From 64aac672363c98234b408e4afd2f0d2f0db44aae Mon Sep 17 00:00:00 2001 From: Chris Lloyd Date: Mon, 11 Oct 2021 19:12:08 +0100 Subject: [PATCH 01/31] PHP 8.0, 8.1, PHPUnit 9 support --- .github/workflows/tests.yml | 26 +-- .gitignore | 1 + composer.json | 4 +- phpunit.xml.dist | 53 +++--- src/MockHandler.php | 2 +- tests/AbstractConfigurationProviderTest.php | 7 +- tests/Api/ApiProviderTest.php | 17 +- tests/Api/ErrorParser/XmlErrorParserTest.php | 2 + tests/Api/ListShapeTest.php | 7 +- tests/Api/MapShapeTest.php | 7 +- tests/Api/OperationTest.php | 7 +- tests/Api/Parser/ComplianceTest.php | 1 + .../Api/Parser/Crc32ValidatingParserTest.php | 5 +- .../DecodingEventStreamIteratorTest.php | 8 +- tests/Api/Parser/EventParsingIteratorTest.php | 17 +- tests/Api/Parser/JsonParserTest.php | 4 +- tests/Api/Parser/JsonRpcParserTest.php | 1 + tests/Api/Parser/XmlParserTest.php | 4 +- tests/Api/Serializer/ComplianceTest.php | 1 + .../Api/Serializer/RestJsonSerializerTest.php | 6 +- .../Api/Serializer/RestXmlSerializerTest.php | 4 +- tests/Api/ServiceTest.php | 14 +- tests/Api/ShapeMapTest.php | 7 +- tests/Api/ShapeTest.php | 13 +- tests/Api/StructureShapeTest.php | 9 +- tests/Api/TimestampShapeTest.php | 11 +- tests/Api/ValidatorTest.php | 13 +- tests/AwsClientTest.php | 52 ++--- .../Build/Changelog/ChangelogBuilderTest.php | 14 +- tests/Build/Changelog/CurrentChangesTest.php | 2 + tests/ClientResolverTest.php | 72 ++++--- .../ConfigurationProviderTest.php | 34 ++-- .../ConfigurationTest.php | 6 +- .../MonitoringMiddlewareTestingTrait.php | 5 +- tests/CloudFront/CloudFrontClientTest.php | 41 ++-- tests/CloudFront/CookieSignerTest.php | 42 ++--- tests/CloudFront/SignerTest.php | 33 ++-- tests/CloudFront/UrlSignerTest.php | 98 +++++----- tests/CloudFront/fixtures/test2.pem | 27 +++ .../CloudSearchDomainTest.php | 7 +- tests/CloudTrail/LogFileIteratorTest.php | 10 +- .../CognitoIdentityProviderTest.php | 3 + tests/CognitoSync/CognitoSyncClientTest.php | 4 +- tests/CommandPoolTest.php | 14 +- .../AssumeRoleCredentialProviderTest.php | 14 +- ...eWithWebIdentityCredentialProviderTest.php | 58 +++--- tests/Credentials/CredentialProviderTest.php | 178 +++++++----------- .../Credentials/EcsCredentialProviderTest.php | 20 +- .../InstanceProfileProviderTest.php | 23 +-- tests/Crypto/AesDecryptingStreamTest.php | 6 +- tests/Crypto/AesEncryptingStreamTest.php | 5 +- tests/Crypto/AesGcmDecryptingStreamTest.php | 6 +- tests/Crypto/AesGcmEncryptingStreamTest.php | 4 +- tests/Crypto/Cipher/CbcTest.php | 19 +- tests/Crypto/KmsMaterialsProviderV2Test.php | 26 +-- tests/Crypto/MetadataEnvelopeTest.php | 5 +- tests/Crypto/Polyfill/KeyTest.php | 7 +- tests/DocDb/DocDbClientTest.php | 9 +- tests/DynamoDb/DynamoDbClientTest.php | 2 + tests/DynamoDb/MarshalerTest.php | 11 +- tests/DynamoDb/SessionHandlerTest.php | 2 + .../StandardSessionConnectionTest.php | 10 +- tests/DynamoDb/WriteRequestBatchTest.php | 8 +- tests/Endpoint/EndpointProviderTest.php | 11 +- tests/Endpoint/PartitionTest.php | 10 +- .../ConfigurationProviderTest.php | 37 ++-- tests/EndpointDiscovery/ConfigurationTest.php | 7 +- .../EndpointDiscoveryMiddlewareTest.php | 8 +- tests/EndpointParameterMiddlewareTest.php | 2 +- tests/FunctionsTest.php | 8 +- tests/Glacier/GlacierClientTest.php | 6 +- tests/Glacier/MultipartUploaderTest.php | 4 +- tests/Glacier/TreeHashTest.php | 7 +- tests/Handler/GuzzleV5/HandlerTest.php | 5 +- tests/Handler/GuzzleV5/StreamTest.php | 5 +- tests/Handler/GuzzleV6/HandlerTest.php | 7 +- tests/HandlerListTest.php | 26 +-- tests/HistoryTest.php | 26 +-- tests/IdempotencyTokenMiddlewareTest.php | 5 +- tests/Integ/GuzzleV5HandlerTest.php | 5 +- tests/Integ/GuzzleV6StreamHandlerTest.php | 4 +- tests/JsonCompilerTest.php | 11 +- tests/Lambda/LambdaClientTest.php | 3 + tests/MiddlewareTest.php | 11 +- tests/MockHandlerTest.php | 21 +-- tests/MultiRegionClientTest.php | 9 +- tests/Multipart/AbstractUploaderTest.php | 22 +-- tests/Neptune/NeptuneClientTest.php | 9 +- tests/Polly/PollyClientTest.php | 31 +-- .../Polyfill/PHPUnit4/PHPUnitCompatTrait.php | 131 +++++++++++++ .../Polyfill/PHPUnit5/PHPUnitCompatTrait.php | 119 ++++++++++++ tests/Polyfill/PHPUnit9/ArraySubset.php | 133 +++++++++++++ .../Polyfill/PHPUnit9/PHPUnitCompatTrait.php | 130 +++++++++++++ tests/PresignUrlMiddlewareTest.php | 22 ++- tests/Psr16CacheAdapterTest.php | 5 +- tests/PsrCacheAdapterTest.php | 5 +- tests/Rds/AuthTokenGeneratorTest.php | 51 ++--- tests/Rds/RdsClientTest.php | 11 +- tests/ResultPaginatorTest.php | 2 + tests/ResultTest.php | 5 +- tests/Retry/ConfigurationProviderTest.php | 37 ++-- tests/Retry/ConfigurationTest.php | 15 +- tests/RetryMiddlewareTest.php | 5 +- tests/RetryMiddlewareV2Test.php | 6 +- tests/Route53/RouteClient53Test.php | 13 +- tests/S3/AmbiguousSuccessParserTest.php | 17 +- tests/S3/BatchDeleteTest.php | 12 +- tests/S3/BucketEndpointArnMiddlewareTest.php | 4 +- tests/S3/Crypto/S3EncryptionClientTest.php | 31 ++- tests/S3/Crypto/S3EncryptionClientV2Test.php | 62 +++--- .../S3EncryptionMultipartUploaderTest.php | 5 +- .../S3EncryptionMultipartUploaderV2Test.php | 5 +- .../DeleteMultipleObjectsExceptionTest.php | 5 +- tests/S3/MultipartUploaderTest.php | 13 +- tests/S3/PermanentRedirectMiddlewareTest.php | 11 +- tests/S3/PostObjectTest.php | 4 +- tests/S3/PostObjectV4Test.php | 12 +- .../ConfigurationProviderTest.php | 33 ++-- .../S3/RegionalEndpoint/ConfigurationTest.php | 9 +- .../RetryableMalformedResponseParserTest.php | 9 +- tests/S3/S3ClientTest.php | 110 +++++------ tests/S3/S3EndpointMiddlewareTest.php | 32 ++-- tests/S3/S3MultiRegionClientTest.php | 44 ++--- tests/S3/S3UriParserTest.php | 5 + tests/S3/SSECMiddlewareTest.php | 7 +- tests/S3/StreamWrapperPathStyleTest.php | 126 +++++-------- tests/S3/StreamWrapperTest.php | 134 ++++++------- tests/S3/TransferTest.php | 66 +++---- .../ConfigurationProviderTest.php | 31 ++- tests/S3/UseArnRegion/ConfigurationTest.php | 9 +- tests/S3Control/EndpointArnMiddlewareTest.php | 4 +- tests/SdkTest.php | 7 +- tests/Signature/S3SignatureV4Test.php | 30 +-- tests/Signature/SignatureProviderTest.php | 7 +- tests/Signature/SignatureV4Test.php | 64 ++++--- tests/Sqs/SqsClientTest.php | 27 ++- tests/StreamRequestPayloadMiddlewareTest.php | 8 +- .../ConfigurationProviderTest.php | 37 ++-- .../RegionalEndpoints/ConfigurationTest.php | 9 +- tests/Sts/StsClientTest.php | 17 +- tests/TraceMiddlewareTest.php | 69 +++---- tests/WaiterTest.php | 12 +- tests/WrappedHttpHandlerTest.php | 10 +- tests/bootstrap.php | 23 ++- 144 files changed, 1831 insertions(+), 1407 deletions(-) create mode 100644 tests/CloudFront/fixtures/test2.pem create mode 100644 tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php create mode 100644 tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php create mode 100644 tests/Polyfill/PHPUnit9/ArraySubset.php create mode 100644 tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a4c26098a1..0733ac0d3f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -13,7 +13,7 @@ jobs: strategy: #for each of the following versions of PHP, with and without --prefer-lowest matrix: - php-versions: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4'] + php-versions: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1'] composer-options: ['', '--prefer-lowest'] #set the name for each job name: PHP ${{ matrix.php-versions }} ${{ matrix.composer-options }} @@ -39,28 +39,32 @@ jobs: - name: Validate composer.json and composer.lock run: composer validate - #downgrade to supported php unit and remove incompatible xdebug file if it exists + #remove incompatible xdebug file if it exists - if: ${{ matrix.php-versions == '5.5' }} - name: PHP 5.5 specific setup + name: PHP 5.5 run: | sudo rm -f /etc/php5/cli/conf.d/20-xdebug.ini - composer require --dev --ignore-platform-reqs phpunit/phpunit "4.8.36" - - #downgrade to supported php unit - - if: ${{ matrix.php-versions <= '7.1' && matrix.php-versions > 5.5}} - name: PHP 5.6-7.1 specific setup - run: composer require --dev --ignore-platform-reqs phpunit/phpunit "^5.7.11" #get dependencies - name: Install dependencies run: composer update ${{ matrix.composer-options }} --no-interaction --prefer-source + #php 8.x requirements + - if: ${{ matrix.php-versions >= '8.0' && matrix.composer-options != '' }} + name: PHP 8.x + run: composer require --dev phpunit/phpunit "^9.5" --no-interaction --prefer-source --with-all-dependencies + + #php 8.1 requirements + - if: ${{ matrix.php-versions >= '8.1' && matrix.composer-options != '' }} + name: PHP 8.1 + run: composer require --dev guzzlehttp/guzzle "^7.3" --no-interaction --prefer-source --with-all-dependencies + #run tests - name: Run test suite run: make test #static analysis - - if: ${{ matrix.php-versions >= '7.1' && matrix.php-versions <= 7.4 && matrix.composer-options == '' }} + - if: ${{ matrix.php-versions >= '7.1' && matrix.php-versions < '8.0' && matrix.composer-options == '' }} name: Static analysis run: | composer require --dev nette/neon "^3.0" @@ -76,6 +80,6 @@ jobs: make package #generate code coverage - - if: ${{ matrix.php-versions == '7.1' && matrix.composer-options == '' }} + - if: ${{ (matrix.php-versions == '7.1' || matrix.php-versions == '8.0') && matrix.composer-options == '' }} name: Code coverage run: bash <(curl -s https://codecov.io/bash) diff --git a/.gitignore b/.gitignore index fcd68067cf..3dd71323a3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ test_services.json /Makefile .idea .php_cs.cache +.phpunit.result.cache atlassian-ide-plugin.xml aws-sdk-php.iml .DS_Store diff --git a/composer.json b/composer.json index 0edef0cf89..7f8d03675d 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "ext-dom": "*", "ext-pcntl": "*", "ext-sockets": "*", - "phpunit/phpunit": "^4.8.35 || ^5.6.3", + "phpunit/phpunit": "^4.8.35 || ^5.6.3|^9.5", "behat/behat": "~3.0", "doctrine/cache": "~1.4", "aws/aws-php-sns-message-validator": "~1.0", @@ -40,7 +40,7 @@ "psr/cache": "^1.0", "psr/simple-cache": "^1.0", "paragonie/random_compat": ">= 2", - "sebastian/comparator": "^1.2.3" + "sebastian/comparator": "^1.2.3|^4.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 c6b27adde0..ec6f5ddae3 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,33 +1,24 @@ - - - - - - - - - - - - tests/ - tests/Integ - - - tests/Integ - - - - - - src - - src/data - - - - - - + + + + src + + + src/data + + + + + + + + tests/ + tests/Integ + + + tests/Integ + + + diff --git a/src/MockHandler.php b/src/MockHandler.php index a2c2ba8fa3..61373ad841 100644 --- a/src/MockHandler.php +++ b/src/MockHandler.php @@ -37,7 +37,7 @@ public function __construct( $this->onRejected = $onRejected; if ($resultOrQueue) { - call_user_func_array([$this, 'append'], $resultOrQueue); + call_user_func_array([$this, 'append'], array_values($resultOrQueue)); } } diff --git a/tests/AbstractConfigurationProviderTest.php b/tests/AbstractConfigurationProviderTest.php index 7bfa64c802..8ed3a04275 100644 --- a/tests/AbstractConfigurationProviderTest.php +++ b/tests/AbstractConfigurationProviderTest.php @@ -5,6 +5,7 @@ use Aws\LruArrayCache; use Aws\Result; use Aws\ResultInterface; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -13,6 +14,8 @@ */ class AbstractConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + /** @var \PHPUnit_Framework_MockObject_MockObject */ private $provider; @@ -65,11 +68,9 @@ public function testChainsConfiguration() $this->assertSame($expected, $result); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); call_user_func([$this->provider, 'chain']); } diff --git a/tests/Api/ApiProviderTest.php b/tests/Api/ApiProviderTest.php index c346bb6569..16e98537d4 100644 --- a/tests/Api/ApiProviderTest.php +++ b/tests/Api/ApiProviderTest.php @@ -3,6 +3,7 @@ use Aws\Api\ApiProvider; use Aws\Exception\UnresolvedApiException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ApiProviderTest extends TestCase { + use PHPUnitCompatTrait; + /** * @return ApiProvider; */ @@ -30,7 +33,7 @@ public function testCanResolveProvider() $this->assertEquals($result, ApiProvider::resolve($p, 't', 's', 'v')); $p = function ($a, $b, $c) {return null;}; - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); ApiProvider::resolve($p, 't', 's', 'v'); } @@ -66,15 +69,13 @@ public function testManifestProviderCanLoadData() { $p = $this->getTestApiProvider(); $data = $p('api', 'dynamodb', 'latest'); - $this->assertInternalType('array', $data); + $this->assertIsArray($data); $this->assertArrayHasKey('foo', $data); } - /** - * @expectedException \InvalidArgumentException - */ public function testFilesystemProviderEnsuresDirectoryIsValid() { + $this->expectException(\InvalidArgumentException::class); ApiProvider::filesystem('/path/to/invalid/dir'); } @@ -116,21 +117,21 @@ public function testReturnsWaiterConfigsForLatestCompatibleVersion() public function testThrowsOnBadType() { - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); $p = $this->getTestApiProvider(); ApiProvider::resolve($p, 'foo', 's3', 'latest'); } public function testThrowsOnBadService() { - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); $p = $this->getTestApiProvider(); ApiProvider::resolve($p, 'api', '', 'latest'); } public function testThrowsOnBadVersion() { - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); $p = $this->getTestApiProvider(); ApiProvider::resolve($p, 'api', 'dynamodb', 'derp'); } diff --git a/tests/Api/ErrorParser/XmlErrorParserTest.php b/tests/Api/ErrorParser/XmlErrorParserTest.php index fb6f98a965..6a87c23703 100644 --- a/tests/Api/ErrorParser/XmlErrorParserTest.php +++ b/tests/Api/ErrorParser/XmlErrorParserTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\ErrorParser; use Aws\Api\ErrorParser\XmlErrorParser; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\TestServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -11,6 +12,7 @@ */ class XmlErrorParserTest extends TestCase { + use PHPUnitCompatTrait; use TestServiceTrait; /** diff --git a/tests/Api/ListShapeTest.php b/tests/Api/ListShapeTest.php index 552526c385..a14f702998 100644 --- a/tests/Api/ListShapeTest.php +++ b/tests/Api/ListShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\ListShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ListShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsMember() { $s = new ListShape( @@ -23,11 +26,9 @@ public function testReturnsMember() $this->assertSame('string', $m->getType()); } - /** - * @expectedException \RuntimeException - */ public function testFailsWhenMemberIsMissing() { + $this->expectException(\RuntimeException::class); (new ListShape([], new ShapeMap([])))->getMember(); } } diff --git a/tests/Api/MapShapeTest.php b/tests/Api/MapShapeTest.php index 794dfa13b3..c1c14633fe 100644 --- a/tests/Api/MapShapeTest.php +++ b/tests/Api/MapShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\MapShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class MapShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsValue() { $s = new MapShape(['value' => ['type' => 'string']], new ShapeMap([])); @@ -19,11 +22,9 @@ public function testReturnsValue() $this->assertSame($v, $s->getValue()); } - /** - * @expectedException \RuntimeException - */ public function testFailsWhenValueIsMissing() { + $this->expectException(\RuntimeException::class); (new MapShape([], new ShapeMap([])))->getValue(); } diff --git a/tests/Api/OperationTest.php b/tests/Api/OperationTest.php index 11fc3f9b05..2a0e9f2614 100644 --- a/tests/Api/OperationTest.php +++ b/tests/Api/OperationTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\Operation; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class OperationTest extends TestCase { + use PHPUnitCompatTrait; + public function testCreatesDefaultMethodAndUri() { $o = new Operation([], new ShapeMap([])); @@ -22,7 +25,7 @@ public function testReturnsEmptyShapes() $o = new Operation([], new ShapeMap([])); $this->assertInstanceOf('Aws\Api\Shape', $o->getInput()); $this->assertInstanceOf('Aws\Api\Shape', $o->getOutput()); - $this->assertInternalType('array', $o->getErrors()); + $this->assertIsArray($o->getErrors()); } public function testReturnsInputShape() @@ -60,7 +63,7 @@ public function testReturnsErrorsShapeArray() 'b' => ['type' => 'list'], ])); $e = $o->getErrors(); - $this->assertInternalType('array', $e); + $this->assertIsArray($e); $this->assertInstanceOf('Aws\Api\Shape', $e[0]); $this->assertInstanceOf('Aws\Api\Shape', $e[1]); $this->assertSame('structure', $e[0]->getType()); diff --git a/tests/Api/Parser/ComplianceTest.php b/tests/Api/Parser/ComplianceTest.php index 9e01af5b66..c3a66467c8 100644 --- a/tests/Api/Parser/ComplianceTest.php +++ b/tests/Api/Parser/ComplianceTest.php @@ -22,6 +22,7 @@ class ComplianceTest extends TestCase { use UsesServiceTrait; + /** @doesNotPerformAssertions */ public function testCaseProvider() { $cases = []; diff --git a/tests/Api/Parser/Crc32ValidatingParserTest.php b/tests/Api/Parser/Crc32ValidatingParserTest.php index 25881ee59b..7fbc169176 100644 --- a/tests/Api/Parser/Crc32ValidatingParserTest.php +++ b/tests/Api/Parser/Crc32ValidatingParserTest.php @@ -7,6 +7,7 @@ use Aws\Api\Service; use Aws\Command; use Aws\Exception\AwsException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class Crc32ValidatingParserTest extends TestCase { + use PHPUnitCompatTrait; + private function getWrapped() { $provider = ApiProvider::defaultProvider(); @@ -40,7 +43,7 @@ public function testThrowsWhenMismatch() $wrapped($command, $response); $this->fail(); } catch (AwsException $e) { - $this->assertContains('crc32 mismatch. Expected 123, found 11124959', $e->getMessage()); + $this->assertStringContainsString('crc32 mismatch. Expected 123, found 11124959', $e->getMessage()); $this->assertTrue($e->isConnectionError()); } } diff --git a/tests/Api/Parser/DecodingEventStreamIteratorTest.php b/tests/Api/Parser/DecodingEventStreamIteratorTest.php index 893dbee4a8..201881458c 100644 --- a/tests/Api/Parser/DecodingEventStreamIteratorTest.php +++ b/tests/Api/Parser/DecodingEventStreamIteratorTest.php @@ -4,6 +4,7 @@ use Aws\Api\Parser\DecodingEventStreamIterator; use Aws\Api\Parser\Exception\ParserException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Stream; use PHPUnit\Framework\TestCase; @@ -13,6 +14,8 @@ */ class DecodingEventStreamIteratorTest extends TestCase { + use PHPUnitCompatTrait; + public function complianceTests() { $cases = []; @@ -130,11 +133,10 @@ public function testPassesComplianceTest( $this->fail('Unsuccessful parse of event from valid source.'); } - $this->assertContains( + $this->assertStringContainsStringIgnoringCase( (string) $decodedData, $e->getMessage(), - '', - true + '' ); } } diff --git a/tests/Api/Parser/EventParsingIteratorTest.php b/tests/Api/Parser/EventParsingIteratorTest.php index f920322e5b..e73a9b35c4 100644 --- a/tests/Api/Parser/EventParsingIteratorTest.php +++ b/tests/Api/Parser/EventParsingIteratorTest.php @@ -9,6 +9,7 @@ use Aws\Api\ShapeMap; use Aws\Api\StructureShape; use Aws\Exception\EventStreamDataException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; @@ -18,6 +19,8 @@ */ class EventParsingIteratorTest extends TestCase { + use PHPUnitCompatTrait; + /** @var array */ private static $successEventNames = [ 'end_event', @@ -29,7 +32,7 @@ class EventParsingIteratorTest extends TestCase /** @var StructureShape */ private $eventstreamShape; - public function setUp() + public function _setUp() { $shape = json_decode( file_get_contents( @@ -131,12 +134,10 @@ public function testThrowsOnErrorEvent() } } - /** - * @expectedException Aws\Api\Parser\Exception\ParserException - * @expectedExceptionMessage Failed to parse unknown message type. - */ public function testThrowsOnUnknownMessageType() { + $this->expectExceptionMessage("Failed to parse unknown message type."); + $this->expectException(\Aws\Api\Parser\Exception\ParserException::class); $stream = Psr7\Utils::streamFor( base64_decode(file_get_contents( __DIR__ . '/../eventstream_fixtures/input/unknown_message_type' @@ -153,12 +154,10 @@ public function testThrowsOnUnknownMessageType() $iterator->current(); } - /** - * @expectedException Aws\Api\Parser\Exception\ParserException - * @expectedExceptionMessage Failed to parse without event type. - */ public function testThrowsOnUnknownEventType() { + $this->expectExceptionMessage("Failed to parse without event type."); + $this->expectException(\Aws\Api\Parser\Exception\ParserException::class); $stream = Psr7\Utils::streamFor( base64_decode(file_get_contents( __DIR__ . '/../eventstream_fixtures/input/unknown_event_type' diff --git a/tests/Api/Parser/JsonParserTest.php b/tests/Api/Parser/JsonParserTest.php index bd8f2fe43b..4368c8b948 100644 --- a/tests/Api/Parser/JsonParserTest.php +++ b/tests/Api/Parser/JsonParserTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,6 +13,7 @@ */ class JsonParserTest extends TestCase { + use PHPUnitCompatTrait; use ParserTestServiceTrait; public function timeStampModelProvider() @@ -119,7 +121,7 @@ public function testTimeStampExceptions( $command = $client->getCommand($commandName); $list = $client->getHandlerList(); $handler = $list->resolve(); - $this->setExpectedException($expectedException, $expectedMessage); + $this->expectException($expectedException, $expectedMessage); $handler($command)->wait(); } } diff --git a/tests/Api/Parser/JsonRpcParserTest.php b/tests/Api/Parser/JsonRpcParserTest.php index d5fa2388c2..38df19c5e8 100644 --- a/tests/Api/Parser/JsonRpcParserTest.php +++ b/tests/Api/Parser/JsonRpcParserTest.php @@ -12,6 +12,7 @@ class JsonRpcParserTest extends TestCase { + /** @doesNotPerformAssertions */ public function testCanHandleNullResponses() { $operation = $this->getMockBuilder(Operation::class) diff --git a/tests/Api/Parser/XmlParserTest.php b/tests/Api/Parser/XmlParserTest.php index 136965835d..ed831ceb70 100644 --- a/tests/Api/Parser/XmlParserTest.php +++ b/tests/Api/Parser/XmlParserTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; ; @@ -14,6 +15,7 @@ */ class XmlParserTest extends TestCase { + use PHPUnitCompatTrait; use ParserTestServiceTrait; public function timeStampModelProvider() @@ -117,7 +119,7 @@ public function testExceptionTimeStamps( $command = $client->getCommand($commandName); $list = $client->getHandlerList(); $handler = $list->resolve(); - $this->setExpectedException($expectedException, $expectedMessage); + $this->expectException($expectedException, $expectedMessage); $handler($command)->wait(); } diff --git a/tests/Api/Serializer/ComplianceTest.php b/tests/Api/Serializer/ComplianceTest.php index 4f1a0e99cb..fc11d15021 100644 --- a/tests/Api/Serializer/ComplianceTest.php +++ b/tests/Api/Serializer/ComplianceTest.php @@ -21,6 +21,7 @@ class ComplianceTest extends TestCase { use UsesServiceTrait; + /** @doesNotPerformAssertions */ public function testCaseProvider() { $cases = []; diff --git a/tests/Api/Serializer/RestJsonSerializerTest.php b/tests/Api/Serializer/RestJsonSerializerTest.php index b53188fc4a..c7c6a02931 100644 --- a/tests/Api/Serializer/RestJsonSerializerTest.php +++ b/tests/Api/Serializer/RestJsonSerializerTest.php @@ -4,6 +4,7 @@ use Aws\Api\Service; use Aws\Command; use Aws\Api\Serializer\RestJsonSerializer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -12,6 +13,7 @@ */ class RestJsonSerializerTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getTestService() @@ -221,11 +223,9 @@ public function testPreparesRequestsWithJsonValueTraitEmptyString() $this->assertSame('', $request->getHeaderLine('Content-Type')); } - /** - * @expectedException \InvalidArgumentException - */ public function testPreparesRequestsWithJsonValueTraitThrowsException() { + $this->expectException(\InvalidArgumentException::class); $obj = new \stdClass(); $obj->obj = $obj; $this->getRequest('foobar', ['baz' => $obj]); diff --git a/tests/Api/Serializer/RestXmlSerializerTest.php b/tests/Api/Serializer/RestXmlSerializerTest.php index da806cf5be..5db0a6e040 100644 --- a/tests/Api/Serializer/RestXmlSerializerTest.php +++ b/tests/Api/Serializer/RestXmlSerializerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\Serializer; use Aws\Api\Serializer\RestXmlSerializer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -10,6 +11,7 @@ */ class RestXmlSerializerTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getRequest($commandName, $input) @@ -42,7 +44,7 @@ public function testEscapesAllXMLCharacters() ], ]); $contents = $request->getBody()->getContents(); - $this->assertContains( + $this->assertStringContainsString( "/@/#/=/;/:/ /,/?/'/"/</>/&/ / /", $contents ); diff --git a/tests/Api/ServiceTest.php b/tests/Api/ServiceTest.php index 0594abd6b5..3458e535ce 100644 --- a/tests/Api/ServiceTest.php +++ b/tests/Api/ServiceTest.php @@ -4,6 +4,7 @@ use Aws\Api\Parser\QueryParser; use Aws\Api\Service; use Aws\Api\StructureShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\TestServiceTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ */ class ServiceTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; use TestServiceTrait; @@ -63,7 +65,7 @@ function () { return []; } public function testReturnsMetadata() { $s = new Service([], function () { return []; }); - $this->assertInternalType('array', $s->getMetadata()); + $this->assertIsArray($s->getMetadata()); $s['metadata'] = [ 'serviceFullName' => 'foo', 'endpointPrefix' => 'bar', @@ -94,11 +96,9 @@ function () { return []; } $this->assertArrayHasKey('foo', $s->getOperations()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresOperationExists() { + $this->expectException(\InvalidArgumentException::class); $s = new Service([], function () { return []; }); $s->getOperation('foo'); } @@ -159,11 +159,9 @@ public function testCreatesRelevantErrorParsers($p, $cl) $this->assertInstanceOf($cl, Service::createErrorParser($p)); } - /** - * @expectedException \UnexpectedValueException - */ public function testThrowsOnUnexpectedProtocol() { + $this->expectException(\UnexpectedValueException::class); Service::createErrorParser('undefined_protocol'); } @@ -180,6 +178,7 @@ public function serializerDataProvider() /** * @dataProvider serializerDataProvider + * @doesNotPerformAssertions */ public function testCreatesSerializer($type, $cl) { @@ -204,6 +203,7 @@ public function parserDataProvider() /** * @dataProvider parserDataProvider + * @doesNotPerformAssertions */ public function testCreatesParsers($type, $cl) { diff --git a/tests/Api/ShapeMapTest.php b/tests/Api/ShapeMapTest.php index a650e3ac69..4bc2ca3e60 100644 --- a/tests/Api/ShapeMapTest.php +++ b/tests/Api/ShapeMapTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api; use Aws\Api\ShapeMap; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,17 +10,17 @@ */ class ShapeMapTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsShapeName() { $sm = new ShapeMap(['foo' => [], 'baz' => []]); $this->assertEquals(['foo', 'baz'], $sm->getShapeNames()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresShapeExists() { + $this->expectException(\InvalidArgumentException::class); $sm = new ShapeMap([]); $sm->resolve(['shape' => 'missing']); } diff --git a/tests/Api/ShapeTest.php b/tests/Api/ShapeTest.php index 13e128e849..b72125d918 100644 --- a/tests/Api/ShapeTest.php +++ b/tests/Api/ShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -11,6 +12,8 @@ */ class ShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testImplementsArray() { $s = new Shape(['metadata' => ['foo' => 'bar']], new ShapeMap([])); @@ -27,11 +30,9 @@ public function testImplementsArray() $this->assertArrayNotHasKey('abc', $s); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesShapeAt() { + $this->expectException(\InvalidArgumentException::class); $s = new Shape([], new ShapeMap([])); $m = new \ReflectionMethod($s, 'shapeAt'); $m->setAccessible(true); @@ -69,12 +70,10 @@ public function testCreatesNestedShapeReferences() $this->assertSame('float', $s->getType()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Invalid type - */ public function testValidatesShapeTypes() { + $this->expectExceptionMessage("Invalid type"); + $this->expectException(\RuntimeException::class); $s = new Shape( ['foo' => ['type' => 'what?']], new ShapeMap([]) diff --git a/tests/Api/StructureShapeTest.php b/tests/Api/StructureShapeTest.php index 8b37fefc45..c92f6f7c32 100644 --- a/tests/Api/StructureShapeTest.php +++ b/tests/Api/StructureShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\StructureShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class StructureShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsWhenMembersAreEmpty() { $s = new StructureShape([], new ShapeMap([])); @@ -36,18 +39,16 @@ public function testReturnsAllMembers() ] ], new ShapeMap([])); $members = $s->getMembers(); - $this->assertInternalType('array', $members); + $this->assertIsArray($members); $this->assertInstanceOf('Aws\Api\Shape', $members['foo']); $this->assertInstanceOf('Aws\Api\Shape', $members['baz']); $this->assertSame('string', $members['foo']->getType()); $this->assertSame('integer', $members['baz']->getType()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresMemberExists() { + $this->expectException(\InvalidArgumentException::class); (new StructureShape([], new ShapeMap([])))->getMember('foo'); } } diff --git a/tests/Api/TimestampShapeTest.php b/tests/Api/TimestampShapeTest.php index 64d757127c..ef4fe70c83 100644 --- a/tests/Api/TimestampShapeTest.php +++ b/tests/Api/TimestampShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\TimestampShape; use Aws\Api\ShapeMap; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class TimestampShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function formatProvider() { $t = strtotime('january 5, 1999'); @@ -35,20 +38,16 @@ public function testFormatsData($value, $format, $result) $this->assertEquals($result, $s->format($value, $format)); } - /** - * @expectedException \UnexpectedValueException - */ public function testValidatesTimestampFormat() { + $this->expectException(\UnexpectedValueException::class); $s = new TimestampShape([], new ShapeMap([])); $s->format('now', 'foo'); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesTimestampValue() { + $this->expectException(\InvalidArgumentException::class); $s = new TimestampShape([], new ShapeMap([])); $s->format(true, 'iso8601'); } diff --git a/tests/Api/ValidatorTest.php b/tests/Api/ValidatorTest.php index 84dc29c249..caa6fec8a2 100644 --- a/tests/Api/ValidatorTest.php +++ b/tests/Api/ValidatorTest.php @@ -4,6 +4,7 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Aws\Api\Validator; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -12,6 +13,8 @@ */ class ValidatorTest extends TestCase { + use PHPUnitCompatTrait; + public function validationProvider() { return [ @@ -619,6 +622,7 @@ public function testValidatesInput($shape, $input, $result) try { $validator->validate('Foo', $shape, $input); + $this->expectNotToPerformAssertions(); if ($result !== true) { $this->fail('Should have failed with ' . $result); } @@ -631,12 +635,10 @@ public function testValidatesInput($shape, $input, $result) } } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage expected string length to be >= 1, but found string length of 0 - */ public function testValidatesMinByDefault() { + $this->expectExceptionMessage("expected string length to be >= 1, but found string length of 0"); + $this->expectException(\InvalidArgumentException::class); $shape = Shape::create( [ 'type' => 'structure', @@ -648,6 +650,7 @@ public function testValidatesMinByDefault() $validator->validate('Foo', $shape, ['foo' => '']); } + /** @doesNotPerformAssertions */ public function testDoesNotValidateMaxByDefault() { $shape = Shape::create( @@ -661,6 +664,7 @@ public function testDoesNotValidateMaxByDefault() $validator->validate('Foo', $shape, ['foo' => '1234567890']); } + /** @doesNotPerformAssertions */ public function testDoesNotValidatePatternsByDefault() { $validator = new Validator(); @@ -679,6 +683,7 @@ public function testDoesNotValidatePatternsByDefault() $validator->validate('Foo', $shape, ['caps' => 'abc']); } + /** @doesNotPerformAssertions */ public function testCanDisableRequiredTrait() { $validator = new Validator(['required' => false]); diff --git a/tests/AwsClientTest.php b/tests/AwsClientTest.php index 4a37aa0f04..510ef8d2a7 100644 --- a/tests/AwsClientTest.php +++ b/tests/AwsClientTest.php @@ -15,6 +15,7 @@ use Aws\S3\S3Client; use Aws\Signature\SignatureV4; use Aws\Sts\StsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\WrappedHttpHandler; use GuzzleHttp\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; @@ -25,6 +26,7 @@ */ class AwsClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getApiProvider() @@ -61,12 +63,10 @@ public function testHasGetters() $this->assertSame('foo', $client->getApi()->getEndpointPrefix()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Operation not found: Foo - */ public function testEnsuresOperationIsFoundWhenCreatingCommands() { + $this->expectExceptionMessage("Operation not found: Foo"); + $this->expectException(\InvalidArgumentException::class); $this->createClient()->getCommand('foo'); } @@ -86,12 +86,10 @@ public function testReturnsCommandForOperation() ); } - /** - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage Error executing "foo" on "http://us-east-1.foo.amazonaws.com"; AWS HTTP error: Baz Bar! - */ public function testWrapsExceptions() { + $this->expectExceptionMessage("Error executing \"foo\" on \"http://us-east-1.foo.amazonaws.com\"; AWS HTTP error: Baz Bar!"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $parser = function () {}; $errorParser = new JsonRpcErrorParser(); $h = new WrappedHttpHandler( @@ -163,11 +161,9 @@ public function testCanGetIteratorWithoutFullyDefinedPaginator() } } - /** - * @expectedException \UnexpectedValueException - */ public function testGetIteratorFailsForMissingConfig() { + $this->expectException(\UnexpectedValueException::class); $client = $this->createClient(); $client->getIterator('ListObjects'); } @@ -187,21 +183,17 @@ public function testCanGetPaginator() ); } - /** - * @expectedException \UnexpectedValueException - */ public function testGetPaginatorFailsForMissingConfig() { + $this->expectException(\UnexpectedValueException::class); $client = $this->createClient(); $client->getPaginator('ListObjects'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Operation not found - */ public function testCanWaitSynchronously() { + $this->expectExceptionMessage("Operation not found"); + $this->expectException(\InvalidArgumentException::class); $client = $this->createClient(['waiters' => ['PigsFly' => [ 'acceptors' => [], 'delay' => 1, @@ -212,11 +204,9 @@ public function testCanWaitSynchronously() $client->waitUntil('PigsFly'); } - /** - * @expectedException \UnexpectedValueException - */ public function testGetWaiterFailsForMissingConfig() { + $this->expectException(\UnexpectedValueException::class); $client = $this->createClient(); $client->waitUntil('PigsFly'); } @@ -269,9 +259,10 @@ public function testSignsRequestsUsingSigner() $client->describeInstances(); $request = $mock->getLastRequest(); $str = \GuzzleHttp\Psr7\Message::toString($request); - $this->assertContains('AWS4-HMAC-SHA256', $str); + $this->assertStringContainsString('AWS4-HMAC-SHA256', $str); } + /** @doesNotPerformAssertions */ public function testAllowsFactoryMethodForBc() { Ec2Client::factory([ @@ -280,6 +271,7 @@ public function testAllowsFactoryMethodForBc() ]); } + /** @doesNotPerformAssertions */ public function testCanInstantiateAliasedClients() { new SesClient([ @@ -294,15 +286,13 @@ public function testCanGetSignatureProvider() $ref = new \ReflectionMethod($client, 'getSignatureProvider'); $ref->setAccessible(true); $provider = $ref->invoke($client); - $this->assertInternalType('callable', $provider); + $this->assertIsCallable($provider); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Instances of Aws\AwsClient cannot be serialized - */ public function testDoesNotPermitSerialization() { + $this->expectExceptionMessage("Instances of Aws\AwsClient cannot be serialized"); + $this->expectException(\RuntimeException::class); $client = $this->createClient(); \serialize($client); } @@ -395,7 +385,7 @@ public function testUsesCommandContextSigningRegionAndService() CommandInterface $command, RequestInterface $request ) { - $this->assertContains('ap-southeast-1/custom-service', $request->getHeader('Authorization')[0]); + $this->assertStringContainsString('ap-southeast-1/custom-service', $request->getHeader('Authorization')[0]); return new Result; } ] @@ -436,12 +426,10 @@ public function testLoadsAliases() ); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Operation not found: GetConfig - */ public function testCallsAliasedFunction() { + $this->expectExceptionMessage("Operation not found: GetConfig"); + $this->expectException(\InvalidArgumentException::class); $client = $this->createClient([ 'metadata' => [ 'serviceId' => 'TestService', diff --git a/tests/Build/Changelog/ChangelogBuilderTest.php b/tests/Build/Changelog/ChangelogBuilderTest.php index 737222b5a4..3ddf1936d8 100644 --- a/tests/Build/Changelog/ChangelogBuilderTest.php +++ b/tests/Build/Changelog/ChangelogBuilderTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Build\Changelog; use Aws\Build\Changelog\ChangelogBuilder; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,25 +10,22 @@ */ class ChangelogBuilderTest extends TestCase { + use PHPUnitCompatTrait; private $RESOURCE_DIR = "tests/Build/Changelog/resources/"; - /** - * @expectedException \InvalidArgumentException - */ public function testBuildChangelogNoDirectory() { + $this->expectException(\InvalidArgumentException::class); $params = []; $params['base_dir'] = 'wrong-folder'; $obj = new ChangelogBuilder($params); $obj->buildChangelog(); } - /** - * @expectedException \InvalidArgumentException - */ public function testBuildChangelogNoReleaseNotes() { + $this->expectException(\InvalidArgumentException::class); $tempDir = sys_get_temp_dir() . "/"; if (!file_exists($tempDir . "/.changes/nextrelease/")) { mkdir($tempDir . "/.changes/nextrelease/", 0777, true); @@ -40,11 +38,9 @@ public function testBuildChangelogNoReleaseNotes() unlink($tempDir . "/.changes/nextrelease/"); } - /** - * @expectedException \InvalidArgumentException - */ public function testBuildChangelogInvalidChangelog() { + $this->expectException(\InvalidArgumentException::class); $params = []; $params['base_dir'] = $this->RESOURCE_DIR; $params['release_notes_output_dir'] = sys_get_temp_dir() . "/"; diff --git a/tests/Build/Changelog/CurrentChangesTest.php b/tests/Build/Changelog/CurrentChangesTest.php index 828d631e28..d83f1954dc 100644 --- a/tests/Build/Changelog/CurrentChangesTest.php +++ b/tests/Build/Changelog/CurrentChangesTest.php @@ -12,6 +12,7 @@ private function getNameFromFilePath($filePath) return end($portions); } + /** @doesNotPerformAssertions */ public function testVerifyDotChangesFolder() { $files = glob(__DIR__ . '/../../../.changes/*'); @@ -30,6 +31,7 @@ public function testVerifyDotChangesFolder() } } + /** @doesNotPerformAssertions */ public function testVerifyNextreleaseContents() { if (!is_dir(__DIR__ . '/../../../.changes/nextrelease/')) { diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index f3a377cd26..7d96eda0b6 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -16,6 +16,7 @@ use Aws\HandlerList; use Aws\Sdk; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -24,18 +25,18 @@ */ class ClientResolverTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required client configuration options - */ public function testEnsuresRequiredArgumentsAreProvided() { + $this->expectExceptionMessage("Missing required client configuration options"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver(ClientResolver::getDefaultArguments()); $r->resolve([], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testAddsValidationSubscriber() { $c = new DynamoDbClient([ @@ -50,6 +51,7 @@ public function testAddsValidationSubscriber() } catch (\InvalidArgumentException $e) {} } + /** @doesNotPerformAssertions */ public function testCanDisableValidation() { $c = new DynamoDbClient([ @@ -63,6 +65,7 @@ public function testCanDisableValidation() $c->execute($command); } + /** @doesNotPerformAssertions */ public function testCanDisableSpecificValidationConstraints() { $c = new DynamoDbClient([ @@ -161,12 +164,10 @@ public function testPrefersApiProviderNameToPartitionName() $this->assertSame($conf['config']['signing_name'], $signingName); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid configuration value provided for "foo". Expected string, but got int(-1) - */ public function testValidatesInput() { + $this->expectExceptionMessage("Invalid configuration value provided for \"foo\". Expected string, but got int(-1)"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver([ 'foo' => [ 'type' => 'value', @@ -176,12 +177,10 @@ public function testValidatesInput() $r->resolve(['foo' => -1], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid configuration value provided for "foo". Expected callable, but got string(1) "c" - */ public function testValidatesCallables() { + $this->expectExceptionMessage("Invalid configuration value provided for \"foo\". Expected callable, but got string(1) \"c\""); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver([ 'foo' => [ 'type' => 'value', @@ -206,14 +205,14 @@ public function testValidatesCallableClosure() $this->assertSame('callable_test', $res['foo']); } - public function checkCallable() + public static function checkCallable() { return "testcall"; } public function testValidatesNotInvokeStringCallable() { - $callableFunction = '\Aws\test\ClientResolverTest::checkCallable'; + $callableFunction = '\Aws\Test\ClientResolverTest::checkCallable'; $r = new ClientResolver([ 'foo' => [ 'type' => 'value', @@ -222,19 +221,17 @@ public function testValidatesNotInvokeStringCallable() ] ]); $res = $r->resolve([], new HandlerList()); - $this->assertInternalType('callable', $callableFunction); + $this->assertIsCallable($callableFunction); $this->assertSame( - '\Aws\test\ClientResolverTest::checkCallable', + '\Aws\Test\ClientResolverTest::checkCallable', $res['foo'] ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Credentials must be an - */ public function testValidatesCredentials() { + $this->expectExceptionMessage("Credentials must be an"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver([ 'credentials' => ClientResolver::getDefaultArguments()['credentials'] ]); @@ -283,6 +280,7 @@ public function testCreatesFromArray() $this->assertSame($exp, $creds->getExpiration()); } + /** @doesNotPerformAssertions */ public function testCanDisableRetries() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -294,6 +292,7 @@ public function testCanDisableRetries() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testCanEnableRetries() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -305,6 +304,7 @@ public function testCanEnableRetries() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testCanEnableRetriesStandardMode() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -319,6 +319,7 @@ public function testCanEnableRetriesStandardMode() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testCanEnableRetriesAdaptivedMode() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -665,6 +666,7 @@ public function s3EndpointCases() ]; } + /** @doesNotPerformAssertions */ public function testAddsLoggerWithDebugSettings() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -677,6 +679,7 @@ public function testAddsLoggerWithDebugSettings() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testAddsDebugListener() { $em = new HandlerList(); @@ -725,6 +728,7 @@ public function testCanAddConfigOptions() $this->assertTrue($c->getConfig('bucket_endpoint')); } + /** @doesNotPerformAssertions */ public function testSkipsNonRequiredKeys() { $r = new ClientResolver([ @@ -736,23 +740,19 @@ public function testSkipsNonRequiredKeys() $r->resolve([], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "version" configuration value is required - */ public function testHasSpecificMessageForMissingVersion() { + $this->expectExceptionMessage("A \"version\" configuration value is required"); + $this->expectException(\InvalidArgumentException::class); $args = ClientResolver::getDefaultArguments()['version']; $r = new ClientResolver(['version' => $args]); $r->resolve(['service' => 'foo'], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "version" configuration value is required - */ public function testHasSpecificMessageForNullRequiredVersion() { + $this->expectExceptionMessage("A \"version\" configuration value is required"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver(ClientResolver::getDefaultArguments()); $list = new HandlerList(); $r->resolve([ @@ -763,23 +763,19 @@ public function testHasSpecificMessageForNullRequiredVersion() ], $list); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "region" configuration value is required for the "foo" service - */ public function testHasSpecificMessageForMissingRegion() { + $this->expectExceptionMessage("A \"region\" configuration value is required for the \"foo\" service"); + $this->expectException(\InvalidArgumentException::class); $args = ClientResolver::getDefaultArguments()['region']; $r = new ClientResolver(['region' => $args]); $r->resolve(['service' => 'foo'], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "region" configuration value is required for the "foo" service - */ public function testHasSpecificMessageForNullRequiredRegion() { + $this->expectExceptionMessage("A \"region\" configuration value is required for the \"foo\" service"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver(ClientResolver::getDefaultArguments()); $list = new HandlerList(); $r->resolve([ @@ -802,7 +798,7 @@ public function testAddsTraceMiddleware() 'debug' => ['logfn' => function ($value) use (&$str) { $str .= $value; }] ], $list); $value = $this->readAttribute($list, 'interposeFn'); - $this->assertInternalType('callable', $value); + $this->assertIsCallable($value); } public function testAppliesUserAgent() @@ -817,7 +813,7 @@ public function testAppliesUserAgent() 'ua_append' => 'PHPUnit/Unit', ], $list); $this->assertArrayHasKey('ua_append', $conf); - $this->assertInternalType('array', $conf['ua_append']); + $this->assertIsArray($conf['ua_append']); $this->assertContains('PHPUnit/Unit', $conf['ua_append']); $this->assertContains('aws-sdk-php/' . Sdk::VERSION, $conf['ua_append']); } diff --git a/tests/ClientSideMonitoring/ConfigurationProviderTest.php b/tests/ClientSideMonitoring/ConfigurationProviderTest.php index 5151ccf1ae..73f37683bb 100644 --- a/tests/ClientSideMonitoring/ConfigurationProviderTest.php +++ b/tests/ClientSideMonitoring/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\ClientSideMonitoring\ConfigurationProvider; use Aws\ClientSideMonitoring\Exception\ConfigurationException; use Aws\LruArrayCache; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -16,6 +17,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENABLED) ?: '', @@ -75,7 +78,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENABLED . '=' . self::$originalEnv['enabled']); @@ -235,21 +238,17 @@ public function testCreatesWithDefaultsFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[aws_csm]"; file_put_contents($dir . '/config', $ini); @@ -263,12 +262,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -281,12 +278,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -479,12 +474,11 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ConfigurationProvider::unwrap($toUnwrap)->toArray() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid CSM configuration argument. - */ + public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid CSM configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/ClientSideMonitoring/ConfigurationTest.php b/tests/ClientSideMonitoring/ConfigurationTest.php index 1e6b1d4e70..c2db64036a 100644 --- a/tests/ClientSideMonitoring/ConfigurationTest.php +++ b/tests/ClientSideMonitoring/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\ClientSideMonitoring; use Aws\ClientSideMonitoring\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Log\InvalidArgumentException; @@ -12,6 +13,7 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; public function testGetsCorrectValues() { @@ -34,11 +36,9 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException InvalidArgumentException - */ public function testHandlesInvalidPort() { + $this->expectException(\InvalidArgumentException::class); new Configuration(true, 'invalidport', 'FooApp'); } diff --git a/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php b/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php index 2d3cf4b0ed..1739d4c2b5 100644 --- a/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php +++ b/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php @@ -5,10 +5,13 @@ use Aws\HandlerList; use Aws\MonitoringEventsInterface; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; trait MonitoringMiddlewareTestingTrait { + use PHPUnitCompatTrait; + /** * @dataProvider getMonitoringDataTests */ @@ -67,6 +70,6 @@ public function testPopulatesMonitoringData( $this->assertTrue($called); $this->assertArraySubset($expected, $eventData); - $this->assertInternalType('int', $eventData['Timestamp']); + $this->assertIsInt($eventData['Timestamp']); } } \ No newline at end of file diff --git a/tests/CloudFront/CloudFrontClientTest.php b/tests/CloudFront/CloudFrontClientTest.php index 6145956b5f..4ab56beea1 100644 --- a/tests/CloudFront/CloudFrontClientTest.php +++ b/tests/CloudFront/CloudFrontClientTest.php @@ -1,7 +1,9 @@ key = realpath(__DIR__.'/fixtures/test2.pem'); + $this->kp = 'test'; + } + public function testEnsuresKeysArePassed() { + $this->expectException(\InvalidArgumentException::class); $c = new CloudFrontClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -21,45 +32,33 @@ public function testEnsuresKeysArePassed() $c->getSignedUrl([]); } + /** @doesNotPerformAssertions */ public function testCreatesSignedUrl() { - foreach (['CF_PRIVATE_KEY', 'CF_KEY_PAIR_ID'] as $k) { - if (!isset($_SERVER[$k]) || $_SERVER[$k] == 'change_me') { - $this->markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } - $c = new CloudFrontClient([ 'region' => 'us-west-2', 'version' => 'latest' ]); $c->getSignedUrl([ - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $_SERVER['CF_KEY_PAIR_ID'], + 'private_key' => $this->key, + 'key_pair_id' => $this->kp, 'url' => 'https://foo.bar.com', 'expires' => strtotime('+10 minutes'), ]); } + /** @doesNotPerformAssertions */ public function testCreatesSignedCookie() { - foreach (['CF_PRIVATE_KEY', 'CF_KEY_PAIR_ID'] as $k) { - if (!isset($_SERVER[$k]) || $_SERVER[$k] == 'change_me') { - $this->markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } - $c = new CloudFrontClient([ 'region' => 'us-west-2', 'version' => 'latest' ]); $c->getSignedCookie([ - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $_SERVER['CF_KEY_PAIR_ID'], + 'private_key' => $this->key, + 'key_pair_id' => $this->kp, 'url' => 'https://foo.bar.com', 'expires' => strtotime('+10 minutes'), ]); diff --git a/tests/CloudFront/CookieSignerTest.php b/tests/CloudFront/CookieSignerTest.php index ddbdfe3f31..791fcfffa4 100644 --- a/tests/CloudFront/CookieSignerTest.php +++ b/tests/CloudFront/CookieSignerTest.php @@ -3,43 +3,41 @@ use Aws\CloudFront\CookieSigner; use Aws\CloudFront\Policy; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class CookieSignerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + protected $key; + protected $kp; + + public function _setUp() { - foreach (['CF_PRIVATE_KEY', 'CF_KEY_PAIR_ID'] as $k) { - if (!isset($_SERVER[$k]) || $_SERVER[$k] == 'change_me') { - $this->markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } + $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + $this->kp = 'test'; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid or missing URI scheme - */ public function testEnsuresUriSchemeIsPresent() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid or missing URI scheme"); + $this->expectException(\InvalidArgumentException::class); + $s = new CookieSigner('a', $this->key); $s->getSignedCookie('bar.com'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid or missing URI scheme - */ public function testEnsuresUriSchemeIsValid() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid or missing URI scheme"); + $this->expectException(\InvalidArgumentException::class); + $s = new CookieSigner('a', $this->key); $s->getSignedCookie('foo://bar.com', strtotime('+10 minutes')); } public function testAllowsHttpScheme() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie('http://bar.com', strtotime('+10 minutes')); $this->assertNotEmpty($cookie); @@ -47,7 +45,7 @@ public function testAllowsHttpScheme() public function testAllowsHttpsScheme() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie('https://bar.com', strtotime('+10 minutes')); $this->assertNotEmpty($cookie); @@ -55,7 +53,7 @@ public function testAllowsHttpsScheme() public function testAllowsWildcardScheme() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie( 'http*://bar.com/*', null, @@ -67,7 +65,7 @@ public function testAllowsWildcardScheme() public function testReturnsHashWithCookieParameterNamesForCannedPolicy() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie('https://bar.com', strtotime('+10 minutes')); $this->assertArrayHasKey('CloudFront-Signature', $cookie); @@ -78,7 +76,7 @@ public function testReturnsHashWithCookieParameterNamesForCannedPolicy() public function testReturnsHashWithCookieParameterNamesForCustomPolicy() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie( 'http*://bar.com/*', null, diff --git a/tests/CloudFront/SignerTest.php b/tests/CloudFront/SignerTest.php index c3e7354455..7d992a1156 100644 --- a/tests/CloudFront/SignerTest.php +++ b/tests/CloudFront/SignerTest.php @@ -3,17 +3,20 @@ use Aws\CloudFront\Policy; use Aws\CloudFront\Signer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class SignerTest extends TestCase { + use PHPUnitCompatTrait; + /** @var Signer */ private $instance; private $testKeyFile; const PASSPHRASE = "1234"; - public function setUp() + public function _setUp() { $this->testKeyFile =__DIR__ . '/fixtures/test.pem'; $this->instance = new Signer( @@ -25,11 +28,10 @@ public function setUp() /** * Assert that the key variable contents are parsed during construction - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /PK .*Not a real private key/ */ public function testBadPrivateKeyContents() { + $this->expectExceptionMessageMatches("/PK .*Not a real private key/"); + $this->expectException(\InvalidArgumentException::class); $privateKey = "Not a real private key"; $s = new Signer( "not a real keypair id", @@ -39,11 +41,10 @@ public function testBadPrivateKeyContents() { /** * Assert that the key file is parsed during construction - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /PEM .*no start line/ */ public function testBadPrivateKeyPath() { + $this->expectExceptionMessageMatches("/PEM .*no start line/"); + $this->expectException(\InvalidArgumentException::class); $filename = tempnam(sys_get_temp_dir(), 'cloudfront-fake-key'); file_put_contents($filename, "Not a real private key"); try { @@ -56,21 +57,17 @@ public function testBadPrivateKeyPath() { } } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage PK file not found - */ public function testEnsuresPkFileExists() { + $this->expectExceptionMessage("PK file not found"); + $this->expectException(\InvalidArgumentException::class); $s = new Signer('a', 'b'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Either a policy or a resource and an expiration time must be provided. - */ public function testEnsuresExpiresIsSetWhenUsingCannedPolicy() { + $this->expectExceptionMessage("Either a policy or a resource and an expiration time must be provided."); + $this->expectException(\InvalidArgumentException::class); $s = new Signer('a', $this->testKeyFile, self::PASSPHRASE); $s->getSignature('http://foo/bar'); } @@ -103,7 +100,7 @@ public function testReturnsExpiresForCannedPolicies($expires) $signature = $this->instance->getSignature('test.mp4', $expires); $this->assertArrayHasKey('Expires', $signature); - $this->assertInternalType('int', $signature['Expires']); + $this->assertIsInt($signature['Expires']); } public function testReturnsPolicyForCustomPolicies() @@ -134,7 +131,7 @@ public function testSignatureContainsNoForbiddenCharacters() { $signature = $this->instance->getSignature('test.mp4', time() + 1000); - $this->assertNotRegExp('/[\+\=\/]/', $signature['Signature']); + $this->assertDoesNotMatchRegularExpression('/[\+\=\/]/', $signature['Signature']); } public function testPolicyContainsNoForbiddenCharacters() @@ -142,7 +139,7 @@ public function testPolicyContainsNoForbiddenCharacters() $signature = $this->instance ->getSignature(null, null, $this->getCustomPolicy()); - $this->assertNotRegExp('/[\+\=\/]/', $signature['Policy']); + $this->assertDoesNotMatchRegularExpression('/[\+\=\/]/', $signature['Policy']); } /** diff --git a/tests/CloudFront/UrlSignerTest.php b/tests/CloudFront/UrlSignerTest.php index f9933c4d0d..74dbd44b3b 100644 --- a/tests/CloudFront/UrlSignerTest.php +++ b/tests/CloudFront/UrlSignerTest.php @@ -1,8 +1,10 @@ markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } + $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + $this->kp = 'test'; } public function testCreatesUrlSignersForHttp() @@ -28,30 +31,28 @@ public function testCreatesUrlSignersForHttp() 'region' => 'us-west-2', 'version' => 'latest' ]); - $ts = time() + 1000; - $key = $_SERVER['CF_PRIVATE_KEY']; - $kp = $_SERVER['CF_KEY_PAIR_ID']; + $ts = time() + 1000; $url = $client->getSignedUrl([ 'url' => 'http://abc.cloudfront.net/images/image.jpg?color=red', 'expires' => $ts, - 'private_key' => $key, - 'key_pair_id' => $kp + 'private_key' => $this->key, + 'key_pair_id' => $this->kp ]); - $this->assertContains("Key-Pair-Id={$kp}", $url); + $this->assertStringContainsString("Key-Pair-Id={$this->kp}", $url); $this->assertStringStartsWith( "http://abc.cloudfront.net/images/image.jpg?color=red&Expires={$ts}&Signature=", $url ); $urlObject = new Uri($url); - $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); + $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); $signature = $query['Signature']; - $this->assertNotContains('?', $signature); - $this->assertNotContains('=', $signature); - $this->assertNotContains('/', $signature); - $this->assertNotContains('&', $signature); - $this->assertNotContains('+', $signature); + $this->assertStringNotContainsString('?', $signature); + $this->assertStringNotContainsString('=', $signature); + $this->assertStringNotContainsString('/', $signature); + $this->assertStringNotContainsString('&', $signature); + $this->assertStringNotContainsString('+', $signature); } public function testCreatesUrlSignersWithSpecialCharacters() @@ -61,23 +62,21 @@ public function testCreatesUrlSignersWithSpecialCharacters() 'region' => 'us-west-2', 'version' => 'latest' ]); - $ts = time() + 1000; - $key = $_SERVER['CF_PRIVATE_KEY']; - $kp = $_SERVER['CF_KEY_PAIR_ID']; + $ts = time() + 1000; $invalidUri = 'http://abc.cloudfront.net/images/éüàçµñ圌.jpg?query key=query value'; - $uri = new Uri($invalidUri); + $uri = new Uri($invalidUri); $this->assertNotEquals($invalidUri, (string) $uri); $url = $client->getSignedUrl([ 'url' => $invalidUri, 'expires' => $ts, - 'private_key' => $key, - 'key_pair_id' => $kp + 'private_key' => $this->key, + 'key_pair_id' => $this->kp ]); - $this->assertContains("Key-Pair-Id={$kp}", $url); - $this->assertContains((string) $uri, $url); + $this->assertStringContainsString("Key-Pair-Id={$this->kp}", $url); + $this->assertStringContainsString((string) $uri, $url); $this->assertStringStartsWith( "{$uri}&Expires={$ts}&Signature=", $url @@ -91,14 +90,14 @@ public function testCreatesUrlSignersWithCustomPolicy() 'region' => 'us-west-2', 'version' => 'latest' ]); - $url = $client->getSignedUrl(array( - 'url' => 'http://abc.cloudfront.net/images/image.jpg', - 'policy' => '{}', - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $_SERVER['CF_KEY_PAIR_ID'] + $url = $client->getSignedUrl(array( + 'url' => 'http://abc.cloudfront.net/images/image.jpg', + 'policy' => '{}', + 'private_key' => $this->key, + 'key_pair_id' => $this->kp )); $policy = (new Uri($url))->getQuery(); - $this->assertRegExp('/Policy=[0-9a-zA-Z-_~]+/', $policy); + $this->assertMatchesRegularExpression('/Policy=[0-9a-zA-Z-_~]+/', $policy); } public function testCreatesUrlSignersForRtmp() @@ -108,47 +107,42 @@ public function testCreatesUrlSignersForRtmp() 'region' => 'us-west-2', 'version' => 'latest' ]); - $ts = time() + 1000; - $kp = $_SERVER['CF_KEY_PAIR_ID']; - $url = $client->getSignedUrl(array( + $ts = time() + 1000; + $url = $client->getSignedUrl(array( 'url' => 'rtmp://foo.cloudfront.net/test.mp4?a=b', 'expires' => $ts, - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $kp + 'private_key' => $this->key, + 'key_pair_id' => $this->kp )); $this->assertStringStartsWith("test.mp4?a=b&Expires={$ts}&Signature=", $url); - $this->assertContains("Key-Pair-Id={$kp}", $url); + $this->assertStringContainsString("Key-Pair-Id={$this->kp}", $url); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid URI scheme - */ public function testEnsuresUriSchemeIsValid() { - $s = new UrlSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid URI scheme"); + $this->expectException(\InvalidArgumentException::class); + $s = new UrlSigner('a', $this->key); $s->getSignedUrl('foo://bar.com', strtotime('+10 minutes')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid URL: bar.com - */ public function testEnsuresUriSchemeIsPresent() { - $s = new UrlSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid URL: bar.com"); + $this->expectException(\InvalidArgumentException::class); + $s = new UrlSigner('a', $this->key); $s->getSignedUrl('bar.com'); } /** * @dataProvider urlAndResourceProvider * - * @param string $url - * @param string $resource + * @param string $url + * @param string $resource */ public function testIsolatesResourceIUrls($url, $resource) { - $s = new UrlSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new UrlSigner('a', $this->key); $m = new \ReflectionMethod(get_class($s), 'createResource'); $m->setAccessible(true); diff --git a/tests/CloudFront/fixtures/test2.pem b/tests/CloudFront/fixtures/test2.pem new file mode 100644 index 0000000000..0bfb6e4a57 --- /dev/null +++ b/tests/CloudFront/fixtures/test2.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEAxTbyKHzrPyxD91YYgq5R87tt66oX+OjJrMQI9MGp74t/N7+V +4uCGyPc5pXDgMtPO5JNAaEfkxJUosn3/g+0i/xnl7INOLrLRTLbOSBMAZVusLhlR +2l+iXPeFNrxwPxRSoROx5T9r2/rBvSwhUsDUJREPBz2IyUdbq+893QUytIm7DYSJ +NkgJFL7bIXxzQISZmfZ6ocJ1qpKuOsiAZdUu6Eaox8jdalvSqrgKhPhQ85T3HG6L +nlnEwMJAQHauwhVBaTzOybyycfvKVQNlT+JN1JnKQvdbt9lQxYVtLhZ9CEKcY41Q +3Yqyb+1MBl49C4kppYoZ5ZllIRa8sbHGk3gxgQIDAQABAoIBAQCPrwyXOwwaJqIO +HggVjfPfY/sd6/szOkdVPC5aRI8PG89ASrFlbrhEyvqQ8sAlx/PAzRfr4hVmtFXG +Vc5HzAnnWnMN8kyP8XBUOAvqrw1my3eSzpe4Rl0A5sWDr58IFkJtYPAHWkG3L+bf +cLuGkz79EoSkfcye+QJtLg0gbp0WsspfgnRxF0xKQu7H2MWkzppXzWOehxWc6YtJ +LIlBicnAQGOIbX0tghpguYNe/HsOyM5Mh1Q7AzTj6fhISxX8l/zjE5k/d9qPjk2S +hTYKYGTY11FCF6mhnRSt5hCop/N4lS+jR1ld3rbuKUzDMsuJFGKpM+8Vdn82gP7S +SzFBExzBAoGBAOyjSfKlCjojRtQ9G7D7oc11UnwP0tF73IonVoRrYyPub153/Nlc +DMB5YLCHl8u51TtPLpLH9tK+aQKaCpLoKkGxU1IK/pCGIL9JSJzyAkhajNtg/hmh +kWUdTQ9wckb5a+0VBjDPCgx4xk3sKC9fdWcrmETDs/hpJS8qz3v91N9NAoGBANVZ +4fPREN8rYIRABM/r8sd5+bIHrmFxWTb0iumx/B2Uf1z3HNDDOwUNe/WOSbZiMlsz +wK+3OoUygDT+yGvYpF6ZpjWtpPcuyKLxYQzICnISgjsohpwWt33LjGCqDtxuvcNx +JaDrLj+vZJzMr76PD6+z4KydErcAePoMDWZrfqkFAoGAO/elZbgtP05xRJe3zMH3 +3vk8TfQ0mKGq4dfWNPiBxzlFP8toaCzLjnsz5Yh3D0mon78RLmE+S2m1ctNWmqP7 +EWq+kqv2lulmoxMPM7agnXVU/MM3oYcwMU+bl64HR7UthIcvam8NPNveZSDTji3C +ssJ5c/OkR+9dXPacXe+VYoECgYEAuqxAVVKxznJnqo9RJpOuAvcokKrD2yKQCtOA +z+UZUNBjd/YHUmnftBYORdZPjLLymHX5vEU3gN+k6bmbpzEQ8GzDzue2FUjr6BYG +8mX9Lb4gEJ7u2JfPyNNWaiWhhyGmC+FuKRRdjP9rqv41LyiBcxySErYEb/aL40y0 +VM7tLfkCgYEArKYfLKzkJmicUQ7xzRIEM66DEynUEwH5VeTzHBO3Eszgj5w9C7rj +e+dGdUEJ6ie5J6QVLfT7oUCCuKF7Mrhvho8NLeObtzt2URRxQmQQfWH1TSzaarc0 +GQi4IIkGDLJeTow+7N2RB29zNDW6edh7vkoEJwvqIuC4bj4/wsEdfCI= +-----END RSA PRIVATE KEY----- diff --git a/tests/CloudSearchDomain/CloudSearchDomainTest.php b/tests/CloudSearchDomain/CloudSearchDomainTest.php index 9b06f948da..91beb6b851 100644 --- a/tests/CloudSearchDomain/CloudSearchDomainTest.php +++ b/tests/CloudSearchDomain/CloudSearchDomainTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\CloudSearchDomain; use Aws\CloudSearchDomain\CloudSearchDomainClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; @@ -10,11 +11,11 @@ */ class CloudSearchDomainTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - */ + use PHPUnitCompatTrait; + public function testRequiresEndpoint() { + $this->expectException(\InvalidArgumentException::class); new CloudSearchDomainClient([ 'service' => 'cloudsearchdomain', 'version' => 'latest' diff --git a/tests/CloudTrail/LogFileIteratorTest.php b/tests/CloudTrail/LogFileIteratorTest.php index 7faa9f0422..6941e85062 100644 --- a/tests/CloudTrail/LogFileIteratorTest.php +++ b/tests/CloudTrail/LogFileIteratorTest.php @@ -6,6 +6,7 @@ use Aws\CloudTrail\LogFileIterator; use Aws\Result; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; @@ -15,6 +16,7 @@ */ class LogFileIteratorTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testFactoryCanCreateForTrail() @@ -31,11 +33,9 @@ public function testFactoryCanCreateForTrail() $this->assertInstanceOf('Aws\CloudTrail\LogFileIterator', $files); } - /** - * @expectedException \InvalidArgumentException - */ public function testFactoryErrorsOnUnknownBucket() { + $this->expectException(\InvalidArgumentException::class); $s3Client = $this->getMockS3Client(); $cloudTrailClient = CloudTrailClient::factory([ 'credentials' => ['key' => 'foo', 'secret' => 'bar'], @@ -65,11 +65,9 @@ public function testConstructorWorksWithDates() $this->assertInstanceOf('Aws\CloudTrail\LogFileIterator', $files); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorErrorsOnInvalidDate() { + $this->expectException(\InvalidArgumentException::class); $s3Client = $this->getMockS3Client(); new LogFileIterator($s3Client, 'test-bucket', [ LogFileIterator::START_DATE => true, diff --git a/tests/CognitoIdentity/CognitoIdentityProviderTest.php b/tests/CognitoIdentity/CognitoIdentityProviderTest.php index 05114a61c2..7f1125c328 100644 --- a/tests/CognitoIdentity/CognitoIdentityProviderTest.php +++ b/tests/CognitoIdentity/CognitoIdentityProviderTest.php @@ -5,10 +5,13 @@ use Aws\CognitoIdentity\CognitoIdentityProvider; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class CognitoIdentityProviderTest extends TestCase { + use PHPUnitCompatTrait; + public function testCreatesFromCognitoIdentity() { $options = [ diff --git a/tests/CognitoSync/CognitoSyncClientTest.php b/tests/CognitoSync/CognitoSyncClientTest.php index 922443d641..94a2c6d421 100644 --- a/tests/CognitoSync/CognitoSyncClientTest.php +++ b/tests/CognitoSync/CognitoSyncClientTest.php @@ -1,6 +1,7 @@ assertContains( + $this->assertStringContainsString( urlencode($unencodedString), (string) $request->getUri() ); diff --git a/tests/CommandPoolTest.php b/tests/CommandPoolTest.php index 7b022f6921..97b0884280 100644 --- a/tests/CommandPoolTest.php +++ b/tests/CommandPoolTest.php @@ -5,6 +5,7 @@ use Aws\CommandPool; use Aws\Exception\AwsException; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,26 +13,23 @@ */ class CommandPoolTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Each value yielded by the iterator must be an Aws\CommandInterface - */ public function testEnsuresEachIsCommand() { + $this->expectExceptionMessage("Each value yielded by the iterator must be an Aws\CommandInterface"); + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); $iter = ['a']; $pool = new CommandPool($client, $iter); $pool->promise()->wait(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage before must be callable - */ public function testEnsuresBeforeIsCallable() { + $this->expectExceptionMessage("before must be callable"); + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); new CommandPool($client, [], ['before' => 'foo']); } diff --git a/tests/Credentials/AssumeRoleCredentialProviderTest.php b/tests/Credentials/AssumeRoleCredentialProviderTest.php index f70f79646e..2b4e614449 100644 --- a/tests/Credentials/AssumeRoleCredentialProviderTest.php +++ b/tests/Credentials/AssumeRoleCredentialProviderTest.php @@ -7,6 +7,7 @@ use Aws\Result; use Aws\Sts\StsClient; use Aws\Api\DateTimeResult; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\RejectedPromise; use Aws\Test\UsesServiceTrait; @@ -19,17 +20,18 @@ class AssumeRoleCredentialProviderTest extends TestCase { const SAMPLE_ROLE_ARN = 'arn:aws:iam::012345678910:role/role_name'; + use PHPUnitCompatTrait; use UsesServiceTrait; /** * @dataProvider insufficientArguments * * @param array $config - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required 'AssumeRoleCredentialProvider' configuration option: */ public function testEnsureSourceProfileProvidedForAssumeRole($config) { + $this->expectExceptionMessage("Missing required 'AssumeRoleCredentialProvider' configuration option:"); + $this->expectException(\InvalidArgumentException::class); new AssumeRoleCredentialProvider($config); } @@ -90,16 +92,14 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('bar', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error in retrieving assume role credentials. - */ public function testThrowsExceptionWhenRetrievingAssumeRoleCredentialFails() { + $this->expectExceptionMessage("Error in retrieving assume role credentials."); + $this->expectException(\Aws\Exception\CredentialsException::class); $sts = new StsClient([ 'region' => 'us-west-2', 'version' => 'latest', diff --git a/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php b/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php index 3c300c2fbe..583cc9d911 100644 --- a/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php +++ b/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php @@ -9,6 +9,7 @@ use Aws\Sts\StsClient; use Aws\Sts\Exception\StsException; use Aws\Api\DateTimeResult; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\RejectedPromise; use Aws\Test\UsesServiceTrait; @@ -21,6 +22,7 @@ class AssumeRoleWithWebIdentityCredentialProviderTest extends TestCase { const SAMPLE_ROLE_ARN = 'arn:aws:iam::012345678910:role/role_name'; + use PHPUnitCompatTrait; use UsesServiceTrait; private function clearEnv() @@ -35,36 +37,30 @@ private function clearEnv() return $dir; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option: - */ public function testEnsureRoleArnProvidedForAssumeRole() { + $this->expectExceptionMessage("Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option:"); + $this->expectException(\InvalidArgumentException::class); $config = [ 'WebIdentityTokenFile' => '/path/to/token/file', ]; new AssumeRoleWithWebIdentityCredentialProvider($config); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option: - */ public function testEnsureWebIdentityTokenFileProvidedForAssumeRole() { + $this->expectExceptionMessage("Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option:"); + $this->expectException(\InvalidArgumentException::class); $config = [ 'RoleArn' => self::SAMPLE_ROLE_ARN, ]; new AssumeRoleWithWebIdentityCredentialProvider($config); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage 'WebIdentityTokenFile' must be an absolute path. - */ public function testEnsureWebIdentityTokenFileIsAbsolutePath() { + $this->expectExceptionMessage("'WebIdentityTokenFile' must be an absolute path."); + $this->expectException(\InvalidArgumentException::class); $config = [ 'RoleArn' => self::SAMPLE_ROLE_ARN, 'WebIdentityTokenFile' => '..\foo\path' @@ -106,7 +102,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('bar', $creds->getSecretKey()); $this->assertSame('baz', $creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Error $e) { throw $e; @@ -133,7 +129,7 @@ public function testSetsSessionNameWhenNotProvided() $sts = $this->getTestClient('Sts', ['credentials' => false]); $sts->getHandlerList()->setHandler( function ($c, $r) use ($result) { - $this->assertContains('aws-sdk-php-', $c->toArray()['RoleSessionName']); + $this->assertStringContainsString('aws-sdk-php-', $c->toArray()['RoleSessionName']); return Promise\Create::promiseFor(new Result($result)); } ); @@ -146,12 +142,10 @@ function ($c, $r) use ($result) { unlink($tokenPath); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error reading WebIdentityTokenFile - */ public function testThrowsExceptionWhenReadingTokenFileFails() { + $this->expectExceptionMessage("Error reading WebIdentityTokenFile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $args['RoleArn'] = self::SAMPLE_ROLE_ARN; $args['WebIdentityTokenFile'] = '/foo'; $provider = new AssumeRoleWithWebIdentityCredentialProvider($args); @@ -172,18 +166,16 @@ public function testThrowsExceptionWhenEmptyTokenFile() $this->fail("Should have thrown an exception"); } catch (\Exception $e) { self::assertInstanceOf('\Aws\Exception\CredentialsException', $e); - self::assertContains('Error reading WebIdentityTokenFile', $e->getMessage()); + self::assertStringContainsString('Error reading WebIdentityTokenFile', $e->getMessage()); } finally { unlink($tokenPath); } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error assuming role from web identity credentials - */ public function testThrowsExceptionWhenRetrievingAssumeRoleCredentialFails() { + $this->expectExceptionMessage("Error assuming role from web identity credentials"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $sts = new StsClient([ 'region' => 'us-west-2', @@ -216,12 +208,10 @@ public function testThrowsExceptionWhenRetrievingAssumeRoleCredentialFails() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving web identity credentials: Found 1 error while validating the input provided for the AssumeRoleWithWebIdentity operation: - */ public function testThrowsNonAwsExceptionWhenRetrievingAssumeRoleCredentialFails() { + $this->expectExceptionMessage("Error retrieving web identity credentials: Found 1 error while validating the input provided for the AssumeRoleWithWebIdentity operation:"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $sts = new StsClient([ 'region' => 'us-west-2', @@ -294,7 +284,7 @@ public function testRetryInvalidIdentityToken() $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('bar', $creds->getSecretKey()); $this->assertSame('baz', $creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -303,12 +293,10 @@ public function testRetryInvalidIdentityToken() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage InvalidIdentityToken, retries exhausted - */ public function testThrowsExceptionWhenInvalidIdentityTokenRetriesExhausted() { + $this->expectExceptionMessage("InvalidIdentityToken, retries exhausted"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $result = [ 'Credentials' => [ @@ -353,12 +341,10 @@ public function testThrowsExceptionWhenInvalidIdentityTokenRetriesExhausted() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage InvalidIdentityToken, retries exhausted - */ public function testCanDisableInvalidIdentityTokenRetries() { + $this->expectExceptionMessage("InvalidIdentityToken, retries exhausted"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $result = [ 'Credentials' => [ diff --git a/tests/Credentials/CredentialProviderTest.php b/tests/Credentials/CredentialProviderTest.php index d6ce7adbe8..31f0e2e7ee 100644 --- a/tests/Credentials/CredentialProviderTest.php +++ b/tests/Credentials/CredentialProviderTest.php @@ -9,6 +9,7 @@ use Aws\Middleware; use Aws\Result; use Aws\Sts\StsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -28,6 +29,7 @@ class CredentialProviderTest extends TestCase aws_session_token = baz EOT; + use PHPUnitCompatTrait; use UsesServiceTrait; private function clearEnv() @@ -65,7 +67,7 @@ private function clearEnv() return $dir; } - public function setUp() + public function _setUp() { $this->home = getenv('HOME'); $this->homedrive = getenv('HOMEDRIVE'); @@ -75,7 +77,7 @@ public function setUp() $this->profile = getenv(CredentialProvider::ENV_PROFILE); } - public function tearDown() + public function _tearDown() { putenv('HOME=' . $this->home); putenv('HOMEDRIVE=' . $this->homedrive); @@ -264,12 +266,10 @@ public function testUsesIniWithUseAwsConfigFileTrue() unlink($dir . '/credentials'); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credentials from the instance profile metadata service - */ public function testIgnoresIniWithUseAwsConfigFileFalse() { + $this->expectExceptionMessage("Error retrieving credentials from the instance profile metadata service"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/credentials', self::$standardIni); $expectedCreds = [ @@ -287,12 +287,10 @@ public function testIgnoresIniWithUseAwsConfigFileFalse() unlink($dir . '/credentials'); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Invalid credentials file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid credentials file:"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/credentials', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -305,21 +303,17 @@ public function testEnsuresIniFileIsValid() } } - /** - * @expectedException \Aws\Exception\CredentialsException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Exception\CredentialsException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(CredentialProvider::ini())->wait(); } - /** - * @expectedException \Aws\Exception\CredentialsException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = "[default]\naws_access_key_id = foo\n" . "aws_secret_access_key = baz\n[foo]"; @@ -334,12 +328,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/credentials', ''); putenv('HOME=' . dirname($dir)); @@ -484,12 +476,10 @@ public function testCreatesTemporaryFromProcessCredential() $this->assertSame($expires, $creds->getExpiration()); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage No credential_process present in INI profile - */ public function testEnsuresProcessCredentialIsPresent() { + $this->expectExceptionMessage("No credential_process present in INI profile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("credential_process does not return Version == 1"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("credential_process returned expired credentials"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("credential_process returned invalid expiration"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<wait(); $body = (string) $history->getLastRequest()->getBody(); - $this->assertContains('RoleSessionName=foobar', $body); + $this->assertStringContainsString('RoleSessionName=foobar', $body); $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -645,12 +629,10 @@ public function testCreatesFromRoleArn() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Circular source_profile reference found. - */ public function testCreatesFromRoleArnCatchesCircular() { + $this->expectExceptionMessage("Circular source_profile reference found."); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<getLastRequest(); $body = (string) $history->getLastRequest()->getBody(); - $this->assertRegExp('/RoleSessionName=aws-sdk-php-\d{13}/', $body); + $this->assertMatchesRegularExpression('/RoleSessionName=aws-sdk-php-\d{13}/', $body); } catch (\Exception $e) { throw $e; } finally { @@ -727,12 +709,10 @@ public function testSetsRoleSessionNameToDefault() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Role assumption profiles are disabled. Failed to load profile assume - */ public function testEnsuresAssumeRoleCanBeDisabled() { + $this->expectExceptionMessage("Role assumption profiles are disabled. Failed to load profile assume"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("Either source_profile or credential_source must be set using profile assume, but not both"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("A role_arn must be provided with credential_source in"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv(CredentialProvider::ENV_KEY . '=abc'); putenv(CredentialProvider::ENV_SESSION . ''); @@ -819,12 +795,10 @@ public function testAssumeRoleInConfigFromCredentialSourceNoRoleArn() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Could not find environment variable credentials in AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY - */ public function testAssumeRoleInConfigFromFailingCredentialsSource() { + $this->expectExceptionMessage("Could not find environment variable credentials in AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv(CredentialProvider::ENV_KEY . '=abc'); putenv(CredentialProvider::ENV_SESSION . ''); @@ -883,12 +857,10 @@ public function testAssumeRoleInConfigFromCredentialsSourceEnvironment() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credentials from the instance profile metadata service - */ public function testAssumeRoleInConfigFromCredentialsSourceEc2InstanceMetadata() { + $this->expectExceptionMessage("Error retrieving credentials from the instance profile metadata service"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $credentials = <<expectExceptionMessage("Error retrieving credential from ECS"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $credentials = <<expectExceptionMessage("Invalid credential_source found in config file: InvalidSource. Valid inputs include Environment, Ec2InstanceMetadata, and EcsContainer."); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $credentials = <<expectExceptionMessage("Either source_profile or credential_source must be set using profile assume, but not both"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("source_profile default using profile assume does not exist"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("No credentials present in INI profile 'default'"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("must contain an access token and an expiration"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("Profile nonExistingProfile does not exist in"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("Cannot read credentials from"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $filename = $dir . '/config'; @@ -1319,12 +1275,10 @@ public function testSsoProfileProviderBadFile() } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage must contain the following keys: sso_start_url, sso_region, sso_account_id, and sso_role_name - */ public function testSsoProfileProviderMissingData() { + $this->expectExceptionMessage("must contain the following keys: sso_start_url, sso_region, sso_account_id, and sso_role_name"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1436,7 +1390,7 @@ public function testAssumeRoleInCredentialsFromSourceInConfig() $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1486,7 +1440,7 @@ public function testAssumeRoleInConfigFromSourceInCredentials() $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1540,7 +1494,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1592,7 +1546,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1644,7 +1598,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1696,7 +1650,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1706,12 +1660,10 @@ function ($c, $r) use ($result) { } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unknown profile: fooProfile - */ public function testEnsuresAssumeRoleWebIdentityProfileIsPresent() { + $this->expectExceptionMessage("Unknown profile: fooProfile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv('AWS_PROFILE=fooProfile'); @@ -1733,12 +1685,10 @@ public function testEnsuresAssumeRoleWebIdentityProfileIsPresent() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unknown profile: fooProfile - */ public function testEnsuresAssumeRoleWebIdentityProfileInDefaultFiles() { + $this->expectExceptionMessage("Unknown profile: fooProfile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv('AWS_PROFILE=fooProfile'); touch($dir . '/credentials'); diff --git a/tests/Credentials/EcsCredentialProviderTest.php b/tests/Credentials/EcsCredentialProviderTest.php index d761baf9aa..56d9df6390 100644 --- a/tests/Credentials/EcsCredentialProviderTest.php +++ b/tests/Credentials/EcsCredentialProviderTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Credentials; use Aws\Credentials\EcsCredentialProvider; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\ClientInterface; use GuzzleHttp\Client; use GuzzleHttp\Promise; @@ -15,6 +16,8 @@ */ class EcsCredentialProviderTest extends TestCase { + use PHPUnitCompatTrait; + private $uripath; private function clearEnv() @@ -29,26 +32,24 @@ private function clearEnv() unset($_SERVER[EcsCredentialProvider::ENV_AUTH_TOKEN]); } - public function setUp() + public function _setUp() { $this->uripath = getenv(EcsCredentialProvider::ENV_URI); $this->fulluripath = getenv(EcsCredentialProvider::ENV_FULL_URI); $this->authtokenpath = getenv(EcsCredentialProvider::ENV_AUTH_TOKEN); } - public function tearDown() + public function _tearDown() { $this->uripath = getenv(EcsCredentialProvider::ENV_URI); $this->fulluripath = getenv(EcsCredentialProvider::ENV_FULL_URI); $this->authtokenpath = getenv(EcsCredentialProvider::ENV_AUTH_TOKEN); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credential from ECS - */ public function testRejectsIfUriPathIsNotAvailable() { + $this->expectExceptionMessage("Error retrieving credential from ECS"); + $this->expectException(\Aws\Exception\CredentialsException::class); $client = function () use (&$responses) { return Promise\Create::rejectionFor([ 'exception' => new \Exception('error') @@ -58,12 +59,10 @@ public function testRejectsIfUriPathIsNotAvailable() $p()->wait(); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unexpected ECS credential value - */ public function testThrowsExceptionOnInvalidEcsCredential() { + $this->expectExceptionMessage("Unexpected ECS credential value"); + $this->expectException(\Aws\Exception\CredentialsException::class); $this->getTestCreds( $this->getCredentialArray(null, null, null, null, false) )->wait(); @@ -81,6 +80,7 @@ public function testLoadsCredentialsAndProfile() $this->assertSame($t, $c->getExpiration()); } + /** @doesNotPerformAssertions */ public function testDoesNotRequireConfig() { new EcsCredentialProvider(); diff --git a/tests/Credentials/InstanceProfileProviderTest.php b/tests/Credentials/InstanceProfileProviderTest.php index 7711d9cf90..27f7fed545 100644 --- a/tests/Credentials/InstanceProfileProviderTest.php +++ b/tests/Credentials/InstanceProfileProviderTest.php @@ -9,6 +9,7 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\Sdk; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Promise; use GuzzleHttp\Psr7; @@ -22,15 +23,17 @@ */ class InstanceProfileProviderTest extends TestCase { + use PHPUnitCompatTrait; + static $originalFlag; - public static function setUpBeforeClass() + public static function _setUpBeforeClass() { self::$originalFlag = getenv(InstanceProfileProvider::ENV_DISABLE) ?: ''; putenv(InstanceProfileProvider::ENV_DISABLE. '=false'); } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(InstanceProfileProvider::ENV_DISABLE. '=' . self::$originalFlag); } @@ -178,7 +181,7 @@ private function getSecureTestClient( Psr7\Utils::streamFor( json_encode(call_user_func_array( [$this, 'getCredentialArray'], - $creds + array_values($creds) )) ) ) @@ -797,12 +800,10 @@ public function failureTestCases() ]; } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credentials from the instance profile metadata service. (999 Expected Exception) - */ 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(); $getRequest = new $requestClass('GET', '/latest/meta-data/foo'); @@ -899,23 +900,23 @@ public function testSeedsInitialCredentials() $this->assertSame($t, $c->getExpiration()); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unexpected instance profile response - */ public function testThrowsExceptionOnInvalidMetadata() { + $this->expectExceptionMessage("Unexpected instance profile response"); + $this->expectException(\Aws\Exception\CredentialsException::class); $this->getTestCreds( $this->getCredentialArray(null, null, null, null, false), 'foo' )->wait(); } + /** @doesNotPerformAssertions */ public function testDoesNotRequireConfig() { new InstanceProfileProvider(); } + /** @doesNotPerformAssertions */ public function testEnvDisableFlag() { $flag = getenv(InstanceProfileProvider::ENV_DISABLE); diff --git a/tests/Crypto/AesDecryptingStreamTest.php b/tests/Crypto/AesDecryptingStreamTest.php index 382b24deb8..b713c2488b 100644 --- a/tests/Crypto/AesDecryptingStreamTest.php +++ b/tests/Crypto/AesDecryptingStreamTest.php @@ -4,6 +4,7 @@ use Aws\Crypto\AesDecryptingStream; use Aws\Crypto\Cipher\Cbc; use Aws\Crypto\Cipher\CipherMethod; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ class AesDecryptingStreamTest extends TestCase const KB = 1024; const MB = 1048576; + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** @@ -142,11 +144,9 @@ public function testIsNotWritable() $this->assertFalse($stream->isWritable()); } - /** - * @expectedException \LogicException - */ public function testDoesNotSupportArbitrarySeeking() { + $this->expectException(\LogicException::class); $stream = new AesDecryptingStream( new RandomByteStream(124 * self::MB), 'foo', diff --git a/tests/Crypto/AesEncryptingStreamTest.php b/tests/Crypto/AesEncryptingStreamTest.php index 3001c2c8c7..ecf406c745 100644 --- a/tests/Crypto/AesEncryptingStreamTest.php +++ b/tests/Crypto/AesEncryptingStreamTest.php @@ -5,6 +5,7 @@ use Aws\Crypto\AesEncryptingStream; use Aws\Crypto\Cipher\Cbc; use Aws\Crypto\Cipher\CipherMethod; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; @@ -14,6 +15,7 @@ class AesEncryptingStreamTest extends TestCase const KB = 1024; const MB = 1048576; + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** @@ -172,11 +174,10 @@ public function testReturnsPaddedOrEmptyStringWhenSourceStreamEmpty( * @dataProvider cipherMethodProvider * * @param CipherMethod $cipherMethod - * - * @expectedException \LogicException */ public function testDoesNotSupportSeekingFromEnd(CipherMethod $cipherMethod) { + $this->expectException(\LogicException::class); $stream = new AesEncryptingStream(Psr7\Utils::streamFor('foo'), 'foo', $cipherMethod); $stream->seek(1, SEEK_END); diff --git a/tests/Crypto/AesGcmDecryptingStreamTest.php b/tests/Crypto/AesGcmDecryptingStreamTest.php index eaa9199281..11b1bbdead 100644 --- a/tests/Crypto/AesGcmDecryptingStreamTest.php +++ b/tests/Crypto/AesGcmDecryptingStreamTest.php @@ -2,12 +2,14 @@ namespace Aws\Test\Crypto; use Aws\Crypto\AesGcmDecryptingStream; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; class AesGcmDecryptingStreamTest extends TestCase { + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** @@ -61,8 +63,6 @@ public function testStreamOutputSameAsOpenSSL( /** * @dataProvider cartesianJoinInputKeySizeProvider - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object could not be decrypted due to an invalid authentication tag * * @param StreamInterface $plainText * @param int $keySize @@ -71,6 +71,8 @@ public function testThrowsForInvalidTag( StreamInterface $plainText, $keySize ) { + $this->expectExceptionMessage("The requested object could not be decrypted due to an invalid authentication tag"); + $this->expectException(\Aws\Exception\CryptoException::class); if (version_compare(PHP_VERSION, '7.1', '<')) { $this->markTestSkipped( 'AES-GCM decryption is only supported in PHP 7.1 or greater' diff --git a/tests/Crypto/AesGcmEncryptingStreamTest.php b/tests/Crypto/AesGcmEncryptingStreamTest.php index eefe3a8a93..0a03fa1ecd 100644 --- a/tests/Crypto/AesGcmEncryptingStreamTest.php +++ b/tests/Crypto/AesGcmEncryptingStreamTest.php @@ -2,15 +2,17 @@ namespace Aws\Test\Crypto; use Aws\Crypto\AesGcmEncryptingStream; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; class AesGcmEncryptingStreamTest extends TestCase { + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; - protected function setUp() + protected function _setUp() { if (version_compare(PHP_VERSION, '7.1', '<')) { $this->markTestSkipped( diff --git a/tests/Crypto/Cipher/CbcTest.php b/tests/Crypto/Cipher/CbcTest.php index c9786d87e6..79d252c763 100644 --- a/tests/Crypto/Cipher/CbcTest.php +++ b/tests/Crypto/Cipher/CbcTest.php @@ -2,10 +2,13 @@ namespace Aws\Test\Crypto\Cipher; use Aws\Crypto\Cipher\Cbc; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class CbcTest extends TestCase { + use PHPUnitCompatTrait; + public function testShouldReportCipherMethodOfCBC() { $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); @@ -35,11 +38,9 @@ public function testUpdateShouldSetCurrentIvToEndOfCipherBlock() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testShouldThrowWhenIvOfInvalidLengthProvided() { + $this->expectException(\InvalidArgumentException::class); new Cbc(openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc') + 1)); } @@ -54,11 +55,9 @@ public function testShouldSupportSeekingToBeginning() $this->assertSame($ivString, $iv->getCurrentIv()); } - /** - * @expectedException \LogicException - */ public function testShouldThrowWhenNonZeroOffsetProvidedToSeek() { + $this->expectException(\LogicException::class); $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $iv = new Cbc($ivString); $cipherTextBlock = openssl_random_pseudo_bytes(1024); @@ -67,11 +66,9 @@ public function testShouldThrowWhenNonZeroOffsetProvidedToSeek() $iv->seek(1); } - /** - * @expectedException \LogicException - */ public function testShouldThrowWhenSeekCurProvidedToSeek() { + $this->expectException(\LogicException::class); $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $iv = new Cbc($ivString); $cipherTextBlock = openssl_random_pseudo_bytes(1024); @@ -80,11 +77,9 @@ public function testShouldThrowWhenSeekCurProvidedToSeek() $iv->seek(0, SEEK_CUR); } - /** - * @expectedException \LogicException - */ public function testShouldThrowWhenSeekEndProvidedToSeek() { + $this->expectException(\LogicException::class); $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $iv = new Cbc($ivString); $cipherTextBlock = openssl_random_pseudo_bytes(1024); diff --git a/tests/Crypto/KmsMaterialsProviderV2Test.php b/tests/Crypto/KmsMaterialsProviderV2Test.php index 4dad52c9d1..4c8c90bf60 100644 --- a/tests/Crypto/KmsMaterialsProviderV2Test.php +++ b/tests/Crypto/KmsMaterialsProviderV2Test.php @@ -5,6 +5,7 @@ use Aws\Kms\KmsClient; use Aws\Middleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ */ class KmsMaterialsProviderV2Test extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testProviderBasics() @@ -83,12 +85,10 @@ public function testGeneratesCek() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage A KMS key id is required for encryption with KMS keywrap - */ public function testGenerateThrowsForNoKmsId() { + $this->expectExceptionMessage("A KMS key id is required for encryption with KMS keywrap"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client); @@ -105,12 +105,10 @@ public function testGenerateThrowsForNoKmsId() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage '@KmsEncryptionContext' is a required argument when using KmsMaterialsProviderV2 - */ public function testGenerateThrowsForNoEncryptionContext() { + $this->expectExceptionMessage("'@KmsEncryptionContext' is a required argument when using KmsMaterialsProviderV2"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client, 'foo'); @@ -123,12 +121,10 @@ public function testGenerateThrowsForNoEncryptionContext() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage Conflict in reserved @KmsEncryptionContext key aws:x-amz-cek-alg - */ public function testGenerateThrowsForContextConflict() { + $this->expectExceptionMessage("Conflict in reserved @KmsEncryptionContext key aws:x-amz-cek-alg"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client, 'foo'); @@ -182,12 +178,10 @@ public function testDecryptCek() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage KMS CMK ID was not specified and the operation is not opted-in to attempting to use any valid CMK - */ public function testDecryptCekThrowsForNoKmsId() { + $this->expectExceptionMessage("KMS CMK ID was not specified and the operation is not opted-in to attempting to use any valid CMK"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client); diff --git a/tests/Crypto/MetadataEnvelopeTest.php b/tests/Crypto/MetadataEnvelopeTest.php index eb19d45af7..95d1c5127d 100644 --- a/tests/Crypto/MetadataEnvelopeTest.php +++ b/tests/Crypto/MetadataEnvelopeTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Crypto; use Aws\Crypto\MetadataEnvelope; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,7 @@ */ class MetadataEnvelopeTest extends TestCase { + use PHPUnitCompatTrait; use UsesMetadataEnvelopeTrait; /** @@ -40,11 +42,10 @@ public function testSetsAllFields($allValidFields) /** * @dataProvider getIndividualInvalidMetadataFields - * - * @expectedException \InvalidArgumentException */ public function testThrowsOnInvalidMetadataField($field, $value) { + $this->expectException(\InvalidArgumentException::class); $envelope = new MetadataEnvelope(); $envelope[$field] = $value; } diff --git a/tests/Crypto/Polyfill/KeyTest.php b/tests/Crypto/Polyfill/KeyTest.php index 74afd1e5e5..b05424804c 100644 --- a/tests/Crypto/Polyfill/KeyTest.php +++ b/tests/Crypto/Polyfill/KeyTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Crypto\Polyfill; use Aws\Crypto\Polyfill\Key; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class KeyTest extends TestCase { + use PHPUnitCompatTrait; + public function testConstructor() { $this->assertInstanceOf(Key::class, new Key('test')); @@ -26,7 +29,7 @@ public function testDebugInfo() ob_start(); var_dump($key); $output = ob_get_clean(); - $this->assertNotContains($test, $output, 'debugInfo() did not suppress output'); + $this->assertStringNotContainsString($test, $output, 'debugInfo() did not suppress output'); } public function testReturnTypeValue() @@ -34,7 +37,7 @@ public function testReturnTypeValue() $test = 'some unique test string'; $key = new Key($test); - $this->assertInternalType('string', $key->get()); + $this->assertIsString($key->get()); $this->assertSame($test, $key->get()); } } diff --git a/tests/DocDb/DocDbClientTest.php b/tests/DocDb/DocDbClientTest.php index 161b46b0b2..cb43941b43 100644 --- a/tests/DocDb/DocDbClientTest.php +++ b/tests/DocDb/DocDbClientTest.php @@ -5,6 +5,7 @@ use Aws\Credentials\Credentials; use Aws\DocDB\DocDBClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -14,13 +15,15 @@ */ class DocDbClientTestClientTest extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; @@ -67,7 +70,7 @@ public function testCorrectPresignDocDbUrls( if (!empty($expectedUrl)) { self::assertSame($expectedUrl, $url); } else if (!empty($expectedSignature)) { - $this->assertContains("X-Amz-Signature={$expectedSignature}", $url); + $this->assertStringContainsString("X-Amz-Signature={$expectedSignature}", $url); } else { self::assertNull($url); } diff --git a/tests/DynamoDb/DynamoDbClientTest.php b/tests/DynamoDb/DynamoDbClientTest.php index df731e5b20..1a24aa489c 100644 --- a/tests/DynamoDb/DynamoDbClientTest.php +++ b/tests/DynamoDb/DynamoDbClientTest.php @@ -7,6 +7,7 @@ use Aws\Exception\AwsException; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Response; @@ -18,6 +19,7 @@ */ class DynamoDbClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testRegisterSessionHandlerReturnsHandler() diff --git a/tests/DynamoDb/MarshalerTest.php b/tests/DynamoDb/MarshalerTest.php index ebdef3ff82..8dcf6ac3a9 100644 --- a/tests/DynamoDb/MarshalerTest.php +++ b/tests/DynamoDb/MarshalerTest.php @@ -5,6 +5,7 @@ use Aws\DynamoDb\BinaryValue; use Aws\DynamoDb\NumberValue; use Aws\DynamoDb\SetValue; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -13,6 +14,8 @@ */ class MarshalerTest extends TestCase { + use PHPUnitCompatTrait; + const ERROR = 'ERROR'; /** @@ -233,11 +236,9 @@ public function testMarshalingJsonAndItems() $this->assertEquals($expected, $m->marshalItem($array)); } - /** - * @expectedException \InvalidArgumentException - */ public function testErrorIfMarshalingBadJsonDoc() { + $this->expectException(\InvalidArgumentException::class); (new Marshaler)->marshalJson('foo'); } @@ -297,11 +298,9 @@ public function testCanUnmarshalToObjectFormat() $this->assertSame('b', $result->a); } - /** - * @expectedException \UnexpectedValueException - */ public function testErrorIfUnmarshalingUnknownType() { + $this->expectException(\UnexpectedValueException::class); $m = new Marshaler; $m->unmarshalValue(['BOMB' => 'BOOM']); } diff --git a/tests/DynamoDb/SessionHandlerTest.php b/tests/DynamoDb/SessionHandlerTest.php index e81ea5a23b..0041a0d806 100644 --- a/tests/DynamoDb/SessionHandlerTest.php +++ b/tests/DynamoDb/SessionHandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\DynamoDb; use Aws\DynamoDb\SessionHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -10,6 +11,7 @@ */ class SessionHandlerTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testCanCreateSessionHandler() diff --git a/tests/DynamoDb/StandardSessionConnectionTest.php b/tests/DynamoDb/StandardSessionConnectionTest.php index 37c75ce0d0..9d2b659408 100644 --- a/tests/DynamoDb/StandardSessionConnectionTest.php +++ b/tests/DynamoDb/StandardSessionConnectionTest.php @@ -5,6 +5,7 @@ use Aws\DynamoDb\StandardSessionConnection; use Aws\Middleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ */ class StandardSessionConnectionTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testStandardConfig() @@ -154,11 +156,9 @@ public function testWriteReturnsFalseOnFailure() $this->assertFalse($return); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testWriteTriggersWarningOnFailure() { + $this->expectWarning(); $client = $this->getTestSdk()->createDynamoDb(); $this->addMockResults($client, [ $this->createMockAwsException('ERROR', 'Aws\DynamoDb\Exception\DynamoDbException') @@ -190,11 +190,9 @@ public function testDeleteReturnsBoolBasedOnSuccess() $this->assertFalse($return); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testDeleteTriggersWarningOnFailure() { + $this->expectWarning(); $client = $this->getTestSdk()->createDynamoDb(); $this->addMockResults($client, [ new Result([]), diff --git a/tests/DynamoDb/WriteRequestBatchTest.php b/tests/DynamoDb/WriteRequestBatchTest.php index e71498a7c2..7d4db5c6d9 100644 --- a/tests/DynamoDb/WriteRequestBatchTest.php +++ b/tests/DynamoDb/WriteRequestBatchTest.php @@ -6,6 +6,7 @@ use Aws\MockHandler; use Aws\Result; use Aws\DynamoDb\WriteRequestBatch; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -14,6 +15,7 @@ */ class WriteRequestBatchTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testInstantiateWriteRequestBatch() @@ -25,10 +27,10 @@ public function testInstantiateWriteRequestBatch() /** * @dataProvider getInvalidArgUseCases - * @expectedException \InvalidArgumentException */ public function testInstantiationFailsOnInvalidArgs($config) { + $this->expectException(\InvalidArgumentException::class); new WriteRequestBatch($this->getTestClient('DynamoDb'), $config); } @@ -65,11 +67,9 @@ public function testAddItems() ); } - /** - * @expectedException \RuntimeException - */ public function testMustProvideTable() { + $this->expectException(\RuntimeException::class); $batch = new WriteRequestBatch($this->getTestClient('DynamoDb')); $batch->put(['a' => 'b']); } diff --git a/tests/Endpoint/EndpointProviderTest.php b/tests/Endpoint/EndpointProviderTest.php index 06bd5faffe..78e72aa979 100644 --- a/tests/Endpoint/EndpointProviderTest.php +++ b/tests/Endpoint/EndpointProviderTest.php @@ -3,6 +3,7 @@ use Aws\Endpoint\EndpointProvider; use Aws\Endpoint\PartitionEndpointProvider; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,19 +11,17 @@ */ class EndpointProviderTest extends TestCase { - /** - * @expectedException \Aws\Exception\UnresolvedEndpointException - */ + use PHPUnitCompatTrait; + public function testThrowsWhenUnresolved() { + $this->expectException(\Aws\Exception\UnresolvedEndpointException::class); EndpointProvider::resolve(function() {}, []); } - /** - * @expectedException \Aws\Exception\UnresolvedEndpointException - */ public function testThrowsWhenNotArray() { + $this->expectException(\Aws\Exception\UnresolvedEndpointException::class); EndpointProvider::resolve(function() { return 'foo'; }, []); } diff --git a/tests/Endpoint/PartitionTest.php b/tests/Endpoint/PartitionTest.php index 7d4b000fb6..09bb87cd52 100644 --- a/tests/Endpoint/PartitionTest.php +++ b/tests/Endpoint/PartitionTest.php @@ -5,6 +5,7 @@ use Aws\Endpoint\PartitionInterface; use Aws\Endpoint\UseDualstackEndpoint; use Aws\Endpoint\UseFipsEndpoint; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,6 +13,8 @@ */ class PartitionTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider partitionDefinitionProvider * @@ -29,12 +32,11 @@ public function testAcceptsValidDefinitions(array $definition) * @dataProvider invalidPartitionDefinitionProvider * * @param array $invalidDefinition - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /missing required \w+ field/ */ public function testRejectsInvalidDefinitions(array $invalidDefinition) { + $this->expectExceptionMessageMatches("/missing required \w+ field/"); + $this->expectException(\InvalidArgumentException::class); new Partition($invalidDefinition); } @@ -63,7 +65,7 @@ public function testFipsEndpoint(array $definition) { $partition = new Partition($definition); $resolved = $partition(['region' => 'fips-aws-global', 'service' => 'service']); - self::assertContains('service-fips.amazonaws.com', $resolved['endpoint']); + self::assertStringContainsString('service-fips.amazonaws.com', $resolved['endpoint']); } public function partitionDefinitionProvider() diff --git a/tests/EndpointDiscovery/ConfigurationProviderTest.php b/tests/EndpointDiscovery/ConfigurationProviderTest.php index c97b757b55..ef98cdbc45 100644 --- a/tests/EndpointDiscovery/ConfigurationProviderTest.php +++ b/tests/EndpointDiscovery/ConfigurationProviderTest.php @@ -8,6 +8,7 @@ use Aws\EndpointDiscovery\ConfigurationProvider; use Aws\EndpointDiscovery\Exception\ConfigurationException; use Aws\LruArrayCache; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -16,6 +17,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENABLED) ?: '', @@ -59,7 +62,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENABLED . '=' . self::$originalEnv['enabled']); @@ -202,21 +205,17 @@ public function testCreatesWithDefaultsFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -230,12 +229,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -248,12 +245,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -323,11 +318,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -488,12 +481,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid endpoint_discovery configuration argument. - */ public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid endpoint_discovery configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/EndpointDiscovery/ConfigurationTest.php b/tests/EndpointDiscovery/ConfigurationTest.php index 4c60d1d5d8..309a651f8e 100644 --- a/tests/EndpointDiscovery/ConfigurationTest.php +++ b/tests/EndpointDiscovery/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\EndpointDiscovery; use Aws\EndpointDiscovery\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Log\InvalidArgumentException; @@ -11,6 +12,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration(true, 2000); @@ -28,11 +31,9 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException InvalidArgumentException - */ public function testHandlesInvalidCacheLimit() { + $this->expectException(\InvalidArgumentException::class); new Configuration(true, 'not_a_cache_limit'); } diff --git a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php index d3a7aa5949..1791fcc1b9 100644 --- a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php +++ b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php @@ -13,6 +13,7 @@ use Aws\Result; use Aws\ResultInterface; use Aws\Sdk; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; @@ -25,6 +26,7 @@ */ class EndpointDiscoveryMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; /** * @backupStaticAttributes enabled @@ -55,7 +57,7 @@ public function testCorrectlyModifiesRequest( } $expectedUserAgentParts = explode(' ', $expected->getHeader('User-Agent')[0]); foreach ($expectedUserAgentParts as $expectedUserAgentPart) { - $this->assertContains( + $this->assertStringContainsString( $expectedUserAgentPart, $req->getHeader('User-Agent')[0] ); @@ -751,11 +753,11 @@ public function testThrowsExceptionWhenMarkedAsEndpointOperation() /** * @backupStaticAttributes enabled - * @expectedException \Aws\Exception\UnresolvedEndpointException - * @expectedExceptionMessage This operation requires the use of endpoint discovery, but this has been disabled */ public function testThrowsExceptionForRequiredOpWhenDisabled() { + $this->expectExceptionMessage("This operation requires the use of endpoint discovery, but this has been disabled"); + $this->expectException(\Aws\Exception\UnresolvedEndpointException::class); $client = $this->generateTestClient( $this->generateTestService(), [ diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 62ad7674ba..0e8a1c1c7a 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -90,7 +90,7 @@ public function testCorrectlyOutputsHost( }); $handler = $list->resolve(); - $handler($command, new Request('POST', $endpoint)); + $handler($command, new Request('POST', $endpoint))->wait(false); } public function getTestCases() diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index 7d4c5d8ba7..fd8f2b6110 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -5,10 +5,13 @@ use Aws\MockHandler; use Aws\Result; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class FunctionsTest extends TestCase { + use PHPUnitCompatTrait; + /** * @covers Aws\recursive_dir_iterator() */ @@ -67,12 +70,11 @@ public function testCreatesConstantlyFunctions() } /** - * @expectedException \InvalidArgumentException - * * @covers Aws\load_compiled_json() */ public function testUsesJsonCompiler() { + $this->expectException(\InvalidArgumentException::class); Aws\load_compiled_json('/path/to/not/here.json'); } @@ -317,10 +319,10 @@ public function testAliasManifest() /** * @covers Aws\manifest() - * @expectedException \InvalidArgumentException */ public function testInvalidManifest() { + $this->expectException(\InvalidArgumentException::class); Aws\manifest('notarealservicename'); } diff --git a/tests/Glacier/GlacierClientTest.php b/tests/Glacier/GlacierClientTest.php index d7bbcce9c7..b1bda13762 100644 --- a/tests/Glacier/GlacierClientTest.php +++ b/tests/Glacier/GlacierClientTest.php @@ -3,6 +3,7 @@ use Aws\Exception\CouldNotCreateChecksumException; use Aws\Glacier\GlacierClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7; @@ -13,6 +14,7 @@ */ class GlacierClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testAppliesAllMiddleware() @@ -45,11 +47,9 @@ public function testAppliesAllMiddleware() $this->assertSame($hash, $request->getHeaderLine('x-amz-sha256-tree-hash')); } - /** - * @expectedException \Aws\Exception\CouldNotCreateChecksumException - */ public function testErrorWhenHashingNonSeekableStream() { + $this->expectException(\Aws\Exception\CouldNotCreateChecksumException::class); $this->getTestClient('Glacier')->uploadArchive([ 'vaultName' => 'foo', 'body' => new NoSeekStream(Psr7\Utils::streamFor('foo')), diff --git a/tests/Glacier/MultipartUploaderTest.php b/tests/Glacier/MultipartUploaderTest.php index 641b6ef81b..eb32d8aad1 100644 --- a/tests/Glacier/MultipartUploaderTest.php +++ b/tests/Glacier/MultipartUploaderTest.php @@ -18,7 +18,7 @@ class MultipartUploaderTest extends TestCase const MB = 1048576; const FILENAME = '_aws-sdk-php-glacier-mup-test-dots.txt'; - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { @unlink(sys_get_temp_dir() . '/' . self::FILENAME); } @@ -28,7 +28,7 @@ public static function tearDownAfterClass() */ public function testGlacierMultipartUploadWorkflow( array $uploadOptions = [], - StreamInterface $source, + StreamInterface $source = null, $error = false ) { $client = $this->getTestClient('glacier'); diff --git a/tests/Glacier/TreeHashTest.php b/tests/Glacier/TreeHashTest.php index f7f3bf755d..2d68d17873 100644 --- a/tests/Glacier/TreeHashTest.php +++ b/tests/Glacier/TreeHashTest.php @@ -2,10 +2,13 @@ namespace Aws\Test\Glacier; use Aws\Glacier\TreeHash; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class TreeHashTest extends TestCase { + use PHPUnitCompatTrait; + /** * @covers Aws\Glacier\TreeHash::__construct * @covers Aws\Glacier\TreeHash::update @@ -38,11 +41,11 @@ public function testHashingIsHappeningCorrectly() } /** - * @expectedException \LogicException * @covers Aws\Glacier\TreeHash::update */ public function testCannotUpdateAfterHashCalculation() { + $this->expectException(\LogicException::class); $hash = new TreeHash('sha256'); $hash->update('foo'); $hash->complete(); @@ -51,11 +54,11 @@ public function testCannotUpdateAfterHashCalculation() } /** - * @expectedException \LogicException * @covers Aws\Glacier\TreeHash::addChecksum */ public function testCannotAddChecksumsAfterHashCalculation() { + $this->expectException(\LogicException::class); $hash = new TreeHash('sha256'); $hash->update('foo'); $hash->complete(); diff --git a/tests/Handler/GuzzleV5/HandlerTest.php b/tests/Handler/GuzzleV5/HandlerTest.php index e1fd58961d..e58deabe08 100644 --- a/tests/Handler/GuzzleV5/HandlerTest.php +++ b/tests/Handler/GuzzleV5/HandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Handler\GuzzleV5; use Aws\Handler\GuzzleV5\GuzzleHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; @@ -24,7 +25,9 @@ */ class HandlerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Handler/GuzzleV5/StreamTest.php b/tests/Handler/GuzzleV5/StreamTest.php index d0f32d9928..11605024bb 100644 --- a/tests/Handler/GuzzleV5/StreamTest.php +++ b/tests/Handler/GuzzleV5/StreamTest.php @@ -3,6 +3,7 @@ use Aws\Handler\GuzzleV5\GuzzleStream as GuzzleStreamAdapter; use Aws\Handler\GuzzleV5\PsrStream as PsrStreamAdapter; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Stream\Stream as GuzzleStream; use PHPUnit\Framework\TestCase; @@ -13,7 +14,9 @@ */ class StreamTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Handler/GuzzleV6/HandlerTest.php b/tests/Handler/GuzzleV6/HandlerTest.php index ffdc7b60c0..636e714cee 100644 --- a/tests/Handler/GuzzleV6/HandlerTest.php +++ b/tests/Handler/GuzzleV6/HandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Handler\GuzzleV6; use Aws\Handler\GuzzleV6\GuzzleHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Handler\MockHandler; @@ -17,7 +18,9 @@ */ class HandlerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\HandlerStack')) { $this->markTestSkipped(); @@ -140,7 +143,7 @@ public function testHandlerWorksWithErroredRequest() $error = $e->getReason(); $this->assertInstanceOf(\Error::class, $error['exception']); $this->assertFalse($error['connection_error']); - $this->assertContains("error message", $error['exception']->getMessage()); + $this->assertStringContainsString("error message", $error['exception']->getMessage()); } $this->assertTrue($wasRejected, 'Reject callback was not triggered.'); diff --git a/tests/HandlerListTest.php b/tests/HandlerListTest.php index a84caea69a..745818a1ba 100644 --- a/tests/HandlerListTest.php +++ b/tests/HandlerListTest.php @@ -5,6 +5,7 @@ use Aws\CommandInterface; use Aws\HandlerList; use Aws\Middleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; @@ -13,11 +14,11 @@ */ class HandlerListTest extends TestCase { - /** - * @expectedException \LogicException - */ + use PHPUnitCompatTrait; + public function testEnsuresHandlerIsSet() { + $this->expectException(\LogicException::class); $list = new HandlerList(); $this->assertFalse($list->hasHandler()); $list->resolve(); @@ -60,6 +61,7 @@ public function testCanRemoveByInstance() $this->assertSame($handler, $list->resolve()); } + /** @doesNotPerformAssertions */ public function testIgnoreWhenNameNotFound() { $list = new HandlerList(); @@ -135,11 +137,11 @@ public function testCanPrintStack() $list->setHandler(function () {}); $lines = explode("\n", (string) $list); $this->assertCount(6, $lines); - $this->assertContains('0) Step: init, Name: foo, Function: callable(', $lines[0]); + $this->assertStringContainsString('0) Step: init, Name: foo, Function: callable(', $lines[0]); $this->assertSame("1) Step: init, Name: bar, Function: callable(['Aws\\Test\\HandlerListTest', 'bar'])", $lines[1]); $this->assertSame('2) Step: validate, Function: callable(Aws\Test\HandlerListTest::foo)', $lines[2]); $this->assertSame("3) Step: sign, Name: baz, Function: callable(['Aws\\Middleware', 'tap'])", $lines[3]); - $this->assertContains('4) Handler: callable(', $lines[4]); + $this->assertStringContainsString('4) Handler: callable(', $lines[4]); } public static function foo() {} @@ -152,8 +154,8 @@ public function testCanAddBefore() $list->appendBuild(function () {}, 'test'); $list->before('test', 'a', function () {}); $lines = explode("\n", (string) $list); - $this->assertContains("1) Step: build, Name: a", $lines[1]); - $this->assertContains("2) Step: build, Name: test", $lines[2]); + $this->assertStringContainsString("1) Step: build, Name: a", $lines[1]); + $this->assertStringContainsString("2) Step: build, Name: test", $lines[2]); } public function testCanAddAfter() @@ -164,16 +166,14 @@ public function testCanAddAfter() $list->appendInit(function () {}); $list->after('test', 'a', function () {}); $lines = explode("\n", (string) $list); - $this->assertContains("1) Step: build, Name: test", $lines[1]); - $this->assertContains("2) Step: build, Name: a", $lines[2]); - $this->assertContains("3) Step: build, Name: after_test", $lines[3]); + $this->assertStringContainsString("1) Step: build, Name: test", $lines[1]); + $this->assertStringContainsString("2) Step: build, Name: a", $lines[2]); + $this->assertStringContainsString("3) Step: build, Name: after_test", $lines[3]); } - /** - * @expectedException \InvalidArgumentException - */ public function testMustExistByNameToPrependOrAppend() { + $this->expectException(\InvalidArgumentException::class); $list = new HandlerList(); $list->before('foo', '', function () {}); } diff --git a/tests/HistoryTest.php b/tests/HistoryTest.php index 57174142e7..04c1d12d45 100644 --- a/tests/HistoryTest.php +++ b/tests/HistoryTest.php @@ -13,6 +13,8 @@ */ class HistoryTest extends TestCase { + use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; + public function testIsCountable() { $h = new History(); @@ -64,41 +66,33 @@ public function testCanAddException() $this->assertSame($e, $h->getLastReturn()); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoEntriesForLastResult() { + $this->expectException(\LogicException::class); $h = new History(); $h->getLastReturn(); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoReturnForLastReturn() { + $this->expectException(\LogicException::class); $h = new History(); $h->start(new Command('foo'), new Request('GET', 'http://foo.com')); $h->getLastReturn(); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenTicketAlreadyComplete() { + $this->expectException(\LogicException::class); $h = new History(); $t = $h->start(new Command('foo'), new Request('GET', 'http://foo.com')); $h->finish($t, new Aws\Result()); $h->finish($t, new Aws\Result()); } - /** - * @expectedException \InvalidArgumentException - */ public function testThrowsWhenTicketIsNotFound() { + $this->expectException(\InvalidArgumentException::class); $h = new History(); $h->finish('foo', new Aws\Result()); } @@ -135,20 +129,16 @@ public function testReturnsLastRequest() $this->assertSame($r, $h->getLastRequest()); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoCommands() { + $this->expectException(\LogicException::class); $h = new History(); $h->getLastCommand(); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoRequests() { + $this->expectException(\LogicException::class); $h = new History(); $h->getLastRequest(); } diff --git a/tests/IdempotencyTokenMiddlewareTest.php b/tests/IdempotencyTokenMiddlewareTest.php index f797ccb21e..9d5c27fd9c 100644 --- a/tests/IdempotencyTokenMiddlewareTest.php +++ b/tests/IdempotencyTokenMiddlewareTest.php @@ -3,6 +3,7 @@ use Aws\IdempotencyTokenMiddleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Aws\HandlerList; use Aws\Api\ApiProvider; @@ -16,6 +17,8 @@ */ class IdempotencyTokenMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; + public function testAutoFillsMemberWithIdempotencyTrait() { $list = new HandlerList(); @@ -23,7 +26,7 @@ public function testAutoFillsMemberWithIdempotencyTrait() $called = true; $this->assertNotNull($command['ClientToken']); $regex = '/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/'; - $this->assertRegExp($regex, $command['ClientToken']); + $this->assertMatchesRegularExpression($regex, $command['ClientToken']); return Promise\Create::promiseFor(new Result([])); }); diff --git a/tests/Integ/GuzzleV5HandlerTest.php b/tests/Integ/GuzzleV5HandlerTest.php index 4ff30cedd3..041439cc24 100644 --- a/tests/Integ/GuzzleV5HandlerTest.php +++ b/tests/Integ/GuzzleV5HandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Integ; use Aws\Handler\GuzzleV5\GuzzleHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise\RejectionException; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; @@ -10,7 +11,9 @@ class GuzzleV5HandlerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Integ/GuzzleV6StreamHandlerTest.php b/tests/Integ/GuzzleV6StreamHandlerTest.php index f221cc42ad..924e68d0a9 100644 --- a/tests/Integ/GuzzleV6StreamHandlerTest.php +++ b/tests/Integ/GuzzleV6StreamHandlerTest.php @@ -1,14 +1,16 @@ markTestSkipped(); diff --git a/tests/JsonCompilerTest.php b/tests/JsonCompilerTest.php index 393db2d328..993eb6c6a6 100644 --- a/tests/JsonCompilerTest.php +++ b/tests/JsonCompilerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test; use Aws\JsonCompiler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,9 +10,11 @@ */ class JsonCompilerTest extends TestCase { + use PHPUnitCompatTrait; + private $models; - public function setup() + public function _setUp() { $this->models = realpath(__DIR__ . '/../src/data'); } @@ -20,14 +23,12 @@ public function testDecodesJsonToArray() { $c = new JsonCompiler(); $data = $c->load($this->models . '/endpoints.json'); - $this->assertInternalType('array', $data); + $this->assertIsArray($data); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresFileExists() { + $this->expectException(\InvalidArgumentException::class); $c = new JsonCompiler(); $c->load($this->models . '/not_there.json'); } diff --git a/tests/Lambda/LambdaClientTest.php b/tests/Lambda/LambdaClientTest.php index 46e9c586d9..850f34ce4d 100644 --- a/tests/Lambda/LambdaClientTest.php +++ b/tests/Lambda/LambdaClientTest.php @@ -3,11 +3,14 @@ use Aws\Lambda\LambdaClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; class LambdaClientTest extends TestCase { + use PHPUnitCompatTrait; + function testsAddsDefaultCurlOptions() { if (!extension_loaded('curl')) { diff --git a/tests/MiddlewareTest.php b/tests/MiddlewareTest.php index 54080d5c78..592e730d07 100644 --- a/tests/MiddlewareTest.php +++ b/tests/MiddlewareTest.php @@ -15,6 +15,7 @@ use Aws\Result; use Aws\ResultInterface; use Aws\Signature\SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Promise; @@ -26,7 +27,9 @@ */ class MiddlewareTest extends TestCase { - public function setup() + use PHPUnitCompatTrait; + + public function _setUp() { \GuzzleHttp\Promise\queue()->run(); } @@ -123,12 +126,10 @@ public function testBuildsRequests() $this->assertTrue($called); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage [a] is missing and is a required parameter - */ public function testValidatesCommands() { + $this->expectExceptionMessage("[a] is missing and is a required parameter"); + $this->expectException(\InvalidArgumentException::class); $list = new HandlerList(); $list->setHandler(new MockHandler([new Result()])); $api = new Service( diff --git a/tests/MockHandlerTest.php b/tests/MockHandlerTest.php index 94cc77acf4..e9706a8227 100644 --- a/tests/MockHandlerTest.php +++ b/tests/MockHandlerTest.php @@ -6,6 +6,7 @@ use Aws\Exception\AwsException; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Promise; @@ -16,12 +17,12 @@ */ class MockHandlerTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Expected an Aws\ResultInterface or Exception - */ + use PHPUnitCompatTrait; + public function testValidatesEachResult() { + $this->expectExceptionMessage("Expected an Aws\ResultInterface or Exception"); + $this->expectException(\InvalidArgumentException::class); new MockHandler(['foo']); } @@ -44,24 +45,20 @@ public function testReturnsMockResultsFromQueue() $this->assertSame($r2, $h($cmd, $request)->wait()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty - */ public function testThrowsWhenNoResultsInQueue() { + $this->expectExceptionMessage("Mock queue is empty"); + $this->expectException(\RuntimeException::class); $h = new MockHandler(); $cmd = new Command('foo'); $request = new Request('GET', 'http://www.example.com'); $h($cmd, $request); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessage Error - */ public function testThrowsExceptionsFromQueue() { + $this->expectExceptionMessage("Error"); + $this->expectException(\Aws\Exception\AwsException::class); $cmd = new Command('foo'); $e = new AwsException('Error', $cmd); $request = new Request('GET', 'http://www.example.com'); diff --git a/tests/MultiRegionClientTest.php b/tests/MultiRegionClientTest.php index d913e14a53..1ce01cc553 100644 --- a/tests/MultiRegionClientTest.php +++ b/tests/MultiRegionClientTest.php @@ -10,6 +10,7 @@ use Aws\MockHandler; use Aws\MultiRegionClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; @@ -17,12 +18,14 @@ class MultiRegionClientTest extends TestCase { + use PHPUnitCompatTrait; + /** @var MultiRegionClient */ private $instance; /** @var \PHPUnit_Framework_MockObject_MockObject */ private $mockRegionalClient; - public function setUp() + public function _setUp() { $this->mockRegionalClient = $this->getMockBuilder(AwsClient::class) ->disableOriginalConstructor() @@ -138,11 +141,9 @@ public function testDefaultsToAwsPartition() $this->assertSame('aws', $mrc->getConfig('partition')->getName()); } - /** - * @expectedException \InvalidArgumentException - */ public function testRejectsUnrecognizedPartitions() { + $this->expectException(\InvalidArgumentException::class); new MultiRegionClient([ 'service' => 'ec2', 'partition' => 'foo', diff --git a/tests/Multipart/AbstractUploaderTest.php b/tests/Multipart/AbstractUploaderTest.php index 1c8e7e73ae..c52d8f6be8 100644 --- a/tests/Multipart/AbstractUploaderTest.php +++ b/tests/Multipart/AbstractUploaderTest.php @@ -6,6 +6,7 @@ use Aws\Exception\MultipartUploadException; use Aws\Multipart\UploadState; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -15,6 +16,7 @@ */ class AbstractUploaderTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getUploaderWithState($status, array $results = [], $source = null) @@ -44,22 +46,18 @@ private function getTestUploader( return new TestUploader($client, $source ?: Psr7\Utils::streamFor(), $config); } - /** - * @expectedException \Aws\S3\Exception\S3MultipartUploadException - */ public function testThrowsExceptionOnBadInitiateRequest() { + $this->expectException(\Aws\S3\Exception\S3MultipartUploadException::class); $uploader = $this->getUploaderWithState(UploadState::CREATED, [ new AwsException('Failed', new Command('Initiate')), ]); $uploader->upload(); } - /** - * @expectedException \LogicException - */ public function testThrowsExceptionIfStateIsCompleted() { + $this->expectException(\LogicException::class); $uploader = $this->getUploaderWithState(UploadState::COMPLETED); $this->assertTrue($uploader->getState()->isCompleted()); $uploader->upload(); @@ -78,11 +76,9 @@ public function testSuccessfulCompleteReturnsResult() $this->assertTrue($uploader->getState()->isCompleted()); } - /** - * @expectedException \Aws\S3\Exception\S3MultipartUploadException - */ public function testThrowsExceptionOnBadCompleteRequest() { + $this->expectException(\Aws\S3\Exception\S3MultipartUploadException::class); $uploader = $this->getUploaderWithState(UploadState::CREATED, [ new Result(), // Initiate new Result(), // Upload @@ -107,8 +103,8 @@ public function testThrowsExceptionOnBadUploadRequest() $this->fail('No exception was thrown.'); } catch (MultipartUploadException $e) { $message = $e->getMessage(); - $this->assertContains('Failed[1]', $message); - $this->assertContains('Failed[4]', $message); + $this->assertStringContainsString('Failed[1]', $message); + $this->assertStringContainsString('Failed[4]', $message); $uploadedParts = $e->getState()->getUploadedParts(); $this->assertCount(3, $uploadedParts); $this->assertArrayHasKey(2, $uploadedParts); @@ -160,11 +156,9 @@ public function testAsyncUpload() $this->assertSame(6, $called); } - /** - * @expectedException \InvalidArgumentException - */ public function testRequiresIdParams() { + $this->expectException(\InvalidArgumentException::class); $this->getTestUploader(Psr7\Utils::streamFor()); } diff --git a/tests/Neptune/NeptuneClientTest.php b/tests/Neptune/NeptuneClientTest.php index 6522cd75ad..b365d61b4f 100644 --- a/tests/Neptune/NeptuneClientTest.php +++ b/tests/Neptune/NeptuneClientTest.php @@ -5,6 +5,7 @@ use Aws\Credentials\Credentials; use Aws\Neptune\NeptuneClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -14,13 +15,15 @@ */ class NeptuneClientTest extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; @@ -71,7 +74,7 @@ function ( if (!empty($expectedUrl)) { self::assertSame($expectedUrl, $url); } else if (!empty($expectedSignature)) { - $this->assertContains("X-Amz-Signature={$expectedSignature}", $url); + $this->assertStringContainsString("X-Amz-Signature={$expectedSignature}", $url); } else { self::assertNull($url); } diff --git a/tests/Polly/PollyClientTest.php b/tests/Polly/PollyClientTest.php index 23c760ede6..62a821f859 100644 --- a/tests/Polly/PollyClientTest.php +++ b/tests/Polly/PollyClientTest.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Polly\PollyClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class PollyClientTest extends TestCase { + use PHPUnitCompatTrait; + public function testCanGeneratePreSignedUrlForSynthesizeSpeech() { $polly = new PollyClient([ @@ -26,19 +29,19 @@ public function testCanGeneratePreSignedUrlForSynthesizeSpeech() 'VoiceId' => 'Ewa' ]; $url = $polly->createSynthesizeSpeechPreSignedUrl($args); - $this->assertContains('https://polly.us-west-2.amazonaws.com/v1/speech', $url); - $this->assertContains('LexiconNames=mno&LexiconNames=abc', $url); - $this->assertContains('OutputFormat=mp3', $url); - $this->assertContains('SampleRate=128', $url); - $this->assertContains('Text=Hello%20World', $url); - $this->assertContains('TextType=text', $url); - $this->assertContains('VoiceId=Ewa', $url); - $this->assertContains('X-Amz-Algorithm=AWS4-HMAC-SHA256', $url); - $this->assertContains('X-Amz-Credential=akid', $url); - $this->assertContains('X-Amz-Date=', $url); - $this->assertContains('X-Amz-Expires=900', $url); - $this->assertContains('X-Amz-SignedHeaders=host', $url); - $this->assertContains('X-Amz-Signature=', $url); - $this->assertContains('X-Amz-Date=', $url); + $this->assertStringContainsString('https://polly.us-west-2.amazonaws.com/v1/speech', $url); + $this->assertStringContainsString('LexiconNames=mno&LexiconNames=abc', $url); + $this->assertStringContainsString('OutputFormat=mp3', $url); + $this->assertStringContainsString('SampleRate=128', $url); + $this->assertStringContainsString('Text=Hello%20World', $url); + $this->assertStringContainsString('TextType=text', $url); + $this->assertStringContainsString('VoiceId=Ewa', $url); + $this->assertStringContainsString('X-Amz-Algorithm=AWS4-HMAC-SHA256', $url); + $this->assertStringContainsString('X-Amz-Credential=akid', $url); + $this->assertStringContainsString('X-Amz-Date=', $url); + $this->assertStringContainsString('X-Amz-Expires=900', $url); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Date=', $url); } } diff --git a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php new file mode 100644 index 0000000000..9af1c4707f --- /dev/null +++ b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php @@ -0,0 +1,131 @@ +setExpectedException( $exception, $this->exceptionMessage, $this->exceptionCode ); + } + + public function expectExceptionMessage( $message ) { + $this->exceptionMessage = $message; + + $exception = $this->getExpectedException(); + $this->setExpectedException( $exception, $message, $this->exceptionCode ); + } + + public function _setUp() + { + } + + public function setUp() + { + $this->_setUp(); + } + + public function _tearDown() + { + } + + public function tearDown() + { + $this->_tearDown(); + } + + public static function setUpBeforeClass() + { + self::_setUpBeforeClass(); + } + + public static function tearDownAfterClass() + { + self::_tearDownAfterClass(); + } + + public static function _tearDownAfterClass() + { + } + + public static function _setUpBeforeClass() + { + } + + public function expectNotToPerformAssertions() + { + } + + public function expectWarning() + { + $this->expectException(\PHPUnit_Framework_Error_Warning::class); + } + + public function expectExceptionMessageMatches($regularExpression) + { + $this->expectExceptionMessageRegExp($regularExpression); + } + + public function expectExceptionMessageRegExp($messageRegExp) + { + $exception = $this->getExpectedException(); + $this->setExpectedExceptionRegExp($exception, $messageRegExp, $this->exceptionCode); + } + + public function assertStringContainsString($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message); + } + + public function assertStringNotContainsString($expected, $actual, $message = '') + { + $this->assertNotContains($expected, $actual, $message); + } + + public function assertStringContainsStringIgnoringCase($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message, true); + } + + public function assertIsInt($actual, $message = '') + { + $this->assertInternalType('int', $actual, $message); + } + + public function assertIsArray($actual, $message = '') + { + $this->assertInternalType('array', $actual, $message); + } + + public function assertIsCallable($actual, $message = '') + { + $this->assertInternalType('callable', $actual, $message); + } + + public function assertIsString($actual, $message = '') + { + $this->assertInternalType('string', $actual, $message); + } + + public function assertIsResource($actual, $message = '') + { + $this->assertInternalType('resource', $actual, $message); + } + + public function assertMatchesRegularExpression($pattern, $string, $message = '') + { + $this->assertRegExp($pattern, $string, $message); + } + + public function assertDoesNotMatchRegularExpression($pattern, $string, $message = '') + { + $this->assertNotRegExp($pattern, $string, $message); + } + + public function assertFileDoesNotExist($file, $message = '') + { + $this->assertFileNotExists($file, $message); + } +} \ No newline at end of file diff --git a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php new file mode 100644 index 0000000000..35eb03eccc --- /dev/null +++ b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php @@ -0,0 +1,119 @@ +_setUp(); + } + + public function _tearDown() + { + } + + public function tearDown() + { + $this->_tearDown(); + } + + public static function setUpBeforeClass() + { + self::_setUpBeforeClass(); + } + + public static function tearDownAfterClass() + { + self::_tearDownAfterClass(); + } + + public static function _tearDownAfterClass() + { + } + + public static function _setUpBeforeClass() + { + } + + public function expectNotToPerformAssertions() + { + } + + public function expectWarning() + { + $this->expectException(\PHPUnit_Framework_Error_Warning::class); + } + + public function expectExceptionMessageMatches($regularExpression) + { + $this->expectExceptionMessageRegExp($regularExpression); + } + + public function expectExceptionMessageRegExp($messageRegExp) + { + $exception = $this->getExpectedException(); + $this->setExpectedExceptionRegExp($exception, $messageRegExp, $this->exceptionCode); + } + + public function assertStringContainsString($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message); + } + + public function assertStringNotContainsString($expected, $actual, $message = '') + { + $this->assertNotContains($expected, $actual, $message); + } + + public function assertStringContainsStringIgnoringCase($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message, true); + } + + public function assertIsInt($actual, $message = '') + { + $this->assertInternalType('int', $actual, $message); + } + + public function assertIsArray($actual, $message = '') + { + $this->assertInternalType('array', $actual, $message); + } + + public function assertIsCallable($actual, $message = '') + { + $this->assertInternalType('callable', $actual, $message); + } + + public function assertIsString($actual, $message = '') + { + $this->assertInternalType('string', $actual, $message); + } + + public function assertIsResource($actual, $message = '') + { + $this->assertInternalType('resource', $actual, $message); + } + + public function assertMatchesRegularExpression($pattern, $string, $message = '') + { + $this->assertRegExp($pattern, $string, $message); + } + + public function assertDoesNotMatchRegularExpression($pattern, $string, $message = '') + { + $this->assertNotRegExp($pattern, $string, $message); + } + + public function assertFileDoesNotExist($file, $message = '') + { + $this->assertFileNotExists($file, $message); + } +} \ No newline at end of file diff --git a/tests/Polyfill/PHPUnit9/ArraySubset.php b/tests/Polyfill/PHPUnit9/ArraySubset.php new file mode 100644 index 0000000000..308dfe9402 --- /dev/null +++ b/tests/Polyfill/PHPUnit9/ArraySubset.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace Aws\Test\Polyfill\PHPUnit9; + +use PHPUnit\Framework\Constraint\Constraint; +use PHPUnit\Framework\ExpectationFailedException; +use PHPUnit\Util\Exception; +use SebastianBergmann\Comparator\ComparisonFailure; + +/** + * Constraint that asserts that the array it is evaluated for has a specified subset. + * + * Uses array_replace_recursive() to check if a key value subset is part of the + * subject array. + */ +class ArraySubset extends Constraint +{ + /** + * @var iterable + */ + private $subset; + + /** + * @var bool + */ + private $strict; + + public function __construct(iterable $subset, bool $strict = false) + { + $this->strict = $strict; + $this->subset = $subset; + } + + /** + * Evaluates the constraint for parameter $other + * + * If $returnResult is set to false (the default), an exception is thrown + * in case of a failure. null is returned otherwise. + * + * If $returnResult is true, the result of the evaluation is returned as + * a boolean value instead: true in case of success, false in case of a + * failure. + * + * @param mixed $other value or object to evaluate + * @param string $description Additional information about the test + * @param bool $returnResult Whether to return a result or throw an exception + * + * @throws ExpectationFailedException + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function evaluate($other, string $description = '', $returnResult = false): ?bool + { + //type cast $other & $this->subset as an array to allow + //support in standard array functions. + $other = $this->toArray($other); + $this->subset = $this->toArray($this->subset); + + $patched = \array_replace_recursive($other, $this->subset); + + if ($this->strict) { + $result = $other === $patched; + } else { + $result = $other == $patched; + } + + if ($returnResult) { + return $result; + } + + if (!$result) { + $f = new ComparisonFailure( + $patched, + $other, + \var_export($patched, true), + \var_export($other, true) + ); + + $this->fail($other, $description, $f); + } + + return null; + } + + /** + * Returns a string representation of the constraint. + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function toString(): string + { + throw new Exception('Not implemented'); + } + + /** + * Returns the description of the failure + * + * The beginning of failure messages is "Failed asserting that" in most + * cases. This method should return the second part of that sentence. + * + * @param mixed $other evaluated value or object + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + protected function failureDescription($other): string + { + return 'an array ' . $this->toString(); + } + + private function toArray($other) + { + if (\is_array($other)) { + return $other; + } + + if ($other instanceof \ArrayObject) { + return $other->getArrayCopy(); + } + + if ($other instanceof \Traversable) { + return \iterator_to_array($other); + } + + // Keep BC even if we know that array would not be the expected one + return (array) $other; + } +} diff --git a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php new file mode 100644 index 0000000000..f10106183e --- /dev/null +++ b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php @@ -0,0 +1,130 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Aws\Test\Polyfill\PHPUnit; + +use ArrayAccess; +use Exception; +use ReflectionException; +use ReflectionObject; +use ReflectionProperty; +use Aws\Test\Polyfill\PHPUnit9\ArraySubset; + +trait PHPUnitCompatTrait +{ + public function _setUp() + { + } + + public function setUp(): void + { + $this->_setUp(); + } + + public function _tearDown() + { + } + + public function tearDown(): void + { + $this->_tearDown(); + } + + public static function setUpBeforeClass(): void + { + self::_setUpBeforeClass(); + } + + public static function tearDownAfterClass(): void + { + self::_tearDownAfterClass(); + } + + public static function _tearDownAfterClass() + { + } + + public static function _setUpBeforeClass() + { + } + + public function readAttribute($object, $attributeName) + { + try { + $attribute = new ReflectionProperty($object, $attributeName); + } catch (ReflectionException $e) { + $reflector = new ReflectionObject($object); + + while ($reflector = $reflector->getParentClass()) { + try { + $attribute = $reflector->getProperty($attributeName); + break; + } catch (ReflectionException $e) { + } + } + } + + if (isset($attribute)) { + if ( ! $attribute || $attribute->isPublic()) { + return $object->$attributeName; + } + $attribute->setAccessible(true); + $value = $attribute->getValue($object); + $attribute->setAccessible(false); + + return $value; + } + + throw new Exception( + sprintf( + 'Attribute "%s" not found in object.', + $attributeName + ) + ); + } + + public static function invalidArgumentHelper($argument, $type, $value = null) + { + $stack = debug_backtrace(false); + + return new \PHPUnit\Framework\Exception( + sprintf( + 'Argument #%d%sof %s::%s() must be a %s', + $argument, + $value !== null ? ' ('.$value.')' : ' ', + $stack[1]['class'], + $stack[1]['function'], + $type + ) + ); + } + + public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = '') + { + if ( ! (\is_array($subset) || $subset instanceof ArrayAccess)) { + throw self::invalidArgumentHelper( + 1, + 'array or ArrayAccess' + ); + } + + if ( ! (\is_array($array) || $array instanceof ArrayAccess)) { + throw self::invalidArgumentHelper( + 2, + 'array or ArrayAccess' + ); + } + + $constraint = new ArraySubset($subset, $checkForObjectIdentity); + + static::assertThat($array, $constraint, $message); + } +} \ No newline at end of file diff --git a/tests/PresignUrlMiddlewareTest.php b/tests/PresignUrlMiddlewareTest.php index e2d3262940..58b01d66c9 100644 --- a/tests/PresignUrlMiddlewareTest.php +++ b/tests/PresignUrlMiddlewareTest.php @@ -8,6 +8,7 @@ use Aws\Neptune\NeptuneClient; use Aws\Rds\RdsClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -16,6 +17,7 @@ */ class PresignUrlMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testDoesNotAddPresignedUrlForNonRequiredOperations() @@ -47,10 +49,10 @@ public function testAddsPresignedUrlForRequiredOperations() 'handler' => function (CommandInterface $cmd, RequestInterface $r) { $url = $cmd['PresignedUrl']; $this->assertNotNull($url); - $this->assertContains('https://ec2.eu-west-1.amazonaws.com', $url); - $this->assertContains('SourceSnapshotId=foo', $url); - $this->assertContains('SourceRegion=eu-west-1', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('https://ec2.eu-west-1.amazonaws.com', $url); + $this->assertStringContainsString('SourceSnapshotId=foo', $url); + $this->assertStringContainsString('SourceRegion=eu-west-1', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); $this->assertSame('us-east-2', $cmd['DestinationRegion']); return new Result; @@ -67,12 +69,12 @@ public function testAddsPresignedUrlForRequiredOperations() 'handler' => function (CommandInterface $cmd, RequestInterface $r) { $url = $cmd['PreSignedUrl']; $this->assertNotNull($url); - $this->assertContains('https://rds.eu-west-1.amazonaws.com', $url); - $this->assertContains('KmsKeyId=', $url); - $this->assertContains('SourceDBSnapshotIdentifier=', $url); - $this->assertContains('TargetDBSnapshotIdentifier=my-snapshot-copy', $url); - $this->assertContains('eu-west-1', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('https://rds.eu-west-1.amazonaws.com', $url); + $this->assertStringContainsString('KmsKeyId=', $url); + $this->assertStringContainsString('SourceDBSnapshotIdentifier=', $url); + $this->assertStringContainsString('TargetDBSnapshotIdentifier=my-snapshot-copy', $url); + $this->assertStringContainsString('eu-west-1', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); $this->assertSame('us-east-2', $cmd['DestinationRegion']); return new Result; diff --git a/tests/Psr16CacheAdapterTest.php b/tests/Psr16CacheAdapterTest.php index d3eb05eaaa..adf00ff7e9 100644 --- a/tests/Psr16CacheAdapterTest.php +++ b/tests/Psr16CacheAdapterTest.php @@ -2,17 +2,20 @@ namespace Aws\Test; use Aws\Psr16CacheAdapter; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\SimpleCache\CacheInterface; use PHPUnit\Framework\TestCase; class Psr16CacheAdapterTest extends TestCase { + use PHPUnitCompatTrait; + /** @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedCache */ private $wrapped; /** @var Psr16CacheAdapter */ private $instance; - public function setUp() + public function _setUp() { $this->wrapped = $this->getMockBuilder(CacheInterface::class)->getMock(); $this->instance = new Psr16CacheAdapter($this->wrapped); diff --git a/tests/PsrCacheAdapterTest.php b/tests/PsrCacheAdapterTest.php index 2b0db7fb06..ac7bde272d 100644 --- a/tests/PsrCacheAdapterTest.php +++ b/tests/PsrCacheAdapterTest.php @@ -2,18 +2,21 @@ namespace Aws\Test; use Aws\PsrCacheAdapter; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; use PHPUnit\Framework\TestCase; class PsrCacheAdapterTest extends TestCase { + use PHPUnitCompatTrait; + /** @var CacheItemPoolInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedCache */ private $wrapped; /** @var PsrCacheAdapter */ private $instance; - public function setUp() + public function _setUp() { $this->wrapped = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock(); $this->instance = new PsrCacheAdapter($this->wrapped); diff --git a/tests/Rds/AuthTokenGeneratorTest.php b/tests/Rds/AuthTokenGeneratorTest.php index 21135d3a6b..a1ced2279c 100644 --- a/tests/Rds/AuthTokenGeneratorTest.php +++ b/tests/Rds/AuthTokenGeneratorTest.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Rds\AuthTokenGenerator; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -11,6 +12,8 @@ */ class AuthTokenGeneratorTest extends TestCase { + use PHPUnitCompatTrait; + public function testCanCreateAuthTokenWthCredentialInstance() { $creds = new Credentials('foo', 'bar', 'baz'); @@ -21,13 +24,13 @@ public function testCanCreateAuthTokenWthCredentialInstance() 'myDBUser' ); - $this->assertContains('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); - $this->assertContains('us-west-2', $token); - $this->assertContains('X-Amz-Credential=foo', $token); - $this->assertContains('X-Amz-Expires=900', $token); - $this->assertContains('X-Amz-SignedHeaders=host', $token); - $this->assertContains('DBUser=myDBUser', $token); - $this->assertContains('Action=connect', $token); + $this->assertStringContainsString('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); + $this->assertStringContainsString('us-west-2', $token); + $this->assertStringContainsString('X-Amz-Credential=foo', $token); + $this->assertStringContainsString('X-Amz-Expires=900', $token); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $token); + $this->assertStringContainsString('DBUser=myDBUser', $token); + $this->assertStringContainsString('Action=connect', $token); } public function testCanCreateAuthTokenWthCredentialProvider() @@ -47,13 +50,13 @@ public function testCanCreateAuthTokenWthCredentialProvider() 'myDBUser' ); - $this->assertContains('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); - $this->assertContains('us-west-2', $token); - $this->assertContains('X-Amz-Credential=AKID', $token); - $this->assertContains('X-Amz-Expires=900', $token); - $this->assertContains('X-Amz-SignedHeaders=host', $token); - $this->assertContains('DBUser=myDBUser', $token); - $this->assertContains('Action=connect', $token); + $this->assertStringContainsString('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); + $this->assertStringContainsString('us-west-2', $token); + $this->assertStringContainsString('X-Amz-Credential=AKID', $token); + $this->assertStringContainsString('X-Amz-Expires=900', $token); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $token); + $this->assertStringContainsString('DBUser=myDBUser', $token); + $this->assertStringContainsString('Action=connect', $token); } public function lifetimeProvider() @@ -82,13 +85,13 @@ public function testCanCreateAuthTokenWthNonDefaultLifetime($lifetime) $lifetime ); $lifetimeInSeconds = $lifetime * 60; - $this->assertContains('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); - $this->assertContains('us-west-2', $token); - $this->assertContains('X-Amz-Credential=foo', $token); - $this->assertContains("X-Amz-Expires={$lifetimeInSeconds}", $token); - $this->assertContains('X-Amz-SignedHeaders=host', $token); - $this->assertContains('DBUser=myDBUser', $token); - $this->assertContains('Action=connect', $token); + $this->assertStringContainsString('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); + $this->assertStringContainsString('us-west-2', $token); + $this->assertStringContainsString('X-Amz-Credential=foo', $token); + $this->assertStringContainsString("X-Amz-Expires={$lifetimeInSeconds}", $token); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $token); + $this->assertStringContainsString('DBUser=myDBUser', $token); + $this->assertStringContainsString('Action=connect', $token); } public function lifetimeFailureProvider() @@ -106,13 +109,13 @@ public function lifetimeFailureProvider() /** * @dataProvider lifetimeFailureProvider - * @param $lifetime * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Lifetime must be a positive number less than or equal to 15, was + * @param $lifetime */ public function testThrowsExceptionWithInvalidLifetime($lifetime) { + $this->expectExceptionMessage("Lifetime must be a positive number less than or equal to 15, was"); + $this->expectException(\InvalidArgumentException::class); $creds = new Credentials('foo', 'bar', 'baz'); $connect = new AuthTokenGenerator($creds); $connect->createToken( diff --git a/tests/Rds/RdsClientTest.php b/tests/Rds/RdsClientTest.php index 76e2e0b5cf..cfcc8176eb 100644 --- a/tests/Rds/RdsClientTest.php +++ b/tests/Rds/RdsClientTest.php @@ -6,6 +6,7 @@ use Aws\Rds\RdsClient; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -15,13 +16,15 @@ */ class RdsClientTest extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; @@ -37,7 +40,7 @@ public function testAddsCopySnapshotMiddleware() $mock = new MockHandler([ function ($command, $request) { $this->assertNotNull($command['PreSignedUrl']); - $this->assertContains('us-west-2', $command['PreSignedUrl']); + $this->assertStringContainsString('us-west-2', $command['PreSignedUrl']); $this->assertSame('us-east-1', $command['DestinationRegion']); return new Result(); } @@ -101,7 +104,7 @@ public function testCorrectPresignRdsUrls( if (!empty($expectedUrl)) { self::assertSame($expectedUrl, $url); } else if (!empty($expectedSignature)) { - $this->assertContains("X-Amz-Signature={$expectedSignature}", $url); + $this->assertStringContainsString("X-Amz-Signature={$expectedSignature}", $url); } else { self::assertNull($url); } diff --git a/tests/ResultPaginatorTest.php b/tests/ResultPaginatorTest.php index d5134d294a..ecefbbcea2 100644 --- a/tests/ResultPaginatorTest.php +++ b/tests/ResultPaginatorTest.php @@ -5,6 +5,7 @@ use Aws\CommandInterface; use Aws\DynamoDb\DynamoDbClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -14,6 +15,7 @@ */ class ResultPaginatorTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getCustomClientProvider(array $config) diff --git a/tests/ResultTest.php b/tests/ResultTest.php index 27c3901047..38cb5f01db 100644 --- a/tests/ResultTest.php +++ b/tests/ResultTest.php @@ -2,6 +2,7 @@ namespace Aws\Test; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ResultTest extends TestCase { + use PHPUnitCompatTrait; + public function testHasData() { $c = new Result(['a' => 'b', 'c' => 'd']); @@ -18,7 +21,7 @@ public function testHasData() $this->assertTrue($c->hasKey('c')); $this->assertFalse($c->hasKey('f')); $this->assertSame('b', $c->search('a')); - $this->assertContains('Model Data', (string) $c); + $this->assertStringContainsString('Model Data', (string) $c); } public function testCanIndirectlyModifyLikeAnArray() diff --git a/tests/Retry/ConfigurationProviderTest.php b/tests/Retry/ConfigurationProviderTest.php index a5f54c9a39..5e4a134b30 100644 --- a/tests/Retry/ConfigurationProviderTest.php +++ b/tests/Retry/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\Retry\ConfigurationInterface; use Aws\Retry\ConfigurationProvider; use Aws\Retry\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_MAX_ATTEMPTS) ?: '', @@ -59,7 +62,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_MAX_ATTEMPTS . '=' . self::$originalEnv['max_attempts']); @@ -176,21 +179,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -204,12 +203,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -222,12 +219,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -297,11 +292,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -419,12 +412,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid retry configuration argument - */ public function testThrowsForInvalidUnwrapArgument() { + $this->expectExceptionMessage("Not a valid retry configuration argument"); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap('some_string'); } } diff --git a/tests/Retry/ConfigurationTest.php b/tests/Retry/ConfigurationTest.php index 176674ea10..48c0df944e 100644 --- a/tests/Retry/ConfigurationTest.php +++ b/tests/Retry/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\Retry; use Aws\Retry\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('adaptive', 8); @@ -27,21 +30,17 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage The 'maxAttempts' parameter has to be an integer >= 1 - */ public function testHandlesInvalidMaxAttempts() { + $this->expectExceptionMessage("The 'maxAttempts' parameter has to be an integer >= 1"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); new Configuration('standard', 0); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' is not a valid mode - */ public function testHandlesInvalidMode() { + $this->expectExceptionMessage("'foo' is not a valid mode"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); new Configuration('foo', 5); } } diff --git a/tests/RetryMiddlewareTest.php b/tests/RetryMiddlewareTest.php index d84bfafb4b..c9a3b6b2ff 100644 --- a/tests/RetryMiddlewareTest.php +++ b/tests/RetryMiddlewareTest.php @@ -7,6 +7,7 @@ use Aws\MockHandler; use Aws\Result; use Aws\RetryMiddleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise\RejectedPromise; @@ -20,6 +21,8 @@ */ class RetryMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; + public function testAddRetryHeader() { $nextHandler = function (CommandInterface $command, RequestInterface $request) { @@ -380,7 +383,7 @@ function () use (&$called) { $called[] = func_get_args(); } $this->fail(); } catch (AwsException $e) { $this->assertCount(1, $called); - $this->assertContains('foo', $e->getMessage()); + $this->assertStringContainsString('foo', $e->getMessage()); } } diff --git a/tests/RetryMiddlewareV2Test.php b/tests/RetryMiddlewareV2Test.php index e0d1147e87..a3f5fd99f7 100644 --- a/tests/RetryMiddlewareV2Test.php +++ b/tests/RetryMiddlewareV2Test.php @@ -12,6 +12,7 @@ use Aws\Retry\QuotaManager; use Aws\Retry\RateLimiter; use Aws\RetryMiddlewareV2; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; @@ -24,6 +25,7 @@ */ class RetryMiddlewareV2Test extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -764,7 +766,7 @@ public function testUsesCustomDelayer() $this->fail(); } catch (AwsException $e) { $this->assertSame(3, $attempts); - $this->assertContains('foo', $e->getMessage()); + $this->assertStringContainsString('foo', $e->getMessage()); } } @@ -885,7 +887,7 @@ function () use (&$called) { $called[] = func_get_args(); } $this->fail(); } catch (AwsException $e) { $this->assertCount(1, $called); - $this->assertContains('foo', $e->getMessage()); + $this->assertStringContainsString('foo', $e->getMessage()); } } diff --git a/tests/Route53/RouteClient53Test.php b/tests/Route53/RouteClient53Test.php index 5d64680dbd..9362e7a671 100644 --- a/tests/Route53/RouteClient53Test.php +++ b/tests/Route53/RouteClient53Test.php @@ -2,6 +2,7 @@ namespace Aws\Test\Route53; use Aws\Route53\Route53Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class RouteClient53Test extends TestCase { + use PHPUnitCompatTrait; + public function testCleansIds() { $client = new Route53Client([ @@ -34,8 +37,8 @@ public function testCleansIds() $request = \Aws\serialize($command); $requestUri = (string) $request->getUri(); - $this->assertContains('/hostedzone/foo/rrset/', $requestUri); - $this->assertNotContains('/hostedzone/hostedzone', $requestUri); + $this->assertStringContainsString('/hostedzone/foo/rrset/', $requestUri); + $this->assertStringNotContainsString('/hostedzone/hostedzone', $requestUri); $command = $client->getCommand('GetReusableDelegationSet', [ 'Id' => '/delegationset/foo', @@ -43,8 +46,8 @@ public function testCleansIds() $request = \Aws\serialize($command); $requestUri = (string) $request->getUri(); - $this->assertContains('/delegationset/foo', $requestUri); - $this->assertNotContains('/delegationset/delegationset', $requestUri); + $this->assertStringContainsString('/delegationset/foo', $requestUri); + $this->assertStringNotContainsString('/delegationset/delegationset', $requestUri); $command = $client->getCommand('CreateHostedZone', [ 'Name' => 'foo', @@ -53,7 +56,7 @@ public function testCleansIds() ]); $request = \Aws\serialize($command); - $this->assertContains( + $this->assertStringContainsString( 'bar', $request->getBody()->getContents() ); diff --git a/tests/S3/AmbiguousSuccessParserTest.php b/tests/S3/AmbiguousSuccessParserTest.php index f2cc6ea7f5..d9e0d20cbf 100644 --- a/tests/S3/AmbiguousSuccessParserTest.php +++ b/tests/S3/AmbiguousSuccessParserTest.php @@ -7,15 +7,18 @@ use Aws\CommandInterface; use Aws\S3\AmbiguousSuccessParser; use Aws\S3\Exception\S3Exception; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\ResponseInterface; use PHPUnit\Framework\TestCase; class AmbiguousSuccessParserTest extends TestCase { + use PHPUnitCompatTrait; + private $instance; - public function setUp() + public function _setUp() { $parser = function () {}; $errorParser = function () { @@ -31,13 +34,13 @@ public function setUp() /** * @dataProvider opsWithAmbiguousSuccessesProvider - * @param string $operation * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage Sorry! + * @param string $operation */ public function testConvertsAmbiguousSuccessesToExceptions($operation) { + $this->expectExceptionMessage("Sorry!"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $command = $this->getMockBuilder(CommandInterface::class)->getMock(); $command->expects($this->any()) ->method('getName') @@ -54,6 +57,7 @@ public function testConvertsAmbiguousSuccessesToExceptions($operation) /** * @dataProvider opsWithoutAmbiguousSuccessesProvider * @param string $operation + * @doesNotPerformAssertions */ public function testIgnoresAmbiguousSuccessesOnUnaffectedOperations($operation) { @@ -72,12 +76,11 @@ public function testIgnoresAmbiguousSuccessesOnUnaffectedOperations($operation) /** * @dataProvider opsWithAmbiguousSuccessesProvider - * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage An error connecting to the service occurred while performing the */ public function testThrowsConnectionErrorForEmptyBody($operation) { + $this->expectExceptionMessage("An error connecting to the service occurred while performing the"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $parser = function() {}; $errorParser = new XmlErrorParser(); $instance = new AmbiguousSuccessParser( diff --git a/tests/S3/BatchDeleteTest.php b/tests/S3/BatchDeleteTest.php index 64cc5fd57b..6a26d85ced 100644 --- a/tests/S3/BatchDeleteTest.php +++ b/tests/S3/BatchDeleteTest.php @@ -6,30 +6,28 @@ use Aws\Result; use Aws\S3\BatchDelete; use Aws\S3\Exception\DeleteMultipleObjectsException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; /** - * @covers Aws\S3\BatchDelete + * @covers \Aws\S3\BatchDelete */ class BatchDeleteTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesBatchSizeIsGreatherThanZero() { + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); BatchDelete::fromIterator($client, 'foo', new \ArrayIterator(), ['batch_size' => 0]); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesBeforeIsCallable() { + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); BatchDelete::fromIterator($client, 'foo', new \ArrayIterator(), ['before' => 0]); } diff --git a/tests/S3/BucketEndpointArnMiddlewareTest.php b/tests/S3/BucketEndpointArnMiddlewareTest.php index 73ca1edf83..44fe345739 100644 --- a/tests/S3/BucketEndpointArnMiddlewareTest.php +++ b/tests/S3/BucketEndpointArnMiddlewareTest.php @@ -9,6 +9,7 @@ use Aws\Result; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -19,6 +20,7 @@ */ class BucketEndpointArnMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -75,7 +77,7 @@ public function testCorrectlyModifiesUri( ); } - $this->assertContains( + $this->assertStringContainsString( "/{$signingRegion}/s3", $req->getHeader('Authorization')[0] ); diff --git a/tests/S3/Crypto/S3EncryptionClientTest.php b/tests/S3/Crypto/S3EncryptionClientTest.php index 6f59ac570a..28794aebc9 100644 --- a/tests/S3/Crypto/S3EncryptionClientTest.php +++ b/tests/S3/Crypto/S3EncryptionClientTest.php @@ -15,6 +15,7 @@ use Aws\S3\Crypto\HeadersMetadataStrategy; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTrait; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Promise; @@ -25,6 +26,7 @@ class S3EncryptionClientTest extends TestCase { + use PHPUnitCompatTrait; use S3EncryptionClientTestingTrait; use UsesCryptoParamsTrait; use UsesMetadataEnvelopeTrait; @@ -264,6 +266,8 @@ public function testPutObjectValidatesCipher( if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $s3 = $this->getS3Client(); @@ -299,6 +303,8 @@ public function testPutObjectValidatesKeySize( ) { if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $cipherOptions = [ @@ -422,12 +428,10 @@ public function testPutObjectWrapsBodyInAesGcmEncryptingStream() $this->assertTrue($this->mockQueueEmpty()); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Unrecognized or unsupported AESName for reverse lookup. - */ public function testGetObjectThrowsOnInvalidCipher() { + $this->expectExceptionMessage("Unrecognized or unsupported AESName for reverse lookup."); + $this->expectException(\RuntimeException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProvider($kms); $this->addMockResults($kms, [ @@ -457,12 +461,10 @@ public function testGetObjectThrowsOnInvalidCipher() $this->assertInstanceOf(AesDecryptingStream::class, $result['Body']); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Not able to detect the materials description. - */ public function testFromDecryptionEnvelopeEmptyKmsMaterialException() { + $this->expectExceptionMessage("Not able to detect the materials description."); + $this->expectException(\RuntimeException::class); $kms = $this->getKmsClient(); $keyId = '11111111-2222-3333-4444-555555555555'; $provider = new KmsMaterialsProvider($kms, $keyId); @@ -471,12 +473,10 @@ public function testFromDecryptionEnvelopeEmptyKmsMaterialException() $provider->fromDecryptionEnvelope($envelope); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Not able to detect kms_cmk_id (legacy implementation) - */ public function testFromDecryptionEnvelopeInvalidKmsMaterialException() { + $this->expectExceptionMessage("Not able to detect kms_cmk_id (legacy implementation)"); + $this->expectException(\RuntimeException::class); $kms = $this->getKmsClient(); $keyId = '11111111-2222-3333-4444-555555555555'; $provider = new KmsMaterialsProvider($kms, $keyId); @@ -727,12 +727,11 @@ public function testGetObjectSavesFile() * Note that outside of PHPUnit, normal code execution will continue through * this warning unless configured otherwise. PHPUnit throws it as an * exception here for testing. - * - * @expectedException PHPUnit_Framework_Error_Warning - * @expectedExceptionMessage 'Aad' has been supplied for content encryption with AES/GCM/NoPadding */ public function testTriggersWarningForGcmEncryptionWithAad() { + $this->expectExceptionMessage("'Aad' has been supplied for content encryption with AES/GCM/NoPadding"); + $this->expectWarning(); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -781,7 +780,7 @@ public function testAddsCryptoUserAgent() 'region' => 'us-west-2', 'version' => 'latest', 'http_handler' => function (RequestInterface $req) use ($provider) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionClient::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Crypto/S3EncryptionClientV2Test.php b/tests/S3/Crypto/S3EncryptionClientV2Test.php index 023f91e55b..f9c7e14226 100644 --- a/tests/S3/Crypto/S3EncryptionClientV2Test.php +++ b/tests/S3/Crypto/S3EncryptionClientV2Test.php @@ -12,17 +12,18 @@ use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\S3\Crypto\S3EncryptionClientV2; use Aws\Test\Crypto\UsesCryptoParamsTraitV2; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; -use PHPUnit_Framework_Error_Warning; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; class S3EncryptionClientV2Test extends TestCase { + use PHPUnitCompatTrait; use S3EncryptionClientTestingTrait; use UsesCryptoParamsTraitV2; use UsesMetadataEnvelopeTrait; @@ -273,6 +274,8 @@ public function testPutObjectValidatesCipher( ) { if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $s3 = $this->getS3Client(); @@ -312,6 +315,8 @@ public function testPutObjectValidatesKeySize( ) { if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $cipherOptions = [ @@ -409,12 +414,11 @@ public function testPutObjectWrapsBodyInAesGcmEncryptingStream() * Note that outside of PHPUnit, normal code execution will continue through * this warning unless configured otherwise. PHPUnit throws it as an * exception here for testing. - * - * @expectedException PHPUnit_Framework_Error_Warning - * @expectedExceptionMessage 'Aad' has been supplied for content encryption with AES/GCM/NoPadding */ public function testTriggersWarningForGcmEncryptionWithAad() { + $this->expectExceptionMessage("'Aad' has been supplied for content encryption with AES/GCM/NoPadding"); + $this->expectWarning(); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -503,12 +507,10 @@ public function testAddsEncryptionContextForKms() $this->assertTrue($this->mockQueueEmpty()); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage Unrecognized or unsupported AESName for reverse lookup. - */ public function testGetObjectThrowsOnInvalidCipher() { + $this->expectExceptionMessage("Unrecognized or unsupported AESName for reverse lookup."); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -539,12 +541,10 @@ public function testGetObjectThrowsOnInvalidCipher() $this->assertInstanceOf(AesDecryptingStream::class, $result['Body']); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object is encrypted with the keywrap schema 'my_first_keywrap' - */ public function testGetObjectThrowsOnInvalidKeywrap() { + $this->expectExceptionMessage("The requested object is encrypted with the keywrap schema 'my_first_keywrap'"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -574,12 +574,10 @@ public function testGetObjectThrowsOnInvalidKeywrap() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2 - */ public function testGetObjectThrowsOnLegacyKeywrap() { + $this->expectExceptionMessage("The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -609,12 +607,10 @@ public function testGetObjectThrowsOnLegacyKeywrap() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage There is a mismatch in specified content encryption algrithm between the materials description value and the metadata envelope value - */ public function testGetObjectThrowsOnMismatchAlgorithm() { + $this->expectExceptionMessage("There is a mismatch in specified content encryption algrithm between the materials description value and the metadata envelope value"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -908,12 +904,10 @@ public function testGetObjectSavesFile() $this->assertStringEqualsFile($file, (string)$result['Body']); } - /** - * @expectedException PHPUnit_Framework_Error_Warning - * @expectedExceptionMessage This S3 Encryption Client operation is configured to read encrypted data with legacy encryption modes - */ public function testEmitsWarningForLegacySecurityProfile() { + $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) { @@ -955,12 +949,10 @@ public function testEmitsWarningForLegacySecurityProfile() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2 - */ public function testThrowsForV2ProfileAndLegacyObject() { + $this->expectExceptionMessage("The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $list = $kms->getHandlerList(); $list->setHandler(function($cmd, $req) { @@ -1003,12 +995,10 @@ public function testThrowsForV2ProfileAndLegacyObject() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage @SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY' - */ public function testThrowsForNoSecurityProfile() { + $this->expectExceptionMessage("@SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY'"); + $this->expectException(\Aws\Exception\CryptoException::class); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -1024,12 +1014,10 @@ public function testThrowsForNoSecurityProfile() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage @SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY' - */ public function testThrowsForIncorrectSecurityProfile() { + $this->expectExceptionMessage("@SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY'"); + $this->expectException(\Aws\Exception\CryptoException::class); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -1058,7 +1046,7 @@ public function testAddsCryptoUserAgent() 'region' => 'us-west-2', 'version' => 'latest', 'http_handler' => function (RequestInterface $req) use ($provider) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionClientV2::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php index 97cc411f15..f99ef4916a 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php @@ -7,6 +7,7 @@ use Aws\Crypto\KmsMaterialsProvider; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTrait; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Psr7; @@ -14,7 +15,7 @@ class S3EncryptionMultipartUploaderTest extends TestCase { - use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTrait; + use PHPUnitCompatTrait, UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTrait; const MB = 1048576; const TEST_URL = 'http://foo.s3.amazonaws.com/bar'; @@ -451,7 +452,7 @@ public function testAddsCryptoUserAgent() ]); $list = $s3->getHandlerList(); $list->appendSign(Middleware::tap(function($cmd, $req) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionMultipartUploader::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php index 42273a4f76..c901f9c5b0 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php @@ -8,6 +8,7 @@ use Aws\Crypto\KmsMaterialsProviderV2; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTraitV2; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Psr7; @@ -16,7 +17,7 @@ class S3EncryptionMultipartUploaderV2Test extends TestCase { - use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTraitV2; + use PHPUnitCompatTrait, UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTraitV2; const MB = 1048576; const TEST_URL = 'http://foo.s3.amazonaws.com/bar'; @@ -502,7 +503,7 @@ public function testAddsCryptoUserAgent() ]); $list = $s3->getHandlerList(); $list->appendSign(Middleware::tap(function($cmd, $req) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionMultipartUploaderV2::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php index ee8c02a60d..ade2ce7f5d 100644 --- a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php +++ b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\S3\Exception; use Aws\S3\Exception\DeleteMultipleObjectsException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class DeleteMultipleObjectsExceptionTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsData() { $del = [['Key' => 'foo']]; @@ -16,7 +19,7 @@ public function testReturnsData() $e = new DeleteMultipleObjectsException($del, $err); $this->assertSame($del, $e->getDeleted()); $this->assertSame($err, $e->getErrors()); - $this->assertContains( + $this->assertStringContainsString( 'Unable to delete certain keys when executing a', $e->getMessage() ); diff --git a/tests/S3/MultipartUploaderTest.php b/tests/S3/MultipartUploaderTest.php index e0614b405d..1fda627565 100644 --- a/tests/S3/MultipartUploaderTest.php +++ b/tests/S3/MultipartUploaderTest.php @@ -4,6 +4,7 @@ use Aws\S3\MultipartUploader; use Aws\Result; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7; @@ -15,12 +16,13 @@ */ class MultipartUploaderTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; const MB = 1048576; const FILENAME = '_aws-sdk-php-s3-mup-test-dots.txt'; - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { @unlink(sys_get_temp_dir() . '/' . self::FILENAME); } @@ -31,7 +33,7 @@ public static function tearDownAfterClass() public function testS3MultipartUploadWorkflow( array $clientOptions = [], array $uploadOptions = [], - StreamInterface $source, + StreamInterface $source = null, $error = false ) { $client = $this->getTestClient('s3', $clientOptions); @@ -135,6 +137,7 @@ public function testCanUseCaseInsensitiveConfigKeys() $this->assertSame($configProp->getValue($classicMup), $configProp->getValue($putObjectMup)); } + /** @doesNotPerformAssertions */ public function testMultipartSuccessStreams() { $size = 12 * self::MB; @@ -265,12 +268,10 @@ public function testS3MultipartContentTypeSetting( $this->assertSame($url, $result['ObjectURL']); } - /** - * @expectedException \Aws\S3\Exception\S3MultipartUploadException - * @expectedExceptionMessage An exception occurred while uploading parts to a multipart upload - */ public function testAppliesAmbiguousSuccessParsing() { + $this->expectExceptionMessage("An exception occurred while uploading parts to a multipart upload"); + $this->expectException(\Aws\S3\Exception\S3MultipartUploadException::class); $counter = 0; $httpHandler = function ($request, array $options) use (&$counter) { diff --git a/tests/S3/PermanentRedirectMiddlewareTest.php b/tests/S3/PermanentRedirectMiddlewareTest.php index 894aa18b58..4ffb7c9ccd 100644 --- a/tests/S3/PermanentRedirectMiddlewareTest.php +++ b/tests/S3/PermanentRedirectMiddlewareTest.php @@ -1,27 +1,28 @@ expectExceptionMessage("Encountered a permanent redirect while requesting"); + $this->expectException(\Aws\S3\Exception\PermanentRedirectException::class); $s3 = $this->getTestClient('s3'); $this->addMockResults($s3, [['@metadata' => ['statusCode' => 301]]]); $s3->getObject(['Bucket' => 'test', 'Key' => 'key']); } + /** @doesNotPerformAssertions */ public function testPassesThroughUntouched() { $s3 = $this->getTestClient('s3'); diff --git a/tests/S3/PostObjectTest.php b/tests/S3/PostObjectTest.php index dafc598215..de31cff2bd 100644 --- a/tests/S3/PostObjectTest.php +++ b/tests/S3/PostObjectTest.php @@ -4,6 +4,7 @@ use Aws\Credentials\Credentials; use Aws\S3\PostObject; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -12,12 +13,13 @@ */ class PostObjectTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ protected $client; - public function setUp() + public function _setUp() { $this->client = $this->getTestClient( 's3', diff --git a/tests/S3/PostObjectV4Test.php b/tests/S3/PostObjectV4Test.php index 82ef1661f7..bb20c011b4 100644 --- a/tests/S3/PostObjectV4Test.php +++ b/tests/S3/PostObjectV4Test.php @@ -4,6 +4,7 @@ use Aws\Credentials\Credentials; use Aws\S3\PostObjectV4; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; require_once __DIR__ . '/sig_hack.php'; @@ -14,12 +15,13 @@ */ class PostObjectV4Test extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ protected $client; - public function setUp() + public function _setUp() { $this->client = new S3Client([ 'version' => 'latest', @@ -30,6 +32,14 @@ public function setUp() ], ]); } + + public function _tearDown() + { + parent::tearDown(); + + unset($_SERVER['aws_time']); + } + /** * Executes the SigV4 POST example from the S3 documentation. * diff --git a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php index 43c6a6fbba..f6d6845496 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\S3\RegionalEndpoint\ConfigurationInterface; use Aws\S3\RegionalEndpoint\ConfigurationProvider; use Aws\S3\RegionalEndpoint\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', @@ -56,7 +59,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '=' . self::$originalEnv['endpoints_type']); @@ -155,21 +158,17 @@ public function testCreatesFromNonLowercaseValue() unlink($dir . '/config'); } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -183,12 +182,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -201,12 +198,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -309,12 +304,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid S3 regional endpoint configuration argument. - */ public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid S3 regional endpoint configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/S3/RegionalEndpoint/ConfigurationTest.php b/tests/S3/RegionalEndpoint/ConfigurationTest.php index 367a5f7e72..585e87a3f0 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\S3\RegionalEndpoint; use Aws\Sts\RegionalEndpoints\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('regional'); @@ -31,12 +34,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new Configuration('invalid_type'); } } diff --git a/tests/S3/RetryableMalformedResponseParserTest.php b/tests/S3/RetryableMalformedResponseParserTest.php index 498dc1db0f..82997ee344 100644 --- a/tests/S3/RetryableMalformedResponseParserTest.php +++ b/tests/S3/RetryableMalformedResponseParserTest.php @@ -6,17 +6,18 @@ use Aws\CommandInterface; use Aws\S3\Exception\S3Exception; use Aws\S3\RetryableMalformedResponseParser; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\ResponseInterface; use PHPUnit\Framework\TestCase; class RetryableMalformedResponseParserTest extends TestCase { - /** - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage Sorry! - */ + use PHPUnitCompatTrait; + public function testConvertsParserExceptionsToRetryableExceptions() { + $this->expectExceptionMessage("Sorry!"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $parser = function () { throw new ParserException('Sorry!'); }; $instance = new RetryableMalformedResponseParser( diff --git a/tests/S3/S3ClientTest.php b/tests/S3/S3ClientTest.php index d4aa15f936..dd1ab1332a 100644 --- a/tests/S3/S3ClientTest.php +++ b/tests/S3/S3ClientTest.php @@ -15,6 +15,7 @@ use Aws\S3\S3Client; use Aws\S3\UseArnRegion\Configuration as UseArnRegionConfiguration; use Aws\Signature\SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; @@ -35,6 +36,7 @@ */ class S3ClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testCanUseBucketEndpoint() @@ -89,9 +91,9 @@ public function testCreatesPresignedRequests() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://foo.s3.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsWithAccessPointArn() @@ -110,9 +112,9 @@ public function testCreatesPresignedRequestsWithAccessPointArn() ); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://myendpoint-123456789012.s3-accesspoint.us-east-1.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsWithStartTime() @@ -129,9 +131,9 @@ public function testCreatesPresignedRequestsWithStartTime() ['start_time' => 1562349366] )->getUri(); $this->assertStringStartsWith('https://foo.s3.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=1200', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=61a9940ecdd901be8e36833f6d47123c0c719fc6aa82042144a6c5cf44a25988', $url); + $this->assertStringContainsString('X-Amz-Expires=1200', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=61a9940ecdd901be8e36833f6d47123c0c719fc6aa82042144a6c5cf44a25988', $url); } public function testCreatesPresignedRequestsWithPathStyleFallback() @@ -144,9 +146,9 @@ public function testCreatesPresignedRequestsWithPathStyleFallback() $command = $client->getCommand('GetObject', ['Bucket' => 'foo.baz', 'Key' => 'bar']); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://s3.amazonaws.com/foo.baz/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsWithPathStyle() @@ -160,9 +162,9 @@ public function testCreatesPresignedRequestsWithPathStyle() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://s3.amazonaws.com/foo/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatingPresignedUrlDoesNotPermanentlyRemoveSigner() @@ -393,12 +395,10 @@ public function testReturnsObjectUrlViaPathWithPathStyle() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The DeleteObject operation requires non-empty parameter: Bucket - */ public function testEnsuresMandatoryInputVariables() { + $this->expectExceptionMessage("The DeleteObject operation requires non-empty parameter: Bucket"); + $this->expectException(\InvalidArgumentException::class); /** @var S3Client $client */ $client = $this->getTestClient('S3'); $client->deleteObject([ @@ -407,11 +407,9 @@ public function testEnsuresMandatoryInputVariables() ); } - /** - * @expectedException \RuntimeException - */ public function testEnsuresPrefixOrRegexSuppliedForDeleteMatchingObjects() { + $this->expectException(\RuntimeException::class); /** @var S3Client $client */ $client = $this->getTestClient('S3'); $client->deleteMatchingObjects('foo'); @@ -449,42 +447,34 @@ public function testDeletesMatchingObjectsByPrefixAndRegex() $this->assertEquals(['foo/bar/baz', 'foo/bar/bam'], $agg); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a PutObject - */ public function testProxiesToTransferObjectPut() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a PutObject"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->uploadDirectory(__DIR__, 'test'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a ListObjects - */ public function testProxiesToTransferObjectGet() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a ListObjects"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->downloadBucket(__DIR__, 'test'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a PutObject - */ public function testProxiesToObjectUpload() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a PutObject"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->upload('bucket', 'key', 'body'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a HeadObject - */ public function testProxiesToObjectCopy() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a HeadObject"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->copy('from-bucket', 'fromKey', 'to-bucket', 'toKey'); } @@ -504,9 +494,9 @@ public function testAddsLocationConstraintAutomatically($region, $target, $comma $text = "{$target}"; $body = (string) \Aws\serialize($command)->getBody(); if ($contains) { - $this->assertContains($text, $body); + $this->assertStringContainsString($text, $body); } else { - $this->assertNotContains($text, $body); + $this->assertStringNotContainsString($text, $body); } } @@ -546,7 +536,7 @@ public function testRequestSucceedsWithColon() $key = 'aaa:bbb'; $s3 = $this->getTestClient('S3', [ 'http_handler' => function (RequestInterface $request) use ($key) { - $this->assertContains( + $this->assertStringContainsString( urlencode($key), (string) $request->getUri() ); @@ -859,12 +849,11 @@ private function getWellFormedXml() * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessageRegExp /Your socket connection to the server/ */ public function testClientSocketTimeoutErrorsAreNotRetriedIndefinitely($retrySettings) { + $this->expectExceptionMessageMatches("/Your socket connection to the server/"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $client = new S3Client([ 'version' => 'latest', 'region' => 'us-west-2', @@ -942,12 +931,11 @@ public function testNetworkingErrorsAreRetriedOnIdempotentCommands($retrySetting * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessageRegExp /CompleteMultipartUpload/ */ public function testNetworkingErrorsAreNotRetriedOnNonIdempotentCommands($retrySettings) { + $this->expectExceptionMessageMatches("/CompleteMultipartUpload/"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $networkingError = $this->getMockBuilder(RequestException::class) ->disableOriginalConstructor() ->setMethods([]) @@ -1211,11 +1199,9 @@ public function testCanDetermineRegionOfBucket() $this->assertSame('us-west-2', $client->determineBucketRegion('bucket')); } - /** - * @expectedException \Aws\Exception\AwsException - */ public function testDetermineBucketRegionExposeException() { + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -1456,12 +1442,10 @@ public function testAppliesS3EndpointMiddlewareDualstackWithPathStyle() ]); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid configuration value provided for "use_arn_region" - */ public function testAddsUseArnRegionArgument() { + $this->expectExceptionMessage("Invalid configuration value provided for \"use_arn_region\""); + $this->expectException(\InvalidArgumentException::class); new S3Client([ 'region' => 'us-east-1', 'version' => 'latest', @@ -1536,12 +1520,10 @@ public function testCopyOperationCorrectlyPopulates() $client->execute($command); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testAddsS3RegionalEndpointArgument() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new S3Client([ 'region' => 'us-east-1', 'version' => 'latest', @@ -1674,12 +1656,10 @@ public function optionsToEndpointsCases() ]; } - /** - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage An error connecting to the service occurred while performing the CopyObject operation - */ public function testAppliesAmbiguousSuccessParsing() { + $this->expectExceptionMessage("An error connecting to the service occurred while performing the CopyObject operation"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $httpHandler = function ($request, array $options) { return Promise\Create::promiseFor( new Psr7\Response(200, [], "\n\n\n") @@ -1835,7 +1815,7 @@ public function testMrapExceptions( $e instanceof UnresolvedEndpointException || $e instanceof S3Exception ); - self::assertContains($expectedException, $e->getMessage()); + self::assertStringContainsString($expectedException, $e->getMessage()); } } @@ -1879,7 +1859,7 @@ public function testAccessPointFailures ( $e instanceof UnresolvedEndpointException || $e instanceof S3Exception ); - self::assertContains($expectedException, $e->getMessage()); + self::assertStringContainsString($expectedException, $e->getMessage()); } } public function AccessPointFailureProvider() @@ -1937,7 +1917,7 @@ public function testPresignedMrapFailure (){ self::fail("exception should have been thrown"); } catch (\Exception $e) { self::assertTrue($e instanceof UnresolvedEndpointException); - self::assertContains($expectedException, $e->getMessage()); + self::assertStringContainsString($expectedException, $e->getMessage()); } } diff --git a/tests/S3/S3EndpointMiddlewareTest.php b/tests/S3/S3EndpointMiddlewareTest.php index 076e978043..b290c42b8d 100644 --- a/tests/S3/S3EndpointMiddlewareTest.php +++ b/tests/S3/S3EndpointMiddlewareTest.php @@ -6,6 +6,7 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\S3\S3EndpointMiddleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Request; @@ -15,6 +16,7 @@ class S3EndpointMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -396,8 +398,8 @@ private function noAcceleratePatternAssertingHandler(CommandInterface $command, CommandInterface $toHandle, RequestInterface $req ) use ($command, $pattern) { - $this->assertNotContains($pattern, (string)$req->getUri()); - $this->assertContains($command['Bucket'], $req->getUri()->getHost()); + $this->assertStringNotContainsString($pattern, (string)$req->getUri()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getHost()); }; } @@ -411,7 +413,7 @@ private function acceleratePatternAssertingHandler(CommandInterface $command, $p "{$command['Bucket']}.{$pattern}.amazonaws.com", $req->getUri()->getHost() ); - $this->assertNotContains($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringNotContainsString($command['Bucket'], $req->getUri()->getPath()); }; } @@ -425,8 +427,8 @@ private function dualStackAssertingHandler(CommandInterface $command) "bucket.s3.dualstack.us-west-2.amazonaws.com", $req->getUri()->getHost() ); - $this->assertNotContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringNotContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -440,8 +442,8 @@ private function dualStackPathStyleFallbackAssertingHandler(CommandInterface $co "s3.dualstack.us-west-2.amazonaws.com", $req->getUri()->getHost() ); - $this->assertContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -455,8 +457,8 @@ private function dualStackWithPathStyleAssertingHandler(CommandInterface $comman "s3.dualstack.us-west-2.amazonaws.com", $req->getUri()->getHost() ); - $this->assertContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -466,9 +468,9 @@ private function noDualStackAssertingHandler(CommandInterface $command) CommandInterface $cmd, RequestInterface $req ) use ($command) { - $this->assertNotContains('s3.dualstack', (string)$req->getUri()); - $this->assertContains($command['Bucket'], $req->getUri()->getHost()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringNotContainsString('s3.dualstack', (string)$req->getUri()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getHost()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -482,8 +484,8 @@ private function ipAddressPathStyleFallbackAssertingHandler(CommandInterface $co "127.250.250.250", $req->getUri()->getHost() ); - $this->assertContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -664,7 +666,7 @@ public function testObjectLambdaArnFailures( $client->execute($command); $this->fail("did not catch exception: " . $expectedException); } catch (\Exception $e) { - $this->assertContains($expectedException, $e->getMessage()); + $this->assertStringContainsString($expectedException, $e->getMessage()); } } diff --git a/tests/S3/S3MultiRegionClientTest.php b/tests/S3/S3MultiRegionClientTest.php index f015b5ae8a..a1fb4c24ca 100644 --- a/tests/S3/S3MultiRegionClientTest.php +++ b/tests/S3/S3MultiRegionClientTest.php @@ -8,6 +8,7 @@ use Aws\ResultInterface; use Aws\S3\S3ClientInterface; use Aws\S3\S3MultiRegionClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7; @@ -19,6 +20,7 @@ class S3MultiRegionClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testWillRecoverFromPermanentRedirect() @@ -107,17 +109,15 @@ public function testCreatesPresignedRequestsForCorrectRegion() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string)$client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://foo.s3.us-west-2.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /AWS HTTP error/ - */ public function testRethrowsOnNoResponseException() { + $this->expectExceptionMessageMatches("/AWS HTTP error/"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', @@ -139,12 +139,10 @@ public function testRethrowsOnNoResponseException() $client->createPresignedRequest($command, 1342138769)->getUri(); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /The authorization header is malformed/ - */ public function testRethrowsOnAuthHeaderMalformedWithoutRegion() { + $this->expectExceptionMessageMatches("/The authorization header is malformed/"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', @@ -194,9 +192,9 @@ public function testRedirectsOnNonRedirectExceptionWithHeader() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string)$client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://foo.s3.us-west-2.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsForCorrectRegionWithPathStyle() @@ -218,9 +216,9 @@ public function testCreatesPresignedRequestsForCorrectRegionWithPathStyle() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string)$client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://s3.us-west-2.amazonaws.com/foo/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesObjectUrlsForCorrectRegion() @@ -291,12 +289,10 @@ public function testCachesBucketLocation() $this->assertSame('us-west-2', $this->readAttribute($client, 'cache')->get('aws:s3:foo:location')); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /Your socket connection to the server was not read from or written to within the timeout period./ - */ public function testRethrowsAwsExceptionViaMiddleware() { + $this->expectExceptionMessageMatches("/Your socket connection to the server was not read from or written to within the timeout period./"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', @@ -318,12 +314,10 @@ public function testRethrowsAwsExceptionViaMiddleware() $client->getObject(['Bucket' => 'foo', 'Key' => 'bar']); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /The authorization header is malformed/ - */ public function testRethrowsOnAuthHeaderMalformedWithoutRegionViaMiddleware() { + $this->expectExceptionMessageMatches("/The authorization header is malformed/"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', diff --git a/tests/S3/S3UriParserTest.php b/tests/S3/S3UriParserTest.php index aa15364e4a..73525d70ff 100644 --- a/tests/S3/S3UriParserTest.php +++ b/tests/S3/S3UriParserTest.php @@ -3,6 +3,7 @@ use Aws\Arn\Exception\InvalidArnException; use Aws\S3\S3UriParser; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class S3UriParserTest extends TestCase { + use PHPUnitCompatTrait; + public function uriProvider() { return [ @@ -101,10 +104,12 @@ public function testParsesUrls($uri, $result, $isError = false) ksort($actual); $this->assertSame($result, $actual); } catch (\InvalidArgumentException $e) { + $this->expectNotToPerformAssertions(); if (!$isError) { throw $e; } } catch (InvalidArnException $e) { + $this->expectNotToPerformAssertions(); if (!$isError) { throw $e; } diff --git a/tests/S3/SSECMiddlewareTest.php b/tests/S3/SSECMiddlewareTest.php index 86b54d84cc..a988d19109 100644 --- a/tests/S3/SSECMiddlewareTest.php +++ b/tests/S3/SSECMiddlewareTest.php @@ -3,6 +3,7 @@ use Aws\Middleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -11,6 +12,7 @@ */ class SSECMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -75,11 +77,9 @@ public function getListenerTestCases() ]; } - /** - * @expectedException \RuntimeException - */ public function testCannotUseWithoutHttps() { + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('s3', ['scheme' => 'http']); $client->listBuckets([ 'SSECustomerKey' => 'foo', @@ -87,6 +87,7 @@ public function testCannotUseWithoutHttps() ]); } + /** @doesNotPerformAssertions */ public function testCanUseWithoutHttpsForNonSse() { $client = $this->getTestClient('s3', ['scheme' => 'http']); diff --git a/tests/S3/StreamWrapperPathStyleTest.php b/tests/S3/StreamWrapperPathStyleTest.php index a1b4d4f10a..162070dfc7 100644 --- a/tests/S3/StreamWrapperPathStyleTest.php +++ b/tests/S3/StreamWrapperPathStyleTest.php @@ -9,6 +9,7 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -18,6 +19,7 @@ */ class StreamWrapperPathStyleTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -26,7 +28,7 @@ class StreamWrapperPathStyleTest extends TestCase /** @var LruArrayCache */ private $cache; - public function setUp() + public function _setUp() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -38,7 +40,7 @@ public function setUp() $this->client->registerStreamWrapper(); } - public function tearDown() + public function _tearDown() { stream_wrapper_unregister('s3'); $this->client = null; @@ -51,34 +53,29 @@ public function testRegistersStreamWrapperOnlyOnce() StreamWrapper::register($this->client); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Cannot open a bucket - */ public function testCannotOpenBuckets() { + $this->expectExceptionMessage("Cannot open a bucket"); + $this->expectWarning(); fopen('s3://bucket', 'r'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Mode not supported - */ public function testSupportsOnlyReadWriteXA() { + $this->expectExceptionMessage("Mode not supported"); + $this->expectWarning(); fopen('s3://bucket/key', 'c'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage s3://bucket/key already exists on Amazon S3 - */ 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'); } + /** @doesNotPerformAssertions */ public function testSuccessfulXMode() { $this->addMockResults( @@ -173,12 +170,10 @@ public function testCanOpenWriteOnlyStreams() $this->assertSame('test', (string) $cmd['Body']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } ]); @@ -244,12 +239,10 @@ public function testCanUnlinkFiles() $this->assertSame('s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testThrowsErrorsWhenUnlinkFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -261,22 +254,18 @@ public function testCreatingBucketWithNoBucketReturnsFalse() $this->assertFalse(mkdir('s3://')); } - /** - * @expectedExceptionMessage Bucket already exists: s3://already-existing-bucket - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Bucket already exists: s3://already-existing-bucket"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket'); } - /** - * @expectedExceptionMessage Subfolder already exists: s3://already-existing-bucket/key - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketForKeyRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Subfolder already exists: s3://already-existing-bucket/key"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket/key'); } @@ -329,24 +318,20 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $entries = $history->toArray(); $this->assertSame('HEAD', $entries[0]['request']->getMethod()); $this->assertSame('PUT', $entries[1]['request']->getMethod()); - $this->assertContains('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); + $this->assertStringContainsString('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage specify a bucket - */ public function testCannotDeleteS3() { + $this->expectExceptionMessage("specify a bucket"); + $this->expectWarning(); rmdir('s3://'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testRmDirWithExceptionTriggersError() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -386,7 +371,7 @@ public function testCanDeleteObjectWithRmDir($path) $this->assertCount(1, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); } public function testCanDeleteNestedFolderWithRmDir() @@ -406,36 +391,30 @@ public function testCanDeleteNestedFolderWithRmDir() $this->assertCount(2, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); $this->assertSame('DELETE', $entries[1]['request']->getMethod()); $this->assertSame('/foo/bar/', $entries[1]['request']->getUri()->getPath()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage rename(): Cannot rename a file across wrapper types - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage The Amazon S3 stream wrapper only supports copying objects - */ public function testRenameEnsuresKeyIsSet() { + $this->expectExceptionMessage("The Amazon S3 stream wrapper only supports copying objects"); + $this->expectWarning(); rename('s3://foo/bar', 's3://baz'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ public function testRenameWithExceptionThrowsError() { + $this->expectExceptionMessage("Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -532,12 +511,10 @@ public function testCanPullStatDataFromCache() $this->assertSame(123, filesize('s3://foo/bar')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ 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); }, @@ -547,12 +524,10 @@ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } stat('s3://bucket/key'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket - */ 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); }, ]); @@ -594,12 +569,10 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $this->assertSame(0040777, $stat['mode']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket/prefix - */ 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() @@ -669,12 +642,16 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) $this->assertCount(count($queue), $history); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage cannot represent a stream of type user-space - */ 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->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) ]); @@ -684,12 +661,10 @@ public function testStreamCastIsNotPossible() stream_select($read, $write, $except, 0); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage No client in stream context - */ public function testEnsuresClientIsSet() { + $this->expectExceptionMessage("No client in stream context"); + $this->expectWarning(); fopen('s3://bucket/key', 'r', false, stream_context_create([ 's3' => ['client' => null] ])); @@ -708,7 +683,7 @@ public function testDoesNotErrorOnFileExists() $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('404', $cmd); }, ]); - $this->assertFileNotExists('s3://bucket/key'); + $this->assertFileDoesNotExist('s3://bucket/key'); } public function testProvidesDirectoriesForS3() @@ -775,7 +750,7 @@ public function testProvidesDirectoriesForS3() $dir = 's3://bucket/key/'; $r = opendir($dir); - $this->assertInternalType('resource', $r); + $this->assertIsResource($r); $files = []; while (($file = readdir($r)) !== false) { @@ -793,6 +768,7 @@ public function testProvidesDirectoriesForS3() closedir($r); } + /** @doesNotPerformAssertions */ public function testCanSetDelimiterStreamContext() { $this->addMockResults($this->client, [ diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index 94a10fd54d..0eacfbc54e 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -9,6 +9,7 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -19,6 +20,7 @@ */ class StreamWrapperTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -27,7 +29,7 @@ class StreamWrapperTest extends TestCase /** @var LruArrayCache */ private $cache; - public function setUp() + public function _setUp() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -36,7 +38,7 @@ public function setUp() $this->client->registerStreamWrapper(); } - public function tearDown() + public function _tearDown() { stream_wrapper_unregister('s3'); $this->client = null; @@ -49,43 +51,36 @@ public function testRegistersStreamWrapperOnlyOnce() StreamWrapper::register($this->client); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Cannot open a bucket - */ public function testCannotOpenBuckets() { + $this->expectExceptionMessage("Cannot open a bucket"); + $this->expectWarning(); fopen('s3://bucket', 'r'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Mode not supported - */ public function testSupportsOnlyReadWriteXA() { + $this->expectExceptionMessage("Mode not supported"); + $this->expectWarning(); fopen('s3://bucket/key', 'c'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage s3://bucket/key already exists on Amazon S3 - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Bucket parameter parsed as ARN and failed with: Provided ARN was not a valid S3 access point ARN - */ public function testValidatesArn() { + $this->expectExceptionMessage("Bucket parameter parsed as ARN and failed with: Provided ARN was not a valid S3 access point ARN"); + $this->expectWarning(); fopen('s3://arn:aws:s3:us-east-1:123456789012:foo:myaccess/test_key', 'r'); } + /** @doesNotPerformAssertions */ public function testSuccessfulXMode() { $this->addMockResults( @@ -285,12 +280,10 @@ public function testCanWriteEmptyFileToStream() $this->assertSame('', (string) $cmd['Body']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } ]); @@ -356,12 +349,10 @@ public function testCanUnlinkFiles() $this->assertSame('bucket.s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testThrowsErrorsWhenUnlinkFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -373,22 +364,18 @@ public function testCreatingBucketWithNoBucketReturnsFalse() $this->assertFalse(mkdir('s3://')); } - /** - * @expectedExceptionMessage Bucket already exists: s3://already-existing-bucket - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Bucket already exists: s3://already-existing-bucket"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket'); } - /** - * @expectedExceptionMessage Subfolder already exists: s3://already-existing-bucket/key - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketForKeyRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Subfolder already exists: s3://already-existing-bucket/key"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket/key'); } @@ -441,24 +428,20 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $entries = $history->toArray(); $this->assertSame('HEAD', $entries[0]['request']->getMethod()); $this->assertSame('PUT', $entries[1]['request']->getMethod()); - $this->assertContains('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); + $this->assertStringContainsString('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage specify a bucket - */ public function testCannotDeleteS3() { + $this->expectExceptionMessage("specify a bucket"); + $this->expectWarning(); rmdir('s3://'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testRmDirWithExceptionTriggersError() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -498,7 +481,7 @@ public function testCanDeleteObjectWithRmDir($path) $this->assertCount(1, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); } public function testCanDeleteNestedFolderWithRmDir() @@ -518,37 +501,31 @@ public function testCanDeleteNestedFolderWithRmDir() $this->assertCount(2, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); $this->assertSame('DELETE', $entries[1]['request']->getMethod()); $this->assertSame('/bar/', $entries[1]['request']->getUri()->getPath()); - $this->assertContains('foo', $entries[1]['request']->getUri()->getHost()); + $this->assertStringContainsString('foo', $entries[1]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage rename(): Cannot rename a file across wrapper types - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage The Amazon S3 stream wrapper only supports copying objects - */ public function testRenameEnsuresKeyIsSet() { + $this->expectExceptionMessage("The Amazon S3 stream wrapper only supports copying objects"); + $this->expectWarning(); rename('s3://foo/bar', 's3://baz'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ public function testRenameWithExceptionThrowsError() { + $this->expectExceptionMessage("Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -646,12 +623,10 @@ public function testCanPullStatDataFromCache() $this->assertSame(123, filesize('s3://foo/bar')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ 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); }, @@ -661,12 +636,10 @@ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } stat('s3://bucket/key'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket - */ 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); }, ]); @@ -708,12 +681,10 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $this->assertSame(0040777, $stat['mode']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket/prefix - */ 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() @@ -783,12 +754,16 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) $this->assertCount(count($queue), $history); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage cannot represent a stream of type user-space - */ 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->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) ]); @@ -798,12 +773,10 @@ public function testStreamCastIsNotPossible() stream_select($read, $write, $except, 0); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage No client in stream context - */ public function testEnsuresClientIsSet() { + $this->expectExceptionMessage("No client in stream context"); + $this->expectWarning(); fopen('s3://bucket/key', 'r', false, stream_context_create([ 's3' => ['client' => null] ])); @@ -822,7 +795,7 @@ public function testDoesNotErrorOnFileExists() $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('404', $cmd); }, ]); - $this->assertFileNotExists('s3://bucket/key'); + $this->assertFileDoesNotExist('s3://bucket/key'); } public function testProvidesDirectoriesForS3() @@ -889,7 +862,7 @@ public function testProvidesDirectoriesForS3() $dir = 's3://bucket/key/'; $r = opendir($dir); - $this->assertInternalType('resource', $r); + $this->assertIsResource($r); $files = []; while (($file = readdir($r)) !== false) { @@ -907,6 +880,7 @@ public function testProvidesDirectoriesForS3() closedir($r); } + /** @doesNotPerformAssertions */ public function testCanSetDelimiterStreamContext() { $this->addMockResults($this->client, [ diff --git a/tests/S3/TransferTest.php b/tests/S3/TransferTest.php index ceee797d03..baedce7c6b 100644 --- a/tests/S3/TransferTest.php +++ b/tests/S3/TransferTest.php @@ -6,6 +6,7 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\S3\Transfer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; @@ -17,75 +18,61 @@ */ class TransferTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage base_dir - */ public function testEnsuresBaseDirIsAvailable() { + $this->expectExceptionMessage("base_dir"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, new \ArrayIterator([]), 's3://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot copy from s3 to s3. - */ public function testCannotCopyS3ToS3() { + $this->expectExceptionMessage("You cannot copy from s3 to s3."); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, 's3://baz/bam', 's3://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot copy from file to file. - */ public function testCannotCopyLocal() { + $this->expectExceptionMessage("You cannot copy from file to file."); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, __DIR__); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage mup_threshold must be >= 5MB - */ public function testEnsuresMupSizeIsValid() { + $this->expectExceptionMessage("mup_threshold must be >= 5MB"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, 's3://foo/bar', ['mup_threshold' => 10]); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage source must be the path to a directory or an - * iterator that yields file names - */ public function testEnsuresSourceIsValid() { + $this->expectExceptionMessage("source must be the path to a directory or an iterator that yields file names"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, false, 's3://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Scheme must be "s3" or "file" - */ public function testEnsuresValidScheme() { + $this->expectExceptionMessage("Scheme must be \"s3\" or \"file\""); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, 'monkey://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage before must be a callable - */ public function testEnsuresBeforeIsCallable() { + $this->expectExceptionMessage("before must be a callable"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, 's3://foo/bar', ['before' => 'cheese']); } @@ -123,7 +110,7 @@ public function testCanSetBeforeOptionForUploadsAndUsedWithDebug() $this->assertSame('PutObject', $test->getName()); $this->assertSame('foo', $test['Bucket']); $this->assertStringStartsWith('bar/', $test['Key']); - $this->assertContains($test['SourceFile'] . ' -> s3://foo/bar', $output); + $this->assertStringContainsString($test['SourceFile'] . ' -> s3://foo/bar', $output); } } @@ -157,7 +144,7 @@ public function testDoesMultipartForLargeFiles() $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); + $this->assertStringContainsString("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); `rm -rf $dir`; } @@ -191,7 +178,7 @@ public function testDoesMultipartForLargeFilesWithFileInfoAsSource() $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); + $this->assertStringContainsString("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); `rm -rf $dir`; } @@ -222,9 +209,9 @@ public function testDownloadsObjects() $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains('s3://foo/bar/../bar/a/b -> ', $output); - $this->assertContains('s3://foo/bar/c//d -> ', $output); - $this->assertContains('s3://foo/../bar//c/../a/b/.. -> ', $output); + $this->assertStringContainsString('s3://foo/bar/../bar/a/b -> ', $output); + $this->assertStringContainsString('s3://foo/bar/c//d -> ', $output); + $this->assertStringContainsString('s3://foo/../bar//c/../a/b/.. -> ', $output); `rm -rf $dir`; } @@ -289,19 +276,18 @@ function (CommandInterface $cmd, RequestInterface $req) { $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/../bar/a/b -> ', $output); - $this->assertContains('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/c//d -> ', $output); - $this->assertContains('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/../bar//c/../a/b/.. -> ', $output); + $this->assertStringContainsString('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/../bar/a/b -> ', $output); + $this->assertStringContainsString('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/c//d -> ', $output); + $this->assertStringContainsString('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/../bar//c/../a/b/.. -> ', $output); `rm -rf $dir`; } /** * @dataProvider providedPathsOutsideTarget - * - * @expectedException \Aws\Exception\AwsException */ public function testCannotDownloadObjectsOutsideTarget($key) { + $this->expectException(\Aws\Exception\AwsException::class); $s3 = $this->getTestClient('s3'); $lso = [ 'IsTruncated' => false, diff --git a/tests/S3/UseArnRegion/ConfigurationProviderTest.php b/tests/S3/UseArnRegion/ConfigurationProviderTest.php index 895aa13440..b61a9c27d1 100644 --- a/tests/S3/UseArnRegion/ConfigurationProviderTest.php +++ b/tests/S3/UseArnRegion/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\S3\UseArnRegion\ConfigurationInterface; use Aws\S3\UseArnRegion\ConfigurationProvider; use Aws\S3\UseArnRegion\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_ARN_REGION) ?: '', @@ -53,7 +56,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_ARN_REGION . '=' . self::$originalEnv['use_arn_region']); @@ -168,21 +171,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -196,12 +195,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -214,12 +211,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -288,11 +283,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } diff --git a/tests/S3/UseArnRegion/ConfigurationTest.php b/tests/S3/UseArnRegion/ConfigurationTest.php index 760a75d405..d7d69bbf4a 100644 --- a/tests/S3/UseArnRegion/ConfigurationTest.php +++ b/tests/S3/UseArnRegion/ConfigurationTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\S3\UseArnRegion; use Aws\S3\UseArnRegion\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider correctValueCases * @@ -44,12 +47,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - * @expectedExceptionMessage 'use_arn_region' config option must be a boolean value. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectExceptionMessage("'use_arn_region' config option must be a boolean value."); + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); new Configuration('not a boolean'); } } diff --git a/tests/S3Control/EndpointArnMiddlewareTest.php b/tests/S3Control/EndpointArnMiddlewareTest.php index 21e95ba2cf..4f02d08544 100644 --- a/tests/S3Control/EndpointArnMiddlewareTest.php +++ b/tests/S3Control/EndpointArnMiddlewareTest.php @@ -6,6 +6,7 @@ use Aws\Exception\InvalidRegionException; use Aws\Exception\UnresolvedEndpointException; use Aws\Middleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\S3Control\S3ControlTestingTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Response; @@ -17,6 +18,7 @@ */ class EndpointArnMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use S3ControlTestingTrait; /** @@ -58,7 +60,7 @@ public function testCorrectlyModifiesRequestAndCommand( $req->getUri()->getHost() ); $this->assertSame("/{$target}", $req->getRequestTarget()); - $this->assertContains( + $this->assertStringContainsString( "/{$signingRegion}/{$signingService}", $req->getHeader('Authorization')[0] ); diff --git a/tests/SdkTest.php b/tests/SdkTest.php index 66975b9270..e000f7df33 100644 --- a/tests/SdkTest.php +++ b/tests/SdkTest.php @@ -5,6 +5,7 @@ use Aws\MultiRegionClient; use Aws\S3\S3MultiRegionClient; use Aws\Sdk; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,11 +13,11 @@ */ class SdkTest extends TestCase { - /** - * @expectedException \BadMethodCallException - */ + use PHPUnitCompatTrait; + public function testEnsuresMissingMethodThrowsException() { + $this->expectException(\BadMethodCallException::class); (new Sdk)->foo(); } diff --git a/tests/Signature/S3SignatureV4Test.php b/tests/Signature/S3SignatureV4Test.php index 76f68a591e..0cf7198ac6 100644 --- a/tests/Signature/S3SignatureV4Test.php +++ b/tests/Signature/S3SignatureV4Test.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Signature\S3SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; require_once __DIR__ . '/sig_hack.php'; @@ -13,11 +14,18 @@ */ class S3SignatureV4Test extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC'); } + public static function _tearDownAfterClass() + { + unset($_SERVER['aws_time']); + } + private function getFixtures() { $request = new Request('GET', 'http://foo.com'); @@ -90,7 +98,7 @@ public function testCreatesPresignedDatesFromDateTime() $credentials, new \DateTime('December 11, 2013 00:00:00 UTC') )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testCreatesPresignedDatesFromUnixTimestamp() @@ -101,7 +109,7 @@ public function testCreatesPresignedDatesFromUnixTimestamp() $credentials, 1386720000 )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testCreatesPresignedDateFromStrtotime() @@ -112,7 +120,7 @@ public function testCreatesPresignedDateFromStrtotime() $credentials, 'December 11, 2013 00:00:00 UTC' )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testCreatesPresignedDateFromStrtotimeRelativeTimeBase() @@ -124,7 +132,7 @@ public function testCreatesPresignedDateFromStrtotimeRelativeTimeBase() '+6 days', ['start_time' => $_SERVER['aws_time']] )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testAddsSecurityTokenIfPresent() @@ -140,8 +148,8 @@ public function testAddsSecurityTokenIfPresent() $credentials, 1386720000 )->getUri(); - $this->assertContains('X-Amz-Security-Token=123', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Security-Token=123', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testUsesStartDateIfSpecified() @@ -152,15 +160,13 @@ public function testUsesStartDateIfSpecified() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresSigV4DurationIsLessThanOneWeek() { + $this->expectException(\InvalidArgumentException::class); list($request, $credentials, $signature) = $this->getFixtures(); $signature->presign( $request, diff --git a/tests/Signature/SignatureProviderTest.php b/tests/Signature/SignatureProviderTest.php index 1908b0e157..df652ba20c 100644 --- a/tests/Signature/SignatureProviderTest.php +++ b/tests/Signature/SignatureProviderTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Signature; use Aws\Signature\SignatureProvider; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class SignatureProviderTest extends TestCase { + use PHPUnitCompatTrait; + public function versionProvider() { return [ @@ -52,11 +55,9 @@ public function testResolvesSignaturesSuccessfully() ); } - /** - * @expectedException \Aws\Exception\UnresolvedSignatureException - */ public function testResolvesSignaturesWithException() { + $this->expectException(\Aws\Exception\UnresolvedSignatureException::class); $fn = SignatureProvider::defaultProvider(); SignatureProvider::resolve($fn, 'foooo', '', ''); } diff --git a/tests/Signature/SignatureV4Test.php b/tests/Signature/SignatureV4Test.php index a746107ba2..0ccb6ffad8 100644 --- a/tests/Signature/SignatureV4Test.php +++ b/tests/Signature/SignatureV4Test.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Signature\SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\NoSeekStream; @@ -15,15 +16,24 @@ */ class SignatureV4Test extends TestCase { + use PHPUnitCompatTrait; + const DEFAULT_KEY = 'AKIDEXAMPLE'; const DEFAULT_SECRET = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'; const DEFAULT_DATETIME = 'Mon, 09 Sep 2011 23:36:00 GMT'; - public function setup() + public function _setUp() { $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC'); } + public function _tearDown() + { + parent::tearDown(); + + unset($_SERVER['aws_time']); + } + public function testReturnsRegionAndService() { $s = new SignatureV4('foo', 'bar'); @@ -125,7 +135,7 @@ public function testCreatesPresignedDatesFromDateTime($dateTime) $credentials, $dateTime )->getUri(); - $this->assertContains('X-Amz-Expires=518400',$url); + $this->assertStringContainsString('X-Amz-Expires=518400',$url); } @@ -135,7 +145,7 @@ public function testCreatesPresignedDatesFromUnixTimestamp() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request,$credentials,1386720000)->getUri(); - $this->assertContains('X-Amz-Expires=518400',$url); + $this->assertStringContainsString('X-Amz-Expires=518400',$url); } public function testCreatesPresignedDateFromStrtotime() @@ -148,7 +158,7 @@ public function testCreatesPresignedDateFromStrtotime() $credentials, 'December 11, 2013 00:00:00 UTC' )->getUri(); - $this->assertContains('X-Amz-Expires=518400',$url); + $this->assertStringContainsString('X-Amz-Expires=518400',$url); } public function testAddsSecurityTokenIfPresentInPresigned() @@ -159,8 +169,8 @@ public function testAddsSecurityTokenIfPresentInPresigned() $request = $signature->presign($request, $credentials, 1386720000); $this->assertEmpty($request->getHeader('X-Amz-Security-Token')); $url = (string) $request->getUri(); - $this->assertContains('X-Amz-Security-Token=123', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Security-Token=123', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function getStartDateTimeInterfaceInputs() @@ -186,8 +196,8 @@ public function testUsesStartDateFromDateTimeIfPresent($dateTime) list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testUsesStartDateFromUnixTimestampIfPresent() @@ -198,8 +208,8 @@ public function testUsesStartDateFromUnixTimestampIfPresent() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testUsesStartDateFromStrtotimeIfPresent() @@ -210,15 +220,13 @@ public function testUsesStartDateFromStrtotimeIfPresent() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresSigV4DurationIsLessThanOneWeek() { + $this->expectException(\InvalidArgumentException::class); $_SERVER['override_v4_time'] = true; list($request, $credentials, $signature) = $this->getFixtures(); $signature->presign($request, $credentials, 'December 31, 2013 00:00:00 UTC'); @@ -254,11 +262,9 @@ public function testConvertsPostToGet() $this->assertSame('foo=bar&baz=bam', $request->getUri()->getQuery()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresMethodIsPost() { + $this->expectException(\InvalidArgumentException::class); $request = new Request('PUT', 'http://foo.com'); SignatureV4::convertPostToGet($request); } @@ -274,7 +280,7 @@ public function testSignSpecificHeaders() 'content-md5' => 'bogus' ]); $signed = $sig->signRequest($req, $creds); - $this->assertContains('content-md5;host;x-amz-date;x-amz-foo', $signed->getHeaderLine('Authorization')); + $this->assertStringContainsString('content-md5;host;x-amz-date;x-amz-foo', $signed->getHeaderLine('Authorization')); } public function testPresignSpecificHeaders() @@ -290,7 +296,7 @@ public function testPresignSpecificHeaders() 'x-amz-content-sha256' => 'abc', ]); $presigned = $sig->presign($req, $creds, '+5 minutes'); - $this->assertContains(urlencode('host;x-amz-foo;content-md5;x-amz-meta-foo'), (string)$presigned->getUri()); + $this->assertStringContainsString(urlencode('host;x-amz-foo;content-md5;x-amz-meta-foo'), (string)$presigned->getUri()); } public function testPresignBlacklistedHeaders() @@ -303,27 +309,23 @@ public function testPresignBlacklistedHeaders() 'Content-Type' => 'text/html', ]); $presigned = $sig->presign($req, $creds, '+5 minutes'); - $this->assertNotContains('user-agent', (string)$presigned->getUri()); - $this->assertNotContains('X-Amz-User-Agent', (string)$presigned->getUri()); - $this->assertNotContains('content-length', (string)$presigned->getUri()); - $this->assertNotContains('Content-Type', (string)$presigned->getUri()); + $this->assertStringNotContainsString('user-agent', (string)$presigned->getUri()); + $this->assertStringNotContainsString('X-Amz-User-Agent', (string)$presigned->getUri()); + $this->assertStringNotContainsString('content-length', (string)$presigned->getUri()); + $this->assertStringNotContainsString('Content-Type', (string)$presigned->getUri()); } - /** - * @expectedException \Aws\Exception\CouldNotCreateChecksumException - */ public function testEnsuresContentSha256CanBeCalculated() { + $this->expectException(\Aws\Exception\CouldNotCreateChecksumException::class); list($request, $credentials, $signature) = $this->getFixtures(); $request = $request->withBody(new NoSeekStream(Psr7\Utils::streamFor('foo'))); $signature->signRequest($request, $credentials); } - /** - * @expectedException \Aws\Exception\CouldNotCreateChecksumException - */ public function testEnsuresContentSha256CanBeCalculatedWhenSeekFails() { + $this->expectException(\Aws\Exception\CouldNotCreateChecksumException::class); list($request, $credentials, $signature) = $this->getFixtures(); $stream = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [ 'seek' => function () { @@ -334,6 +336,7 @@ public function testEnsuresContentSha256CanBeCalculatedWhenSeekFails() $signature->signRequest($request, $credentials); } + /** @doesNotPerformAssertions */ public function testUnsignedPayloadProvider() { return [ @@ -411,6 +414,7 @@ public function testSignRequestUnsignedPayload($req, $sreq, $creq) $this->assertSame($sreq, Psr7\Message::toString($signature->signRequest($request, $credentials))); } + /** @doesNotPerformAssertions */ public function testProvider() { return [ diff --git a/tests/Sqs/SqsClientTest.php b/tests/Sqs/SqsClientTest.php index ca62b2f3f8..a3ba034678 100644 --- a/tests/Sqs/SqsClientTest.php +++ b/tests/Sqs/SqsClientTest.php @@ -4,6 +4,7 @@ use Aws\Middleware; use Aws\Result; use Aws\Sqs\SqsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -12,6 +13,7 @@ */ class SqsClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testGetQueueArn() @@ -36,12 +38,10 @@ public function testFifoQueueArn() $this->assertSame($arn, $sqs->getQueueArn($url)); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage MD5 mismatch. Expected foo, found ddc35f88fa71b6ef142ae61f35364653 - */ public function testValidatesMd5OfBody() { + $this->expectExceptionMessage("MD5 mismatch. Expected foo, found ddc35f88fa71b6ef142ae61f35364653"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -52,12 +52,10 @@ public function testValidatesMd5OfBody() $client->receiveMessage(['QueueUrl' => 'http://foo.com']); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage Attribute MD5 mismatch. Expected foo, found ee5a4b60facbcc4723c1b5b8baca2593 - */ public function testValidatesMd5OfMessageAttributes() { + $this->expectExceptionMessage("Attribute MD5 mismatch. Expected foo, found ee5a4b60facbcc4723c1b5b8baca2593"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -110,12 +108,10 @@ public function testValidatesMd5OfMessageAttributes() ]); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage No Attribute MD5 found. Expected 0408bb33aa149494a6a4683d58a7133f - */ public function testValidatesMd5OfMessageAttributesExists() { + $this->expectExceptionMessage("No Attribute MD5 found. Expected 0408bb33aa149494a6a4683d58a7133f"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -139,12 +135,10 @@ public function testValidatesMd5OfMessageAttributesExists() ]); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage Attribute MD5 mismatch. Expected foo, found No Attributes - */ public function testValidatesMessageAttributesExistWithMd5() { + $this->expectExceptionMessage("Attribute MD5 mismatch. Expected foo, found No Attributes"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -163,6 +157,7 @@ public function testValidatesMessageAttributesExistWithMd5() ]); } + /** @doesNotPerformAssertions */ public function testSkipsCommandsThatAreNotReceiveMessage() { $client = new SqsClient([ diff --git a/tests/StreamRequestPayloadMiddlewareTest.php b/tests/StreamRequestPayloadMiddlewareTest.php index a3bde2ccc3..dd98140f96 100644 --- a/tests/StreamRequestPayloadMiddlewareTest.php +++ b/tests/StreamRequestPayloadMiddlewareTest.php @@ -9,6 +9,7 @@ use Aws\Middleware; use Aws\Result; use Aws\StreamRequestPayloadMiddleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; @@ -19,6 +20,7 @@ */ class StreamRequestPayloadMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; /** * @dataProvider generateTestCases @@ -112,12 +114,10 @@ public function generateTestCases() ]; } - /** - * @expectedException \Aws\Exception\IncalculablePayloadException - * @expectedExceptionMessage Payload content length is required and can not be calculated. - */ public function testThrowsExceptionOnIncalculableSize() { + $this->expectExceptionMessage("Payload content length is required and can not be calculated."); + $this->expectException(\Aws\Exception\IncalculablePayloadException::class); $service = $this->generateTestService(); $client = $this->generateTestClient($service); $command = $client->getCommand( diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index d35f39d8b6..024b94949a 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\Sts\RegionalEndpoints\ConfigurationInterface; use Aws\Sts\RegionalEndpoints\ConfigurationProvider; use Aws\Sts\RegionalEndpoints\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', @@ -54,7 +57,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '=' . self::$originalEnv['endpoints_type']); @@ -168,21 +171,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -196,12 +195,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -214,12 +211,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -288,11 +283,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -402,12 +395,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid STS regional endpoints configuration argument. - */ public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid STS regional endpoints configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/Sts/RegionalEndpoints/ConfigurationTest.php b/tests/Sts/RegionalEndpoints/ConfigurationTest.php index 5828d04ac2..f7767a5b53 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\Sts\RegionalEndpoints; use Aws\Sts\RegionalEndpoints\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('regional'); @@ -25,12 +28,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new Configuration('invalid_type'); } } diff --git a/tests/Sts/StsClientTest.php b/tests/Sts/StsClientTest.php index df4523bccb..e7a0f63732 100644 --- a/tests/Sts/StsClientTest.php +++ b/tests/Sts/StsClientTest.php @@ -8,6 +8,7 @@ use Aws\Result; use Aws\Sts\RegionalEndpoints\Configuration; use Aws\Sts\StsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Uri; use PHPUnit\Framework\TestCase; @@ -16,6 +17,8 @@ */ class StsClientTest extends TestCase { + use PHPUnitCompatTrait; + public function testCanCreateCredentialsObjectFromStsResult() { $result = new Result([ @@ -36,26 +39,22 @@ public function testCanCreateCredentialsObjectFromStsResult() $this->assertSame('foo', $credentials->getAccessKeyId()); $this->assertSame('bar', $credentials->getSecretKey()); $this->assertSame('baz', $credentials->getSecurityToken()); - $this->assertInternalType('int', $credentials->getExpiration()); + $this->assertIsInt($credentials->getExpiration()); $this->assertFalse($credentials->isExpired()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Result contains no credentials - */ public function testThrowsExceptionWhenCreatingCredentialsFromInvalidInput() { + $this->expectExceptionMessage("Result contains no credentials"); + $this->expectException(\InvalidArgumentException::class); $client = new StsClient(['region' => 'us-east-1', 'version' => 'latest']); $client->createCredentials(new Result()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testAddsStsRegionalEndpointsArgument() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new StsClient([ 'region' => 'us-east-1', 'version' => 'latest', diff --git a/tests/TraceMiddlewareTest.php b/tests/TraceMiddlewareTest.php index 3a228c4140..4fb528d2c7 100644 --- a/tests/TraceMiddlewareTest.php +++ b/tests/TraceMiddlewareTest.php @@ -7,6 +7,7 @@ use Aws\Exception\AwsException; use Aws\HandlerList; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\TraceMiddleware; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; @@ -19,6 +20,8 @@ */ class TraceMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; + public function testEmitsDebugInfo() { $str = ''; @@ -48,15 +51,15 @@ public function testEmitsDebugInfo() $request = new Request('GET', 'http://foo.com'); $handler($command, $request); Promise\queue()->run(); - $this->assertContains("-> Entering step init, name ''", $str); - $this->assertContains('command was set to array', $str); - $this->assertContains('request was set to array', $str); - $this->assertContains("<- Leaving step init, name ''", $str); - $this->assertContains('result was set to array', $str); - $this->assertContains('Inclusive step time: ', $str); - $this->assertContains('command.params.b was unset', $str); - $this->assertContains('no changes', $str); - $this->assertContains("<- Leaving step validate, name ''", $str); + $this->assertStringContainsString("-> Entering step init, name ''", $str); + $this->assertStringContainsString('command was set to array', $str); + $this->assertStringContainsString('request was set to array', $str); + $this->assertStringContainsString("<- Leaving step init, name ''", $str); + $this->assertStringContainsString('result was set to array', $str); + $this->assertStringContainsString('Inclusive step time: ', $str); + $this->assertStringContainsString('command.params.b was unset', $str); + $this->assertStringContainsString('no changes', $str); + $this->assertStringContainsString("<- Leaving step validate, name ''", $str); } public function testTracksExceptions() @@ -84,11 +87,11 @@ public function testTracksExceptions() $request = new Request('GET', 'http://foo.com'); $handler($command, $request); Promise\queue()->run(); - $this->assertContains('error was set to array', $str); - $this->assertContains('trace', $str); - $this->assertContains('class', $str); - $this->assertContains('message', $str); - $this->assertContains('string(6) "Oh no!"', $str); + $this->assertStringContainsString('error was set to array', $str); + $this->assertStringContainsString('trace', $str); + $this->assertStringContainsString('class', $str); + $this->assertStringContainsString('message', $str); + $this->assertStringContainsString('string(6) "Oh no!"', $str); } public function testTracksAwsSpecificExceptions() @@ -119,11 +122,11 @@ public function testTracksAwsSpecificExceptions() $request = new Request('GET', 'http://foo.com'); $handler($command, $request); Promise\queue()->run(); - $this->assertContains('error was set to array', $str); - $this->assertContains('trace', $str); - $this->assertContains('class', $str); - $this->assertContains('message', $str); - $this->assertContains('string(5) "error"', $str); + $this->assertStringContainsString('error was set to array', $str); + $this->assertStringContainsString('trace', $str); + $this->assertStringContainsString('class', $str); + $this->assertStringContainsString('message', $str); + $this->assertStringContainsString('string(5) "error"', $str); } /** @@ -160,11 +163,11 @@ public function testScrubsAuthStrings($key, $signature, array $headers) ); $handler($command, $request); - $this->assertNotContains($key, $str); - $this->assertNotContains($signature, $str); + $this->assertStringNotContainsString($key, $str); + $this->assertStringNotContainsString($signature, $str); foreach ($headers as $header) { - $this->assertNotContains($header['raw'], $str); - $this->assertContains($header['scrubbed'], $str); + $this->assertStringNotContainsString($header['raw'], $str); + $this->assertStringContainsString($header['scrubbed'], $str); } } @@ -206,14 +209,14 @@ public function testRedactsSensitiveTraits() $request = new Request('post', "/"); $handler($command, $request); - $this->assertContains("NestedParams also not redacted", $str); - $this->assertContains("PublicParameter not redacted", $str); - $this->assertContains("[SensitiveParameter]", $str); - $this->assertNotContains("SensitiveParameter was redacted", $str); - $this->assertContains("[NestedSensitiveParameter]", $str); - $this->assertNotContains("NestedSensitiveParameter was also redacted", $str); - $this->assertContains("[SensitiveArray]", $str); - $this->assertNotContains("SensitiveArray contents also redacted", $str); + $this->assertStringContainsString("NestedParams also not redacted", $str); + $this->assertStringContainsString("PublicParameter not redacted", $str); + $this->assertStringContainsString("[SensitiveParameter]", $str); + $this->assertStringNotContainsString("SensitiveParameter was redacted", $str); + $this->assertStringContainsString("[NestedSensitiveParameter]", $str); + $this->assertStringNotContainsString("NestedSensitiveParameter was also redacted", $str); + $this->assertStringContainsString("[SensitiveArray]", $str); + $this->assertStringNotContainsString("SensitiveArray contents also redacted", $str); } public function authStringProvider() @@ -273,9 +276,9 @@ public function testCanScrubOnArbitraryPatterns() ); $handler($command, $request); - $this->assertNotContains($toScrub, $str); + $this->assertStringNotContainsString($toScrub, $str); foreach (array_values($scrubPatterns) as $scrubbed) { - $this->assertContains($scrubbed, $str); + $this->assertStringContainsString($scrubbed, $str); } } diff --git a/tests/WaiterTest.php b/tests/WaiterTest.php index c6467f5cff..2387f0d534 100644 --- a/tests/WaiterTest.php +++ b/tests/WaiterTest.php @@ -6,6 +6,7 @@ use Aws\DynamoDb\DynamoDbClient; use Aws\Exception\AwsException; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; @@ -21,13 +22,12 @@ */ class WaiterTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - */ public function testErrorOnBadConfig() { + $this->expectException(\InvalidArgumentException::class); $provider = ApiProvider::defaultProvider(); $client = new DynamoDbClient([ 'region' => 'foo', @@ -44,11 +44,9 @@ public function testErrorOnBadConfig() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testErrorOnBadBeforeCallback() { + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('DynamoDb'); $client->waitUntil( 'TableExists', @@ -59,6 +57,7 @@ public function testErrorOnBadBeforeCallback() ); } + /** @doesNotPerformAssertions */ public function testContinueWaitingOnHandlerError() { $retries = 10; @@ -91,6 +90,7 @@ public function testContinueWaitingOnHandlerError() ]); } + /** @doesNotPerformAssertions */ public function testCanCancel() { $client = $this->getTestClient('DynamoDb'); diff --git a/tests/WrappedHttpHandlerTest.php b/tests/WrappedHttpHandlerTest.php index d8c1a0df57..5ee622d8cc 100644 --- a/tests/WrappedHttpHandlerTest.php +++ b/tests/WrappedHttpHandlerTest.php @@ -10,6 +10,7 @@ use Aws\CommandInterface; use Aws\Exception\AwsException; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\WrappedHttpHandler; use GuzzleHttp\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; @@ -23,6 +24,7 @@ */ class WrappedHttpHandlerTest extends TestCase { + use PHPUnitCompatTrait; use TestServiceTrait; public function testParsesResponses() @@ -59,12 +61,10 @@ public function testParsesResponses() ], $result['@metadata']); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage The HTTP handler was rejected without an "exception" key value pair. - */ public function testEnsuresErrorHasExceptionKey() { + $this->expectExceptionMessage("The HTTP handler was rejected without an \"exception\" key value pair."); + $this->expectException(\RuntimeException::class); $cmd = new Command('foo'); $req = new Request('GET', 'http://foo.com'); $handler = function () { return new RejectedPromise([]); }; @@ -373,7 +373,7 @@ public function testPassesOnTransferStatsCallbackToHandlerWhenRequested() { $handler = function ($request, array $options) { $this->assertArrayHasKey('http_stats_receiver', $options); - $this->assertInternalType('callable', $options['http_stats_receiver']); + $this->assertIsCallable($options['http_stats_receiver']); return new Response; }; diff --git a/tests/bootstrap.php b/tests/bootstrap.php index b8f8d6c0b2..c4cde91a15 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,17 +3,21 @@ date_default_timezone_set('UTC'); // Include the composer autoloader -$loader = require __DIR__ . '/../vendor/autoload.php'; +$loader = require __DIR__.'/../vendor/autoload.php'; -if (!class_exists('\PHPUnit\Framework\Constraint\RegularExpression')) { +if ( ! defined('PHPUNIT_COMPOSER_INSTALL')) { + 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\Constraint\Callback')) { + class_alias('\PHPUnit_Framework_Constraint_Callback', '\PHPUnit\Framework\Constraint\Callback'); } -if (!class_exists('\PHPUnit\Framework\Error\Warning')) { +if ( ! class_exists('\PHPUnit\Framework\Error\Warning')) { class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warning'); } @@ -22,10 +26,13 @@ class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warnin // Patch PHPUnit class for PHP 7.4+ and PHPUnit 5.x to avoid deprecation warning // Necessary because older versions of PHPUnit are no longer supported -$version = PHPUnit_Runner_Version::id(); +$version = class_exists('PHPUnit_Runner_Version') ? PHPUnit_Runner_Version::id() : PHPUnit\Runner\Version::id(); $versionData = explode('.', $version); + +include_once(sprintf("%s/Polyfill/PHPUnit%s/PHPUnitCompatTrait.php", __DIR__, $versionData[0])); + if (PHP_VERSION_ID >= 70400 && $versionData[0] == 5) { - $vendorGeneratorPath = __DIR__ . '/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; - $patchGeneratorPath = __DIR__ . '/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; + $vendorGeneratorPath = __DIR__.'/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; + $patchGeneratorPath = __DIR__.'/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; file_put_contents($vendorGeneratorPath, file_get_contents($patchGeneratorPath)); } From 5963c8c897075166b83401fba99a41835d173729 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Tue, 17 May 2022 09:49:46 +0200 Subject: [PATCH 02/31] Replace key-fixture in CloudFront-tests with generated keys --- tests/CloudFront/CloudFrontClientTest.php | 4 ++-- tests/CloudFront/CookieSignerTest.php | 3 +-- tests/CloudFront/SignerTest.php | 1 - tests/CloudFront/UrlSignerTest.php | 4 ++-- tests/CloudFront/fixtures/test2.pem | 27 ----------------------- 5 files changed, 5 insertions(+), 34 deletions(-) delete mode 100644 tests/CloudFront/fixtures/test2.pem diff --git a/tests/CloudFront/CloudFrontClientTest.php b/tests/CloudFront/CloudFrontClientTest.php index 4ab56beea1..64e67425fd 100644 --- a/tests/CloudFront/CloudFrontClientTest.php +++ b/tests/CloudFront/CloudFrontClientTest.php @@ -7,7 +7,7 @@ use PHPUnit\Framework\TestCase; /** - * @covers Aws\CloudFront\CloudFrontClient + * @covers CloudFrontClient */ class CloudFrontClientTest extends TestCase { @@ -18,7 +18,7 @@ class CloudFrontClientTest extends TestCase public function _setUp() { - $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; } diff --git a/tests/CloudFront/CookieSignerTest.php b/tests/CloudFront/CookieSignerTest.php index 791fcfffa4..5d8742b44f 100644 --- a/tests/CloudFront/CookieSignerTest.php +++ b/tests/CloudFront/CookieSignerTest.php @@ -2,7 +2,6 @@ namespace Aws\Test\CloudFront; use Aws\CloudFront\CookieSigner; -use Aws\CloudFront\Policy; use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; @@ -15,7 +14,7 @@ class CookieSignerTest extends TestCase public function _setUp() { - $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; } diff --git a/tests/CloudFront/SignerTest.php b/tests/CloudFront/SignerTest.php index 7d992a1156..43800fc73c 100644 --- a/tests/CloudFront/SignerTest.php +++ b/tests/CloudFront/SignerTest.php @@ -1,7 +1,6 @@ key = realpath(__DIR__.'/fixtures/test2.pem'); + openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; } diff --git a/tests/CloudFront/fixtures/test2.pem b/tests/CloudFront/fixtures/test2.pem deleted file mode 100644 index 0bfb6e4a57..0000000000 --- a/tests/CloudFront/fixtures/test2.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEAxTbyKHzrPyxD91YYgq5R87tt66oX+OjJrMQI9MGp74t/N7+V -4uCGyPc5pXDgMtPO5JNAaEfkxJUosn3/g+0i/xnl7INOLrLRTLbOSBMAZVusLhlR -2l+iXPeFNrxwPxRSoROx5T9r2/rBvSwhUsDUJREPBz2IyUdbq+893QUytIm7DYSJ -NkgJFL7bIXxzQISZmfZ6ocJ1qpKuOsiAZdUu6Eaox8jdalvSqrgKhPhQ85T3HG6L -nlnEwMJAQHauwhVBaTzOybyycfvKVQNlT+JN1JnKQvdbt9lQxYVtLhZ9CEKcY41Q -3Yqyb+1MBl49C4kppYoZ5ZllIRa8sbHGk3gxgQIDAQABAoIBAQCPrwyXOwwaJqIO -HggVjfPfY/sd6/szOkdVPC5aRI8PG89ASrFlbrhEyvqQ8sAlx/PAzRfr4hVmtFXG -Vc5HzAnnWnMN8kyP8XBUOAvqrw1my3eSzpe4Rl0A5sWDr58IFkJtYPAHWkG3L+bf -cLuGkz79EoSkfcye+QJtLg0gbp0WsspfgnRxF0xKQu7H2MWkzppXzWOehxWc6YtJ -LIlBicnAQGOIbX0tghpguYNe/HsOyM5Mh1Q7AzTj6fhISxX8l/zjE5k/d9qPjk2S -hTYKYGTY11FCF6mhnRSt5hCop/N4lS+jR1ld3rbuKUzDMsuJFGKpM+8Vdn82gP7S -SzFBExzBAoGBAOyjSfKlCjojRtQ9G7D7oc11UnwP0tF73IonVoRrYyPub153/Nlc -DMB5YLCHl8u51TtPLpLH9tK+aQKaCpLoKkGxU1IK/pCGIL9JSJzyAkhajNtg/hmh -kWUdTQ9wckb5a+0VBjDPCgx4xk3sKC9fdWcrmETDs/hpJS8qz3v91N9NAoGBANVZ -4fPREN8rYIRABM/r8sd5+bIHrmFxWTb0iumx/B2Uf1z3HNDDOwUNe/WOSbZiMlsz -wK+3OoUygDT+yGvYpF6ZpjWtpPcuyKLxYQzICnISgjsohpwWt33LjGCqDtxuvcNx -JaDrLj+vZJzMr76PD6+z4KydErcAePoMDWZrfqkFAoGAO/elZbgtP05xRJe3zMH3 -3vk8TfQ0mKGq4dfWNPiBxzlFP8toaCzLjnsz5Yh3D0mon78RLmE+S2m1ctNWmqP7 -EWq+kqv2lulmoxMPM7agnXVU/MM3oYcwMU+bl64HR7UthIcvam8NPNveZSDTji3C -ssJ5c/OkR+9dXPacXe+VYoECgYEAuqxAVVKxznJnqo9RJpOuAvcokKrD2yKQCtOA -z+UZUNBjd/YHUmnftBYORdZPjLLymHX5vEU3gN+k6bmbpzEQ8GzDzue2FUjr6BYG -8mX9Lb4gEJ7u2JfPyNNWaiWhhyGmC+FuKRRdjP9rqv41LyiBcxySErYEb/aL40y0 -VM7tLfkCgYEArKYfLKzkJmicUQ7xzRIEM66DEynUEwH5VeTzHBO3Eszgj5w9C7rj -e+dGdUEJ6ie5J6QVLfT7oUCCuKF7Mrhvho8NLeObtzt2URRxQmQQfWH1TSzaarc0 -GQi4IIkGDLJeTow+7N2RB29zNDW6edh7vkoEJwvqIuC4bj4/wsEdfCI= ------END RSA PRIVATE KEY----- From 73595b33a4ba4236ed35a198d3e6966eb7b5af67 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Wed, 16 Mar 2022 09:57:21 +0100 Subject: [PATCH 03/31] Additional changes to unittest for phpunit9-compatibility --- tests/Api/ServiceTest.php | 7 +- tests/ClientResolverTest.php | 6 +- .../InstanceProfileProviderTest.php | 8 +- .../ConfigurationProviderTest.php | 37 +++--- tests/DefaultsMode/ConfigurationTest.php | 9 +- tests/DynamoDb/DynamoDbClientTest.php | 4 +- tests/Endpoint/PartitionTest.php | 4 +- .../ConfigurationProviderTest.php | 31 ++---- .../ConfigurationTest.php | 16 +-- .../ConfigurationProviderTest.php | 31 ++---- .../UseFipsEndpoint/ConfigurationTest.php | 9 +- .../EventBridgeEndpointMiddlewareTest.php | 5 +- tests/S3/StreamWrapperTest.php | 5 +- tests/S3/StreamWrapperV2ExistenceTest.php | 105 ++++++++---------- .../ConfigurationProviderTest.php | 2 +- 15 files changed, 121 insertions(+), 158 deletions(-) diff --git a/tests/Api/ServiceTest.php b/tests/Api/ServiceTest.php index 3458e535ce..6313559285 100644 --- a/tests/Api/ServiceTest.php +++ b/tests/Api/ServiceTest.php @@ -178,7 +178,6 @@ public function serializerDataProvider() /** * @dataProvider serializerDataProvider - * @doesNotPerformAssertions */ public function testCreatesSerializer($type, $cl) { @@ -203,7 +202,6 @@ public function parserDataProvider() /** * @dataProvider parserDataProvider - * @doesNotPerformAssertions */ public function testCreatesParsers($type, $cl) { @@ -215,8 +213,9 @@ function () { return []; } $this->assertInstanceOf($cl, $parser); if ($parser instanceof QueryParser) { - $this->assertAttributeInstanceOf( - 'Aws\Api\Parser\XmlParser', 'parser', $parser + $this->assertInstanceOf( + 'Aws\Api\Parser\XmlParser', + $this->readAttribute($parser, 'parser') ); } } diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index 7d96eda0b6..8da3967fb1 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -612,12 +612,10 @@ public function testDualstackEndpointInIsoPartition() ); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Dual-stack is not supported in ISO regions - */ public function testDualstackEndpointFailureOnDualstackNotSupported() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Dual-stack is not supported in ISO regions"); $data = json_decode( file_get_contents(__DIR__ . '/Endpoint/fixtures/dualstack_endpoints.json'), true diff --git a/tests/Credentials/InstanceProfileProviderTest.php b/tests/Credentials/InstanceProfileProviderTest.php index 27f7fed545..4c87a66973 100644 --- a/tests/Credentials/InstanceProfileProviderTest.php +++ b/tests/Credentials/InstanceProfileProviderTest.php @@ -986,7 +986,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsYieldsExpiredCreds($cl $creds = $provider()->wait(); $message = stream_get_contents($capture); - $this->assertRegExp('/Attempting credential expiration extension/', $message); + $this->assertMatchesRegularExpression('/Attempting credential expiration extension/', $message); $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('baz', $creds->getSecretKey()); $this->assertFalse($creds->isExpired()); @@ -1008,7 +1008,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsYieldsExpiredCreds($cl $result = $s3Client->listBuckets(); $this->assertEquals('Request sent', $result['message']); - $this->assertAttributeLessThanOrEqual(3, 'attempts', $provider); + $this->assertLessThanOrEqual(3,$this->readAttribute($provider,'attempts')); } public function returnsExpiredCredsProvider() @@ -1072,7 +1072,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsUnavailable($client) $creds = $provider($expiredCreds)->wait(); $message = stream_get_contents($capture); - $this->assertRegExp('/Attempting credential expiration extension/', $message); + $this->assertMatchesRegularExpression('/Attempting credential expiration extension/', $message); $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('baz', $creds->getSecretKey()); $this->assertFalse($expiredCreds->isExpired()); @@ -1094,7 +1094,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsUnavailable($client) $result = $s3Client->listBuckets(); $this->assertEquals('Request sent', $result['message']); - $this->assertAttributeLessThanOrEqual(3, 'attempts', $provider); + $this->assertLessThanOrEqual(3,$this->readAttribute($provider,'attempts')); } public function imdsUnavailableProvider() diff --git a/tests/DefaultsMode/ConfigurationProviderTest.php b/tests/DefaultsMode/ConfigurationProviderTest.php index e66a0b6404..eca5da78d4 100644 --- a/tests/DefaultsMode/ConfigurationProviderTest.php +++ b/tests/DefaultsMode/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\DefaultsMode\ConfigurationInterface; use Aws\DefaultsMode\ConfigurationProvider; use Aws\DefaultsMode\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_MODE) ?: '', @@ -53,7 +56,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_MODE . '=' . self::$originalEnv['mode']); @@ -167,21 +170,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -195,12 +194,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'foo' not found in"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -213,12 +210,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Invalid config file:"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -285,11 +280,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -406,12 +399,10 @@ public function testCreatesLegacy() self::assertNull($config->getStsRegionalEndpoints()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage is not a valid mode. The mode has to be 'legacy', 'standard', 'cross-region', 'in-region', 'mobile', or 'auto'. - */ public function testThrowsForInvalidUnwrapArgument() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage("is not a valid mode. The mode has to be 'legacy', 'standard', 'cross-region', 'in-region', 'mobile', or 'auto'."); ConfigurationProvider::unwrap('some_string'); } } diff --git a/tests/DefaultsMode/ConfigurationTest.php b/tests/DefaultsMode/ConfigurationTest.php index d71547d4db..e3eb1d2fde 100644 --- a/tests/DefaultsMode/ConfigurationTest.php +++ b/tests/DefaultsMode/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\DefaultsMode; use Aws\DefaultsMode\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('standard'); @@ -42,12 +45,10 @@ public function testToArrayWithLegacy() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage 'foo' is not a valid mode - */ public function testHandlesInvalidMode() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage("'foo' is not a valid mode"); new Configuration('foo'); } } diff --git a/tests/DynamoDb/DynamoDbClientTest.php b/tests/DynamoDb/DynamoDbClientTest.php index 1a24aa489c..841f6d910e 100644 --- a/tests/DynamoDb/DynamoDbClientTest.php +++ b/tests/DynamoDb/DynamoDbClientTest.php @@ -26,9 +26,9 @@ public function testRegisterSessionHandlerReturnsHandler() { $client = $this->getTestSdk()->createDynamoDb(); @$sh = $client->registerSessionHandler(['locking' => true]); - $this->assertAttributeInstanceOf( + $this->assertInstanceOf( 'Aws\DynamoDb\LockingSessionConnection', - 'connection', $sh + $this->readAttribute($sh, 'connection') ); } diff --git a/tests/Endpoint/PartitionTest.php b/tests/Endpoint/PartitionTest.php index 09bb87cd52..6b85d6a73f 100644 --- a/tests/Endpoint/PartitionTest.php +++ b/tests/Endpoint/PartitionTest.php @@ -691,7 +691,7 @@ public function testGetVariantIgnoresVariantTagOrder( ] ]); - self::assertContains('testsuffix.com', $resolved['endpoint']); + $this->assertStringContainsString('testsuffix.com', $resolved['endpoint']); } public function variantTagProvider() @@ -841,7 +841,7 @@ public function testGetVariantNoVariantSelectedIfTagsAreEmpty( ] ]); - self::assertNotContains('testsuffix.com', $resolved['endpoint']); + $this->assertStringNotContainsString('testsuffix.com', $resolved['endpoint']); } public function variantTagEmptyProvider() diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php index 6f6fdd09eb..16de56b55e 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\Endpoint\UseDualstackEndpoint\Configuration; use Aws\Endpoint\UseDualstackEndpoint\ConfigurationInterface; use Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT) ?: '', @@ -54,7 +57,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT . '=' . self::$originalEnv['use_dualstack_endpoint']); @@ -169,21 +172,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini('us-east-1'))->wait(); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -197,12 +196,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'foo' not found in"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -215,12 +212,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Invalid config file:"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -290,11 +285,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php index fcedcdd5e4..e6931bba76 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Endpoint\UseDualstackEndpoint; use Aws\Endpoint\UseDualstackEndpoint\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider correctValueCases * @@ -44,20 +47,17 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'use_dual_stack_endpoint' config option must be a boolean value - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'use_dual_stack_endpoint' config option must be a boolean value"); new Configuration('not a boolean', 'us-east-1'); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Dual-stack is not supported in ISO regions - */ + public function testThrowsOnInvalidRegion() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Dual-stack is not supported in ISO regions"); new Configuration(true, 'something-iso-something'); } } diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php index 311c178a17..7ea27d0d18 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\Endpoint\UseFipsEndpoint\Configuration; use Aws\Endpoint\UseFipsEndpoint\ConfigurationInterface; use Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT) ?: '', @@ -53,7 +56,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT . '=' . self::$originalEnv['use_fips_endpoint']); @@ -177,21 +180,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -205,12 +204,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'foo' not found in"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -223,12 +220,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Invalid config file:"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -297,11 +292,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php index 1f915fcdcd..f603f737a4 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Endpoint\UseFipsEndpoint; use Aws\Endpoint\UseFipsEndpoint\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider correctValueCases * @@ -44,12 +47,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'use_fips_endpoint' config option must be a boolean value. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'use_fips_endpoint' config option must be a boolean value."); new Configuration('not a boolean'); } } diff --git a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php index 3967751539..054b75b37d 100644 --- a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php +++ b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php @@ -4,6 +4,7 @@ use Aws\CommandInterface; use Aws\Result; use Aws\EventBridge\EventBridgeClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -11,7 +12,7 @@ class EventBridgeEndpointMiddlewareTest extends TestCase { use UsesServiceTrait; - + use PHPUnitCompatTrait; public function putEventsEndpointSuccessProvider() { @@ -203,7 +204,7 @@ public function testPutEventsEndpointFailureCases( self::fail("this test should have thrown an exception"); } catch (\Exception $exception) { self::assertSame("InvalidArgumentException", get_class($exception)); - self::assertContains($expectedException, $exception->getMessage()); + self::assertStringContainsString($expectedException, $exception->getMessage()); } } diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index 0eacfbc54e..f311d9b3e0 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -1010,12 +1010,13 @@ public function contentProvider() } /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Unable to determine stream size. Did you forget to close or flush the stream? * @dataProvider contentProvider */ public function testTriggersErrorOnNoFlushOrClose($content) { + $this->expectException(\PHPUnit\Framework\Error\Warning::class); + $this->expectExceptionMessage("Unable to determine stream size. Did you forget to close or flush the stream?"); + $stream = $this->getMockBuilder(Psr7\Stream::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/S3/StreamWrapperV2ExistenceTest.php b/tests/S3/StreamWrapperV2ExistenceTest.php index 176fdfc32d..59c885b058 100644 --- a/tests/S3/StreamWrapperV2ExistenceTest.php +++ b/tests/S3/StreamWrapperV2ExistenceTest.php @@ -9,6 +9,7 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Response; @@ -20,6 +21,7 @@ */ class StreamWrapperV2ExistenceTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -28,7 +30,7 @@ class StreamWrapperV2ExistenceTest extends TestCase /** @var LruArrayCache */ private $cache; - public function setUp() + public function _setUp() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -37,12 +39,15 @@ public function setUp() $this->client->registerStreamWrapperV2(); } - public function tearDown() + public function _tearDown() { stream_wrapper_unregister('s3'); $this->client = null; } + /** + * @doesNotPerformAssertions + */ public function testSuccessfulXMode() { $this->addMockResults( @@ -234,12 +239,10 @@ public function testCanWriteEmptyFileToStream() $this->assertSame('', (string) $cmd['Body']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { + $this->expectError(); + $this->expectErrorMessage('403 Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } ]); @@ -305,12 +308,10 @@ public function testCanUnlinkFiles() $this->assertSame('bucket.s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testThrowsErrorsWhenUnlinkFails() { + $this->expectError(); + $this->expectErrorMessage('403 Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -322,22 +323,18 @@ public function testCreatingBucketWithNoBucketReturnsFalse() $this->assertFalse(mkdir('s3://')); } - /** - * @expectedExceptionMessage Bucket already exists: s3://already-existing-bucket - * @expectedException \PHPUnit\Framework\Error\Warning - */ 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'); } - /** - * @expectedExceptionMessage Subfolder already exists: s3://already-existing-bucket/key - * @expectedException \PHPUnit\Framework\Error\Warning - */ 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'); } @@ -407,24 +404,20 @@ function ($cmd, $r) { return new S3Exception( $entries = $history->toArray(); $this->assertSame('HEAD', $entries[0]['request']->getMethod()); $this->assertSame('PUT', $entries[1]['request']->getMethod()); - $this->assertContains('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); + $this->assertStringContainsString('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage specify a bucket - */ public function testCannotDeleteS3() { + $this->expectError(); + $this->expectErrorMessage('specify a bucket'); rmdir('s3://'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testRmDirWithExceptionTriggersError() { + $this->expectError(); + $this->expectErrorMessage('403 Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -464,7 +457,7 @@ public function testCanDeleteObjectWithRmDir($path) $this->assertCount(1, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); } public function testCanDeleteNestedFolderWithRmDir() @@ -484,37 +477,31 @@ public function testCanDeleteNestedFolderWithRmDir() $this->assertCount(2, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); $this->assertSame('DELETE', $entries[1]['request']->getMethod()); $this->assertSame('/bar/', $entries[1]['request']->getUri()->getPath()); - $this->assertContains('foo', $entries[1]['request']->getUri()->getHost()); + $this->assertStringContainsString('foo', $entries[1]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage rename(): Cannot rename a file across wrapper types - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage The Amazon S3 stream wrapper only supports copying objects - */ public function testRenameEnsuresKeyIsSet() { + $this->expectError(); + $this->expectErrorMessage('The Amazon S3 stream wrapper only supports copying objects'); rename('s3://foo/bar', 's3://baz'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ public function testRenameWithExceptionThrowsError() { + $this->expectError(); + $this->expectErrorMessage('Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -612,12 +599,10 @@ public function testCanPullStatDataFromCache() $this->assertSame(123, filesize('s3://foo/bar')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ 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); }, @@ -627,12 +612,10 @@ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } stat('s3://bucket/key'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket - */ public function testBucketNotFoundTriggersError() { + $this->expectError(); + $this->expectErrorMessage('File or directory not found: s3://bucket'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception( @@ -684,12 +667,10 @@ function ($cmd, $r) { return new S3Exception( $this->assertSame(0040777, $stat['mode']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket/prefix - */ 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', @@ -769,12 +750,16 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) $this->assertCount(count($queue), $history); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage cannot represent a stream of type user-space - */ 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->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) ]); @@ -805,7 +790,7 @@ function ($cmd, $r) { return new S3Exception( ['response' => new Response(404)] );}, ]); - $this->assertFileNotExists('s3://bucket/key'); + $this->assertFileDoesNotExist('s3://bucket/key'); } public function testProvidesDirectoriesForS3() @@ -872,7 +857,7 @@ public function testProvidesDirectoriesForS3() $dir = 's3://bucket/key/'; $r = opendir($dir); - $this->assertInternalType('resource', $r); + $this->assertIsResource($r); $files = []; while (($file = readdir($r)) !== false) { diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index 024b94949a..ae60071270 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -12,7 +12,7 @@ use PHPUnit\Framework\TestCase; /** - * @covers \Aws\Sts\RegionalEndpoints\ConfigurationProvider + * git\Sts\RegionalEndpoints\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { From 69e7187a1b7776cf2bd5de72f91af453c50f73bb Mon Sep 17 00:00:00 2001 From: Zombaya Date: Fri, 18 Mar 2022 02:10:57 +0100 Subject: [PATCH 04/31] Fix problems with non-fully-reset environment-variables after test --- tests/ClientSideMonitoring/ConfigurationProviderTest.php | 3 +++ tests/DefaultsMode/ConfigurationProviderTest.php | 4 ++++ .../UseDualstackEndpoint/ConfigurationProviderTest.php | 6 +++++- .../UseFipsEndpoint/ConfigurationProviderTest.php | 8 ++++++-- tests/EndpointDiscovery/ConfigurationProviderTest.php | 4 ++++ tests/Retry/ConfigurationProviderTest.php | 4 ++++ tests/S3/RegionalEndpoint/ConfigurationProviderTest.php | 4 ++++ tests/S3/UseArnRegion/ConfigurationProviderTest.php | 4 ++++ tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php | 4 ++++ 9 files changed, 38 insertions(+), 3 deletions(-) diff --git a/tests/ClientSideMonitoring/ConfigurationProviderTest.php b/tests/ClientSideMonitoring/ConfigurationProviderTest.php index 73f37683bb..04b6a1a2a7 100644 --- a/tests/ClientSideMonitoring/ConfigurationProviderTest.php +++ b/tests/ClientSideMonitoring/ConfigurationProviderTest.php @@ -57,6 +57,7 @@ public static function _setUpBeforeClass() 'port' => getenv(ConfigurationProvider::ENV_PORT) ?: '', 'client_id' => getenv(ConfigurationProvider::ENV_CLIENT_ID) ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -90,6 +91,8 @@ public static function _tearDownAfterClass() self::$originalEnv['client_id']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); } public function testCreatesFromEnvironmentVariables() diff --git a/tests/DefaultsMode/ConfigurationProviderTest.php b/tests/DefaultsMode/ConfigurationProviderTest.php index eca5da78d4..e49c557e71 100644 --- a/tests/DefaultsMode/ConfigurationProviderTest.php +++ b/tests/DefaultsMode/ConfigurationProviderTest.php @@ -39,6 +39,7 @@ public static function _setUpBeforeClass() 'mode' => getenv(ConfigurationProvider::ENV_MODE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -46,6 +47,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_MODE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -62,6 +64,8 @@ public static function _tearDownAfterClass() self::$originalEnv['mode']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php index 16de56b55e..c94f206d06 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php @@ -1,5 +1,5 @@ getenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -47,6 +48,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -63,6 +65,8 @@ public static function _tearDownAfterClass() self::$originalEnv['use_dualstack_endpoint']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php index 7ea27d0d18..d290fc8f69 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php @@ -1,5 +1,5 @@ getenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } private function clearEnv() { putenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -60,9 +62,11 @@ public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT . '=' . self::$originalEnv['use_fips_endpoint']); + putenv('HOME=' . self::$originalEnv['home']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); - putenv('HOME=' . self::$originalEnv['home']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); } public function testCreatesFromEnvironmentVariables() diff --git a/tests/EndpointDiscovery/ConfigurationProviderTest.php b/tests/EndpointDiscovery/ConfigurationProviderTest.php index ef98cdbc45..f63d7d07da 100644 --- a/tests/EndpointDiscovery/ConfigurationProviderTest.php +++ b/tests/EndpointDiscovery/ConfigurationProviderTest.php @@ -44,6 +44,7 @@ public static function _setUpBeforeClass() 'enabled_alt' => getenv(ConfigurationProvider::ENV_ENABLED_ALT) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -52,6 +53,7 @@ private function clearEnv() putenv(ConfigurationProvider::ENV_ENABLED . '='); putenv(ConfigurationProvider::ENV_ENABLED_ALT . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -70,6 +72,8 @@ public static function _tearDownAfterClass() self::$originalEnv['enabled_alt']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Retry/ConfigurationProviderTest.php b/tests/Retry/ConfigurationProviderTest.php index 5e4a134b30..f9e9e531f1 100644 --- a/tests/Retry/ConfigurationProviderTest.php +++ b/tests/Retry/ConfigurationProviderTest.php @@ -44,6 +44,7 @@ public static function _setUpBeforeClass() 'mode' => getenv(ConfigurationProvider::ENV_MODE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -52,6 +53,7 @@ private function clearEnv() putenv(ConfigurationProvider::ENV_MODE . '='); putenv(ConfigurationProvider::ENV_MAX_ATTEMPTS . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -70,6 +72,8 @@ public static function _tearDownAfterClass() self::$originalEnv['mode']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php index f6d6845496..d04396a643 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php @@ -42,6 +42,7 @@ public static function _setUpBeforeClass() 'endpoints_type' => getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -49,6 +50,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -65,6 +67,8 @@ public static function _tearDownAfterClass() self::$originalEnv['endpoints_type']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/S3/UseArnRegion/ConfigurationProviderTest.php b/tests/S3/UseArnRegion/ConfigurationProviderTest.php index b61a9c27d1..6f1b378426 100644 --- a/tests/S3/UseArnRegion/ConfigurationProviderTest.php +++ b/tests/S3/UseArnRegion/ConfigurationProviderTest.php @@ -39,6 +39,7 @@ public static function _setUpBeforeClass() 'use_arn_region' => getenv(ConfigurationProvider::ENV_USE_ARN_REGION) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -46,6 +47,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_USE_ARN_REGION . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -62,6 +64,8 @@ public static function _tearDownAfterClass() self::$originalEnv['use_arn_region']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index ae60071270..2b720b1582 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -40,6 +40,7 @@ public static function _setUpBeforeClass() 'endpoints_type' => getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -47,6 +48,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -63,6 +65,8 @@ public static function _tearDownAfterClass() self::$originalEnv['endpoints_type']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } From 22c3c772dfe5a5e4f0c2984394ab0d2d71f3e4fd Mon Sep 17 00:00:00 2001 From: Zombaya Date: Fri, 18 Mar 2022 11:55:20 +0100 Subject: [PATCH 05/31] Add changelog document --- .changes/nextrelease/php8 | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .changes/nextrelease/php8 diff --git a/.changes/nextrelease/php8 b/.changes/nextrelease/php8 new file mode 100644 index 0000000000..3aac71a472 --- /dev/null +++ b/.changes/nextrelease/php8 @@ -0,0 +1,7 @@ +[ + { + "type": "enhancement", + "category": "", + "description": "Add support for php 8.0 and 8.1" + } +] \ No newline at end of file From 3fa4d92037d4c8e192bba2a6a058a96bfb8fb9a3 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Wed, 11 May 2022 16:48:53 +0200 Subject: [PATCH 06/31] Small rewrites of unittests because of deprecation-warnings in phpunit 9.x --- tests/ClientResolverTest.php | 52 ++++++++++++++++++---------------- tests/S3/StreamWrapperTest.php | 4 +-- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index 8da3967fb1..962401ba17 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -825,33 +825,37 @@ public function testUserAgentAlwaysStartsWithSdkAgentString() ->disableOriginalConstructor() ->getMock(); - $request->expects($this->at(0)) + $request->expects($this->exactly(2)) ->method('getHeader') - ->with('X-Amz-User-Agent') - ->willReturn(["MockBuilder"]); - - $request->expects($this->at(1)) - ->method('withHeader') - ->with( - 'X-Amz-User-Agent', - new \PHPUnit\Framework\Constraint\RegularExpression( - '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' - ) - )->willReturn($request); - - $request->expects($this->at(2)) - ->method('getHeader') - ->with('User-Agent') - ->willReturn(['MockBuilder']); + ->withConsecutive( + ['X-Amz-User-Agent'], + ['User-Agent'] + ) + ->willReturnOnConsecutiveCalls( + ["MockBuilder"], + ['MockBuilder'] + ); - $request->expects($this->at(3)) + $request->expects($this->exactly(2)) ->method('withHeader') - ->with( - 'User-Agent', - new \PHPUnit\Framework\Constraint\RegularExpression( - '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' - ) - )->willReturn($request); + ->withConsecutive( + [ + 'X-Amz-User-Agent', + new \PHPUnit\Framework\Constraint\RegularExpression( + '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' + ) + ], + [ + 'User-Agent', + new \PHPUnit\Framework\Constraint\RegularExpression( + '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' + ) + ] + ) + ->willReturnOnConsecutiveCalls( + $request, + $request + ); $args = []; $list = new HandlerList(function () {}); diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index f311d9b3e0..5285da6681 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -1014,8 +1014,8 @@ public function contentProvider() */ public function testTriggersErrorOnNoFlushOrClose($content) { - $this->expectException(\PHPUnit\Framework\Error\Warning::class); - $this->expectExceptionMessage("Unable to determine stream size. Did you forget to close or flush the stream?"); + $this->expectWarning(); + $this->expectWarning("Unable to determine stream size. Did you forget to close or flush the stream?"); $stream = $this->getMockBuilder(Psr7\Stream::class) ->disableOriginalConstructor() From 82715b90ac4c521edf811c576fd766f58cf2e006 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Wed, 11 May 2022 17:10:37 +0200 Subject: [PATCH 07/31] Remove warnings from usage of arguments of wrong type in php 8.1 --- src/Api/Parser/AbstractRestParser.php | 2 +- src/Api/Serializer/JsonBody.php | 2 +- src/Arn/ArnParser.php | 2 +- src/S3/S3Client.php | 2 +- tests/Integ/S3Context.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Api/Parser/AbstractRestParser.php b/src/Api/Parser/AbstractRestParser.php index de346b6513..c977588bd9 100644 --- a/src/Api/Parser/AbstractRestParser.php +++ b/src/Api/Parser/AbstractRestParser.php @@ -160,7 +160,7 @@ private function extractHeaders( // Check if the headers are prefixed by a location name $result[$name] = []; $prefix = $shape['locationName']; - $prefixLen = strlen($prefix); + $prefixLen = $prefix !== null ? strlen($prefix) : 0; foreach ($response->getHeaders() as $k => $values) { if (!$prefixLen) { diff --git a/src/Api/Serializer/JsonBody.php b/src/Api/Serializer/JsonBody.php index 4a4fe7f9bb..40e6387d6d 100644 --- a/src/Api/Serializer/JsonBody.php +++ b/src/Api/Serializer/JsonBody.php @@ -29,7 +29,7 @@ public function __construct(Service $api) public static function getContentType(Service $service) { return 'application/x-amz-json-' - . number_format($service->getMetadata('jsonVersion'), 1); + . number_format(($version = $service->getMetadata('jsonVersion')) !== null ? $version : 0.0, 1); } /** diff --git a/src/Arn/ArnParser.php b/src/Arn/ArnParser.php index ae57b26be4..331c507d5c 100644 --- a/src/Arn/ArnParser.php +++ b/src/Arn/ArnParser.php @@ -23,7 +23,7 @@ class ArnParser */ public static function isArn($string) { - return strpos($string, 'arn:') === 0; + return $string !== null && strpos($string, 'arn:') === 0; } /** diff --git a/src/S3/S3Client.php b/src/S3/S3Client.php index 68d4fd5d26..cdceaefd99 100644 --- a/src/S3/S3Client.php +++ b/src/S3/S3Client.php @@ -429,7 +429,7 @@ public function __construct(array $args) */ public static function isBucketDnsCompatible($bucket) { - $bucketLen = strlen($bucket); + $bucketLen = $bucket !== null ? strlen($bucket) : 0; return ($bucketLen >= 3 && $bucketLen <= 63) && // Cannot look like an IP address diff --git a/tests/Integ/S3Context.php b/tests/Integ/S3Context.php index 04194f9a74..b08e5571f2 100644 --- a/tests/Integ/S3Context.php +++ b/tests/Integ/S3Context.php @@ -411,7 +411,7 @@ private static function executeWithRetries( throw $e; } $attempts++; - sleep(pow(1.2, $attempts)); + sleep((int) pow(1.2, $attempts)); } } } From bebfcc7fc3ba13abe5c8ea2e0c7c212623de7c51 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Tue, 7 Jun 2022 23:00:00 +0200 Subject: [PATCH 08/31] Solve failing unittest CloudFront\SignerTest::testBadPrivateKeyPath() There were remaining error-messages in the openssl-error-stack, resulting in an unexpected result in the unittest. This was solved by outputting all error-messages in Aws\CloudFront\Signer::__construct(). Another option would be to clear all error-messages in Aws\Test\CloudFront\SignerTest::_tearDown(), so tests would no longer interfer with eachother. The first solution was chosen since it would output all openssl-error-messages to the user, not only the first one, making it more complete. --- src/CloudFront/Signer.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/CloudFront/Signer.php b/src/CloudFront/Signer.php index 156570d595..22e55c2a44 100644 --- a/src/CloudFront/Signer.php +++ b/src/CloudFront/Signer.php @@ -34,11 +34,15 @@ public function __construct($keyPairId, $privateKey, $passphrase = "") if (!$this->pkHandle = openssl_pkey_get_private($privateKey, $passphrase)) { if (!file_exists($privateKey)) { throw new \InvalidArgumentException("PK file not found: $privateKey"); - } else { - $this->pkHandle = openssl_pkey_get_private("file://$privateKey", $passphrase); - if (!$this->pkHandle) { - throw new \InvalidArgumentException(openssl_error_string()); + } + + $this->pkHandle = openssl_pkey_get_private("file://$privateKey", $passphrase); + if (!$this->pkHandle) { + $errorMessages = []; + while(($newMessage = openssl_error_string()) !== false){ + $errorMessages[] = $newMessage; } + throw new \InvalidArgumentException(implode("\n",$errorMessages)); } } } From eccd8964e190a2e8f05cf3d89a3a95c1f7e6d55e Mon Sep 17 00:00:00 2001 From: Sean O'Brien <60306702+stobrien89@users.noreply.github.com> Date: Thu, 9 Jun 2022 12:27:42 -0500 Subject: [PATCH 09/31] switch to double pipe --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 7f8d03675d..eb0356f7bd 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "ext-dom": "*", "ext-pcntl": "*", "ext-sockets": "*", - "phpunit/phpunit": "^4.8.35 || ^5.6.3|^9.5", + "phpunit/phpunit": "^4.8.35 || ^5.6.3 || ^9.5", "behat/behat": "~3.0", "doctrine/cache": "~1.4", "aws/aws-php-sns-message-validator": "~1.0", @@ -40,7 +40,7 @@ "psr/cache": "^1.0", "psr/simple-cache": "^1.0", "paragonie/random_compat": ">= 2", - "sebastian/comparator": "^1.2.3|^4.0" + "sebastian/comparator": "^1.2.3 || ^4.0" }, "suggest": { "ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages", From 863a65a91462da7612d23e14009785d85c84ed27 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Mon, 13 Jun 2022 23:45:26 +0200 Subject: [PATCH 10/31] Formatting fixes --- src/Api/Serializer/JsonBody.php | 7 ++++++- src/S3/S3Client.php | 4 ++++ tests/CloudFront/UrlSignerTest.php | 2 +- tests/EndpointParameterMiddlewareTest.php | 2 +- tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php | 6 +++--- tests/S3/S3ClientTest.php | 9 ++++++++- tests/bootstrap.php | 18 +++++++++--------- 7 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/Api/Serializer/JsonBody.php b/src/Api/Serializer/JsonBody.php index 40e6387d6d..9470c9bbf2 100644 --- a/src/Api/Serializer/JsonBody.php +++ b/src/Api/Serializer/JsonBody.php @@ -29,7 +29,12 @@ public function __construct(Service $api) public static function getContentType(Service $service) { return 'application/x-amz-json-' - . number_format(($version = $service->getMetadata('jsonVersion')) !== null ? $version : 0.0, 1); + . number_format( + ($version = $service->getMetadata('jsonVersion')) !== null + ? $version + : 0.0, + 1 + ); } /** diff --git a/src/S3/S3Client.php b/src/S3/S3Client.php index cdceaefd99..3fb8630f9a 100644 --- a/src/S3/S3Client.php +++ b/src/S3/S3Client.php @@ -429,6 +429,10 @@ public function __construct(array $args) */ public static function isBucketDnsCompatible($bucket) { + if (!is_string($bucket)) { + return false; + } + $bucketLen = $bucket !== null ? strlen($bucket) : 0; return ($bucketLen >= 3 && $bucketLen <= 63) && diff --git a/tests/CloudFront/UrlSignerTest.php b/tests/CloudFront/UrlSignerTest.php index 1c9caaeab2..3818887290 100644 --- a/tests/CloudFront/UrlSignerTest.php +++ b/tests/CloudFront/UrlSignerTest.php @@ -46,7 +46,7 @@ public function testCreatesUrlSignersForHttp() $url ); $urlObject = new Uri($url); - $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); + $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); $signature = $query['Signature']; $this->assertStringNotContainsString('?', $signature); $this->assertStringNotContainsString('=', $signature); diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 0e8a1c1c7a..62ad7674ba 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -90,7 +90,7 @@ public function testCorrectlyOutputsHost( }); $handler = $list->resolve(); - $handler($command, new Request('POST', $endpoint))->wait(false); + $handler($command, new Request('POST', $endpoint)); } public function getTestCases() diff --git a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php index f10106183e..8ecdd7f639 100644 --- a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php +++ b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php @@ -73,7 +73,7 @@ public function readAttribute($object, $attributeName) } if (isset($attribute)) { - if ( ! $attribute || $attribute->isPublic()) { + if (!$attribute || $attribute->isPublic()) { return $object->$attributeName; } $attribute->setAccessible(true); @@ -109,14 +109,14 @@ public static function invalidArgumentHelper($argument, $type, $value = null) public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = '') { - if ( ! (\is_array($subset) || $subset instanceof ArrayAccess)) { + if (!(\is_array($subset) || $subset instanceof ArrayAccess)) { throw self::invalidArgumentHelper( 1, 'array or ArrayAccess' ); } - if ( ! (\is_array($array) || $array instanceof ArrayAccess)) { + if (!(\is_array($array) || $array instanceof ArrayAccess)) { throw self::invalidArgumentHelper( 2, 'array or ArrayAccess' diff --git a/tests/S3/S3ClientTest.php b/tests/S3/S3ClientTest.php index dd1ab1332a..32e6ac3c4a 100644 --- a/tests/S3/S3ClientTest.php +++ b/tests/S3/S3ClientTest.php @@ -69,7 +69,14 @@ public function bucketNameProvider() ['my.bucket.com', true], ['test-fooCaps', false], ['w-w', true], - ['w------', false] + ['w------', false], + ['', false], + [null,false], + [false,false], + [true,false], + [1,false], + [[],false], + [new \stdClass(),false] ]; } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index c4cde91a15..b331f5e341 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,21 +3,21 @@ date_default_timezone_set('UTC'); // Include the composer autoloader -$loader = require __DIR__.'/../vendor/autoload.php'; +$loader = require __DIR__ . '/../vendor/autoload.php'; -if ( ! defined('PHPUNIT_COMPOSER_INSTALL')) { - define('PHPUNIT_COMPOSER_INSTALL', __DIR__.'/../vendor/autoload.php'); +if (!defined('PHPUNIT_COMPOSER_INSTALL')) { + define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/../vendor/autoload.php'); } -if ( ! class_exists('\PHPUnit\Framework\Constraint\RegularExpression')) { +if (!class_exists('\PHPUnit\Framework\Constraint\RegularExpression')) { class_alias('\PHPUnit_Framework_Constraint_PCREMatch', '\PHPUnit\Framework\Constraint\RegularExpression'); } -if ( ! class_exists('\PHPUnit\Framework\Constraint\Callback')) { +if (!class_exists('\PHPUnit\Framework\Constraint\Callback')) { class_alias('\PHPUnit_Framework_Constraint_Callback', '\PHPUnit\Framework\Constraint\Callback'); } -if ( ! class_exists('\PHPUnit\Framework\Error\Warning')) { +if (!class_exists('\PHPUnit\Framework\Error\Warning')) { class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warning'); } @@ -26,13 +26,13 @@ class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warnin // Patch PHPUnit class for PHP 7.4+ and PHPUnit 5.x to avoid deprecation warning // Necessary because older versions of PHPUnit are no longer supported -$version = class_exists('PHPUnit_Runner_Version') ? PHPUnit_Runner_Version::id() : PHPUnit\Runner\Version::id(); +$version = class_exists('PHPUnit_Runner_Version') ? PHPUnit_Runner_Version::id() : PHPUnit\Runner\Version::id(); $versionData = explode('.', $version); include_once(sprintf("%s/Polyfill/PHPUnit%s/PHPUnitCompatTrait.php", __DIR__, $versionData[0])); if (PHP_VERSION_ID >= 70400 && $versionData[0] == 5) { - $vendorGeneratorPath = __DIR__.'/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; - $patchGeneratorPath = __DIR__.'/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; + $vendorGeneratorPath = __DIR__ . '/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; + $patchGeneratorPath = __DIR__ . '/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; file_put_contents($vendorGeneratorPath, file_get_contents($patchGeneratorPath)); } From bce4721e9d044a934ec23e27b4d033f9a44547b4 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Mon, 27 Jun 2022 17:53:11 +0200 Subject: [PATCH 11/31] Additional methods added to PHPUnitCompatibilitityTraits --- tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php | 10 ++++++++++ tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php | 12 ++++++++++++ 2 files changed, 22 insertions(+) diff --git a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php index 9af1c4707f..19dd3eab1d 100644 --- a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php +++ b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php @@ -63,6 +63,16 @@ public function expectWarning() $this->expectException(\PHPUnit_Framework_Error_Warning::class); } + public function expectError() + { + $this->expectException(\PHPUnit_Framework_Error::class); + } + + public function expectErrorMessage($message) + { + $this->expectExceptionMessage($message); + } + public function expectExceptionMessageMatches($regularExpression) { $this->expectExceptionMessageRegExp($regularExpression); diff --git a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php index 35eb03eccc..d7218e462a 100644 --- a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php +++ b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php @@ -2,6 +2,8 @@ namespace Aws\Test\Polyfill\PHPUnit; +use PHPUnit\Framework\Error\Error; + trait PHPUnitCompatTrait { private $exceptionCode = null; @@ -51,6 +53,16 @@ public function expectWarning() $this->expectException(\PHPUnit_Framework_Error_Warning::class); } + public function expectError() + { + $this->expectException(\PHPUnit_Framework_Error::class); + } + + public function expectErrorMessage($message) + { + $this->expectExceptionMessage($message); + } + public function expectExceptionMessageMatches($regularExpression) { $this->expectExceptionMessageRegExp($regularExpression); From 8f4b64ec4a16236c125e237cf7170e827d30e046 Mon Sep 17 00:00:00 2001 From: Chris Lloyd Date: Mon, 11 Oct 2021 19:12:08 +0100 Subject: [PATCH 12/31] PHP 8.0, 8.1, PHPUnit 9 support --- .github/workflows/tests.yml | 26 +-- .gitignore | 1 + composer.json | 4 +- phpunit.xml.dist | 53 +++--- src/MockHandler.php | 2 +- tests/AbstractConfigurationProviderTest.php | 7 +- tests/Api/ApiProviderTest.php | 17 +- tests/Api/ErrorParser/XmlErrorParserTest.php | 2 + tests/Api/ListShapeTest.php | 7 +- tests/Api/MapShapeTest.php | 7 +- tests/Api/OperationTest.php | 7 +- tests/Api/Parser/ComplianceTest.php | 1 + .../Api/Parser/Crc32ValidatingParserTest.php | 5 +- .../DecodingEventStreamIteratorTest.php | 8 +- tests/Api/Parser/EventParsingIteratorTest.php | 17 +- tests/Api/Parser/JsonParserTest.php | 4 +- tests/Api/Parser/JsonRpcParserTest.php | 1 + tests/Api/Parser/XmlParserTest.php | 4 +- tests/Api/Serializer/ComplianceTest.php | 1 + .../Api/Serializer/RestJsonSerializerTest.php | 6 +- .../Api/Serializer/RestXmlSerializerTest.php | 4 +- tests/Api/ServiceTest.php | 14 +- tests/Api/ShapeMapTest.php | 7 +- tests/Api/ShapeTest.php | 13 +- tests/Api/StructureShapeTest.php | 9 +- tests/Api/TimestampShapeTest.php | 11 +- tests/Api/ValidatorTest.php | 13 +- tests/AwsClientTest.php | 52 ++--- .../Build/Changelog/ChangelogBuilderTest.php | 14 +- tests/Build/Changelog/CurrentChangesTest.php | 2 + tests/ClientResolverTest.php | 72 ++++--- .../ConfigurationProviderTest.php | 34 ++-- .../ConfigurationTest.php | 6 +- .../MonitoringMiddlewareTestingTrait.php | 5 +- tests/CloudFront/CloudFrontClientTest.php | 41 ++-- tests/CloudFront/CookieSignerTest.php | 42 ++--- tests/CloudFront/SignerTest.php | 33 ++-- tests/CloudFront/UrlSignerTest.php | 98 +++++----- tests/CloudFront/fixtures/test2.pem | 27 +++ .../CloudSearchDomainTest.php | 7 +- tests/CloudTrail/LogFileIteratorTest.php | 10 +- .../CognitoIdentityProviderTest.php | 3 + tests/CognitoSync/CognitoSyncClientTest.php | 4 +- tests/CommandPoolTest.php | 14 +- .../AssumeRoleCredentialProviderTest.php | 14 +- ...eWithWebIdentityCredentialProviderTest.php | 58 +++--- tests/Credentials/CredentialProviderTest.php | 178 +++++++----------- .../Credentials/EcsCredentialProviderTest.php | 20 +- .../InstanceProfileProviderTest.php | 23 +-- tests/Crypto/AesDecryptingStreamTest.php | 6 +- tests/Crypto/AesEncryptingStreamTest.php | 5 +- tests/Crypto/AesGcmDecryptingStreamTest.php | 6 +- tests/Crypto/AesGcmEncryptingStreamTest.php | 4 +- tests/Crypto/Cipher/CbcTest.php | 19 +- tests/Crypto/KmsMaterialsProviderV2Test.php | 26 +-- tests/Crypto/MetadataEnvelopeTest.php | 5 +- tests/Crypto/Polyfill/KeyTest.php | 7 +- tests/DocDb/DocDbClientTest.php | 9 +- tests/DynamoDb/DynamoDbClientTest.php | 2 + tests/DynamoDb/MarshalerTest.php | 11 +- tests/DynamoDb/SessionHandlerTest.php | 2 + .../StandardSessionConnectionTest.php | 10 +- tests/DynamoDb/WriteRequestBatchTest.php | 8 +- tests/Endpoint/EndpointProviderTest.php | 11 +- tests/Endpoint/PartitionTest.php | 10 +- .../ConfigurationProviderTest.php | 37 ++-- tests/EndpointDiscovery/ConfigurationTest.php | 7 +- .../EndpointDiscoveryMiddlewareTest.php | 8 +- tests/EndpointParameterMiddlewareTest.php | 2 +- tests/FunctionsTest.php | 8 +- tests/Glacier/GlacierClientTest.php | 6 +- tests/Glacier/MultipartUploaderTest.php | 4 +- tests/Glacier/TreeHashTest.php | 7 +- tests/Handler/GuzzleV5/HandlerTest.php | 5 +- tests/Handler/GuzzleV5/StreamTest.php | 5 +- tests/Handler/GuzzleV6/HandlerTest.php | 7 +- tests/HandlerListTest.php | 26 +-- tests/HistoryTest.php | 26 +-- tests/IdempotencyTokenMiddlewareTest.php | 5 +- tests/Integ/GuzzleV5HandlerTest.php | 5 +- tests/Integ/GuzzleV6StreamHandlerTest.php | 4 +- tests/JsonCompilerTest.php | 11 +- tests/Lambda/LambdaClientTest.php | 3 + tests/MiddlewareTest.php | 11 +- tests/MockHandlerTest.php | 21 +-- tests/MultiRegionClientTest.php | 9 +- tests/Multipart/AbstractUploaderTest.php | 22 +-- tests/Neptune/NeptuneClientTest.php | 9 +- tests/Polly/PollyClientTest.php | 31 +-- .../Polyfill/PHPUnit4/PHPUnitCompatTrait.php | 131 +++++++++++++ .../Polyfill/PHPUnit5/PHPUnitCompatTrait.php | 119 ++++++++++++ tests/Polyfill/PHPUnit9/ArraySubset.php | 133 +++++++++++++ .../Polyfill/PHPUnit9/PHPUnitCompatTrait.php | 130 +++++++++++++ tests/PresignUrlMiddlewareTest.php | 22 ++- tests/Psr16CacheAdapterTest.php | 5 +- tests/PsrCacheAdapterTest.php | 5 +- tests/Rds/AuthTokenGeneratorTest.php | 51 ++--- tests/Rds/RdsClientTest.php | 11 +- tests/ResultPaginatorTest.php | 2 + tests/ResultTest.php | 5 +- tests/Retry/ConfigurationProviderTest.php | 37 ++-- tests/Retry/ConfigurationTest.php | 15 +- tests/RetryMiddlewareTest.php | 5 +- tests/RetryMiddlewareV2Test.php | 6 +- tests/Route53/RouteClient53Test.php | 13 +- tests/S3/AmbiguousSuccessParserTest.php | 17 +- tests/S3/BatchDeleteTest.php | 12 +- tests/S3/BucketEndpointArnMiddlewareTest.php | 4 +- tests/S3/Crypto/S3EncryptionClientTest.php | 31 ++- tests/S3/Crypto/S3EncryptionClientV2Test.php | 62 +++--- .../S3EncryptionMultipartUploaderTest.php | 5 +- .../S3EncryptionMultipartUploaderV2Test.php | 5 +- .../DeleteMultipleObjectsExceptionTest.php | 5 +- tests/S3/MultipartUploaderTest.php | 13 +- tests/S3/PermanentRedirectMiddlewareTest.php | 11 +- tests/S3/PostObjectTest.php | 4 +- tests/S3/PostObjectV4Test.php | 12 +- .../ConfigurationProviderTest.php | 33 ++-- .../S3/RegionalEndpoint/ConfigurationTest.php | 9 +- .../RetryableMalformedResponseParserTest.php | 9 +- tests/S3/S3ClientTest.php | 110 +++++------ tests/S3/S3EndpointMiddlewareTest.php | 32 ++-- tests/S3/S3MultiRegionClientTest.php | 44 ++--- tests/S3/S3UriParserTest.php | 5 + tests/S3/SSECMiddlewareTest.php | 7 +- tests/S3/StreamWrapperPathStyleTest.php | 126 +++++-------- tests/S3/StreamWrapperTest.php | 134 ++++++------- tests/S3/TransferTest.php | 62 +++--- .../ConfigurationProviderTest.php | 31 ++- tests/S3/UseArnRegion/ConfigurationTest.php | 9 +- tests/S3Control/EndpointArnMiddlewareTest.php | 4 +- tests/SdkTest.php | 7 +- tests/Signature/S3SignatureV4Test.php | 30 +-- tests/Signature/SignatureProviderTest.php | 7 +- tests/Signature/SignatureV4Test.php | 64 ++++--- tests/Sqs/SqsClientTest.php | 27 ++- tests/StreamRequestPayloadMiddlewareTest.php | 8 +- .../ConfigurationProviderTest.php | 37 ++-- .../RegionalEndpoints/ConfigurationTest.php | 9 +- tests/Sts/StsClientTest.php | 17 +- tests/TraceMiddlewareTest.php | 69 +++---- tests/WaiterTest.php | 12 +- tests/WrappedHttpHandlerTest.php | 10 +- tests/bootstrap.php | 23 ++- 144 files changed, 1829 insertions(+), 1405 deletions(-) create mode 100644 tests/CloudFront/fixtures/test2.pem create mode 100644 tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php create mode 100644 tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php create mode 100644 tests/Polyfill/PHPUnit9/ArraySubset.php create mode 100644 tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9d86e72fec..2d5ed13f1a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -16,7 +16,7 @@ jobs: strategy: #for each of the following versions of PHP, with and without --prefer-lowest matrix: - php-versions: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4'] + php-versions: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1'] composer-options: ['', '--prefer-lowest'] #set the name for each job name: PHP ${{ matrix.php-versions }} ${{ matrix.composer-options }} @@ -42,28 +42,32 @@ jobs: - name: Validate composer.json and composer.lock run: composer validate - #downgrade to supported php unit and remove incompatible xdebug file if it exists + #remove incompatible xdebug file if it exists - if: ${{ matrix.php-versions == '5.5' }} - name: PHP 5.5 specific setup + name: PHP 5.5 run: | sudo rm -f /etc/php5/cli/conf.d/20-xdebug.ini - composer require --dev --ignore-platform-reqs phpunit/phpunit "4.8.36" - - #downgrade to supported php unit - - if: ${{ matrix.php-versions <= '7.1' && matrix.php-versions > 5.5}} - name: PHP 5.6-7.1 specific setup - run: composer require --dev --ignore-platform-reqs phpunit/phpunit "^5.7.11" #get dependencies - name: Install dependencies run: composer update ${{ matrix.composer-options }} --no-interaction --prefer-source + #php 8.x requirements + - if: ${{ matrix.php-versions >= '8.0' && matrix.composer-options != '' }} + name: PHP 8.x + run: composer require --dev phpunit/phpunit "^9.5" --no-interaction --prefer-source --with-all-dependencies + + #php 8.1 requirements + - if: ${{ matrix.php-versions >= '8.1' && matrix.composer-options != '' }} + name: PHP 8.1 + run: composer require --dev guzzlehttp/guzzle "^7.3" --no-interaction --prefer-source --with-all-dependencies + #run tests - name: Run test suite run: make test #static analysis - - if: ${{ matrix.php-versions >= '7.1' && matrix.php-versions <= 7.4 && matrix.composer-options == '' }} + - if: ${{ matrix.php-versions >= '7.1' && matrix.php-versions < '8.0' && matrix.composer-options == '' }} name: Static analysis run: | composer require --dev nette/neon "^3.0" @@ -79,6 +83,6 @@ jobs: make package #generate code coverage - - if: ${{ matrix.php-versions == '7.1' && matrix.composer-options == '' }} + - if: ${{ (matrix.php-versions == '7.1' || matrix.php-versions == '8.0') && matrix.composer-options == '' }} name: Code coverage run: bash <(curl -s https://codecov.io/bash) diff --git a/.gitignore b/.gitignore index fcd68067cf..3dd71323a3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ test_services.json /Makefile .idea .php_cs.cache +.phpunit.result.cache atlassian-ide-plugin.xml aws-sdk-php.iml .DS_Store diff --git a/composer.json b/composer.json index 3b6dc55b34..97aa94391e 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "ext-dom": "*", "ext-pcntl": "*", "ext-sockets": "*", - "phpunit/phpunit": "^4.8.35 || ^5.6.3", + "phpunit/phpunit": "^4.8.35 || ^5.6.3|^9.5", "behat/behat": "~3.0", "doctrine/cache": "~1.4", "aws/aws-php-sns-message-validator": "~1.0", @@ -41,7 +41,7 @@ "psr/cache": "^1.0", "psr/simple-cache": "^1.0", "paragonie/random_compat": ">= 2", - "sebastian/comparator": "^1.2.3" + "sebastian/comparator": "^1.2.3|^4.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 c6b27adde0..ec6f5ddae3 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,33 +1,24 @@ - - - - - - - - - - - - tests/ - tests/Integ - - - tests/Integ - - - - - - src - - src/data - - - - - - + + + + src + + + src/data + + + + + + + + tests/ + tests/Integ + + + tests/Integ + + + diff --git a/src/MockHandler.php b/src/MockHandler.php index a2c2ba8fa3..61373ad841 100644 --- a/src/MockHandler.php +++ b/src/MockHandler.php @@ -37,7 +37,7 @@ public function __construct( $this->onRejected = $onRejected; if ($resultOrQueue) { - call_user_func_array([$this, 'append'], $resultOrQueue); + call_user_func_array([$this, 'append'], array_values($resultOrQueue)); } } diff --git a/tests/AbstractConfigurationProviderTest.php b/tests/AbstractConfigurationProviderTest.php index 7bfa64c802..8ed3a04275 100644 --- a/tests/AbstractConfigurationProviderTest.php +++ b/tests/AbstractConfigurationProviderTest.php @@ -5,6 +5,7 @@ use Aws\LruArrayCache; use Aws\Result; use Aws\ResultInterface; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -13,6 +14,8 @@ */ class AbstractConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + /** @var \PHPUnit_Framework_MockObject_MockObject */ private $provider; @@ -65,11 +68,9 @@ public function testChainsConfiguration() $this->assertSame($expected, $result); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); call_user_func([$this->provider, 'chain']); } diff --git a/tests/Api/ApiProviderTest.php b/tests/Api/ApiProviderTest.php index c346bb6569..16e98537d4 100644 --- a/tests/Api/ApiProviderTest.php +++ b/tests/Api/ApiProviderTest.php @@ -3,6 +3,7 @@ use Aws\Api\ApiProvider; use Aws\Exception\UnresolvedApiException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ApiProviderTest extends TestCase { + use PHPUnitCompatTrait; + /** * @return ApiProvider; */ @@ -30,7 +33,7 @@ public function testCanResolveProvider() $this->assertEquals($result, ApiProvider::resolve($p, 't', 's', 'v')); $p = function ($a, $b, $c) {return null;}; - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); ApiProvider::resolve($p, 't', 's', 'v'); } @@ -66,15 +69,13 @@ public function testManifestProviderCanLoadData() { $p = $this->getTestApiProvider(); $data = $p('api', 'dynamodb', 'latest'); - $this->assertInternalType('array', $data); + $this->assertIsArray($data); $this->assertArrayHasKey('foo', $data); } - /** - * @expectedException \InvalidArgumentException - */ public function testFilesystemProviderEnsuresDirectoryIsValid() { + $this->expectException(\InvalidArgumentException::class); ApiProvider::filesystem('/path/to/invalid/dir'); } @@ -116,21 +117,21 @@ public function testReturnsWaiterConfigsForLatestCompatibleVersion() public function testThrowsOnBadType() { - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); $p = $this->getTestApiProvider(); ApiProvider::resolve($p, 'foo', 's3', 'latest'); } public function testThrowsOnBadService() { - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); $p = $this->getTestApiProvider(); ApiProvider::resolve($p, 'api', '', 'latest'); } public function testThrowsOnBadVersion() { - $this->setExpectedException(UnresolvedApiException::class); + $this->expectException(UnresolvedApiException::class); $p = $this->getTestApiProvider(); ApiProvider::resolve($p, 'api', 'dynamodb', 'derp'); } diff --git a/tests/Api/ErrorParser/XmlErrorParserTest.php b/tests/Api/ErrorParser/XmlErrorParserTest.php index fb6f98a965..6a87c23703 100644 --- a/tests/Api/ErrorParser/XmlErrorParserTest.php +++ b/tests/Api/ErrorParser/XmlErrorParserTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\ErrorParser; use Aws\Api\ErrorParser\XmlErrorParser; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\TestServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -11,6 +12,7 @@ */ class XmlErrorParserTest extends TestCase { + use PHPUnitCompatTrait; use TestServiceTrait; /** diff --git a/tests/Api/ListShapeTest.php b/tests/Api/ListShapeTest.php index 552526c385..a14f702998 100644 --- a/tests/Api/ListShapeTest.php +++ b/tests/Api/ListShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\ListShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ListShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsMember() { $s = new ListShape( @@ -23,11 +26,9 @@ public function testReturnsMember() $this->assertSame('string', $m->getType()); } - /** - * @expectedException \RuntimeException - */ public function testFailsWhenMemberIsMissing() { + $this->expectException(\RuntimeException::class); (new ListShape([], new ShapeMap([])))->getMember(); } } diff --git a/tests/Api/MapShapeTest.php b/tests/Api/MapShapeTest.php index 794dfa13b3..c1c14633fe 100644 --- a/tests/Api/MapShapeTest.php +++ b/tests/Api/MapShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\MapShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class MapShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsValue() { $s = new MapShape(['value' => ['type' => 'string']], new ShapeMap([])); @@ -19,11 +22,9 @@ public function testReturnsValue() $this->assertSame($v, $s->getValue()); } - /** - * @expectedException \RuntimeException - */ public function testFailsWhenValueIsMissing() { + $this->expectException(\RuntimeException::class); (new MapShape([], new ShapeMap([])))->getValue(); } diff --git a/tests/Api/OperationTest.php b/tests/Api/OperationTest.php index 11fc3f9b05..2a0e9f2614 100644 --- a/tests/Api/OperationTest.php +++ b/tests/Api/OperationTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\Operation; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class OperationTest extends TestCase { + use PHPUnitCompatTrait; + public function testCreatesDefaultMethodAndUri() { $o = new Operation([], new ShapeMap([])); @@ -22,7 +25,7 @@ public function testReturnsEmptyShapes() $o = new Operation([], new ShapeMap([])); $this->assertInstanceOf('Aws\Api\Shape', $o->getInput()); $this->assertInstanceOf('Aws\Api\Shape', $o->getOutput()); - $this->assertInternalType('array', $o->getErrors()); + $this->assertIsArray($o->getErrors()); } public function testReturnsInputShape() @@ -60,7 +63,7 @@ public function testReturnsErrorsShapeArray() 'b' => ['type' => 'list'], ])); $e = $o->getErrors(); - $this->assertInternalType('array', $e); + $this->assertIsArray($e); $this->assertInstanceOf('Aws\Api\Shape', $e[0]); $this->assertInstanceOf('Aws\Api\Shape', $e[1]); $this->assertSame('structure', $e[0]->getType()); diff --git a/tests/Api/Parser/ComplianceTest.php b/tests/Api/Parser/ComplianceTest.php index 9e01af5b66..c3a66467c8 100644 --- a/tests/Api/Parser/ComplianceTest.php +++ b/tests/Api/Parser/ComplianceTest.php @@ -22,6 +22,7 @@ class ComplianceTest extends TestCase { use UsesServiceTrait; + /** @doesNotPerformAssertions */ public function testCaseProvider() { $cases = []; diff --git a/tests/Api/Parser/Crc32ValidatingParserTest.php b/tests/Api/Parser/Crc32ValidatingParserTest.php index 25881ee59b..7fbc169176 100644 --- a/tests/Api/Parser/Crc32ValidatingParserTest.php +++ b/tests/Api/Parser/Crc32ValidatingParserTest.php @@ -7,6 +7,7 @@ use Aws\Api\Service; use Aws\Command; use Aws\Exception\AwsException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class Crc32ValidatingParserTest extends TestCase { + use PHPUnitCompatTrait; + private function getWrapped() { $provider = ApiProvider::defaultProvider(); @@ -40,7 +43,7 @@ public function testThrowsWhenMismatch() $wrapped($command, $response); $this->fail(); } catch (AwsException $e) { - $this->assertContains('crc32 mismatch. Expected 123, found 11124959', $e->getMessage()); + $this->assertStringContainsString('crc32 mismatch. Expected 123, found 11124959', $e->getMessage()); $this->assertTrue($e->isConnectionError()); } } diff --git a/tests/Api/Parser/DecodingEventStreamIteratorTest.php b/tests/Api/Parser/DecodingEventStreamIteratorTest.php index 893dbee4a8..201881458c 100644 --- a/tests/Api/Parser/DecodingEventStreamIteratorTest.php +++ b/tests/Api/Parser/DecodingEventStreamIteratorTest.php @@ -4,6 +4,7 @@ use Aws\Api\Parser\DecodingEventStreamIterator; use Aws\Api\Parser\Exception\ParserException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Stream; use PHPUnit\Framework\TestCase; @@ -13,6 +14,8 @@ */ class DecodingEventStreamIteratorTest extends TestCase { + use PHPUnitCompatTrait; + public function complianceTests() { $cases = []; @@ -130,11 +133,10 @@ public function testPassesComplianceTest( $this->fail('Unsuccessful parse of event from valid source.'); } - $this->assertContains( + $this->assertStringContainsStringIgnoringCase( (string) $decodedData, $e->getMessage(), - '', - true + '' ); } } diff --git a/tests/Api/Parser/EventParsingIteratorTest.php b/tests/Api/Parser/EventParsingIteratorTest.php index f920322e5b..e73a9b35c4 100644 --- a/tests/Api/Parser/EventParsingIteratorTest.php +++ b/tests/Api/Parser/EventParsingIteratorTest.php @@ -9,6 +9,7 @@ use Aws\Api\ShapeMap; use Aws\Api\StructureShape; use Aws\Exception\EventStreamDataException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; @@ -18,6 +19,8 @@ */ class EventParsingIteratorTest extends TestCase { + use PHPUnitCompatTrait; + /** @var array */ private static $successEventNames = [ 'end_event', @@ -29,7 +32,7 @@ class EventParsingIteratorTest extends TestCase /** @var StructureShape */ private $eventstreamShape; - public function setUp() + public function _setUp() { $shape = json_decode( file_get_contents( @@ -131,12 +134,10 @@ public function testThrowsOnErrorEvent() } } - /** - * @expectedException Aws\Api\Parser\Exception\ParserException - * @expectedExceptionMessage Failed to parse unknown message type. - */ public function testThrowsOnUnknownMessageType() { + $this->expectExceptionMessage("Failed to parse unknown message type."); + $this->expectException(\Aws\Api\Parser\Exception\ParserException::class); $stream = Psr7\Utils::streamFor( base64_decode(file_get_contents( __DIR__ . '/../eventstream_fixtures/input/unknown_message_type' @@ -153,12 +154,10 @@ public function testThrowsOnUnknownMessageType() $iterator->current(); } - /** - * @expectedException Aws\Api\Parser\Exception\ParserException - * @expectedExceptionMessage Failed to parse without event type. - */ public function testThrowsOnUnknownEventType() { + $this->expectExceptionMessage("Failed to parse without event type."); + $this->expectException(\Aws\Api\Parser\Exception\ParserException::class); $stream = Psr7\Utils::streamFor( base64_decode(file_get_contents( __DIR__ . '/../eventstream_fixtures/input/unknown_event_type' diff --git a/tests/Api/Parser/JsonParserTest.php b/tests/Api/Parser/JsonParserTest.php index bd8f2fe43b..4368c8b948 100644 --- a/tests/Api/Parser/JsonParserTest.php +++ b/tests/Api/Parser/JsonParserTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,6 +13,7 @@ */ class JsonParserTest extends TestCase { + use PHPUnitCompatTrait; use ParserTestServiceTrait; public function timeStampModelProvider() @@ -119,7 +121,7 @@ public function testTimeStampExceptions( $command = $client->getCommand($commandName); $list = $client->getHandlerList(); $handler = $list->resolve(); - $this->setExpectedException($expectedException, $expectedMessage); + $this->expectException($expectedException, $expectedMessage); $handler($command)->wait(); } } diff --git a/tests/Api/Parser/JsonRpcParserTest.php b/tests/Api/Parser/JsonRpcParserTest.php index d5fa2388c2..38df19c5e8 100644 --- a/tests/Api/Parser/JsonRpcParserTest.php +++ b/tests/Api/Parser/JsonRpcParserTest.php @@ -12,6 +12,7 @@ class JsonRpcParserTest extends TestCase { + /** @doesNotPerformAssertions */ public function testCanHandleNullResponses() { $operation = $this->getMockBuilder(Operation::class) diff --git a/tests/Api/Parser/XmlParserTest.php b/tests/Api/Parser/XmlParserTest.php index 136965835d..ed831ceb70 100644 --- a/tests/Api/Parser/XmlParserTest.php +++ b/tests/Api/Parser/XmlParserTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; ; @@ -14,6 +15,7 @@ */ class XmlParserTest extends TestCase { + use PHPUnitCompatTrait; use ParserTestServiceTrait; public function timeStampModelProvider() @@ -117,7 +119,7 @@ public function testExceptionTimeStamps( $command = $client->getCommand($commandName); $list = $client->getHandlerList(); $handler = $list->resolve(); - $this->setExpectedException($expectedException, $expectedMessage); + $this->expectException($expectedException, $expectedMessage); $handler($command)->wait(); } diff --git a/tests/Api/Serializer/ComplianceTest.php b/tests/Api/Serializer/ComplianceTest.php index 4f1a0e99cb..fc11d15021 100644 --- a/tests/Api/Serializer/ComplianceTest.php +++ b/tests/Api/Serializer/ComplianceTest.php @@ -21,6 +21,7 @@ class ComplianceTest extends TestCase { use UsesServiceTrait; + /** @doesNotPerformAssertions */ public function testCaseProvider() { $cases = []; diff --git a/tests/Api/Serializer/RestJsonSerializerTest.php b/tests/Api/Serializer/RestJsonSerializerTest.php index b53188fc4a..c7c6a02931 100644 --- a/tests/Api/Serializer/RestJsonSerializerTest.php +++ b/tests/Api/Serializer/RestJsonSerializerTest.php @@ -4,6 +4,7 @@ use Aws\Api\Service; use Aws\Command; use Aws\Api\Serializer\RestJsonSerializer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -12,6 +13,7 @@ */ class RestJsonSerializerTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getTestService() @@ -221,11 +223,9 @@ public function testPreparesRequestsWithJsonValueTraitEmptyString() $this->assertSame('', $request->getHeaderLine('Content-Type')); } - /** - * @expectedException \InvalidArgumentException - */ public function testPreparesRequestsWithJsonValueTraitThrowsException() { + $this->expectException(\InvalidArgumentException::class); $obj = new \stdClass(); $obj->obj = $obj; $this->getRequest('foobar', ['baz' => $obj]); diff --git a/tests/Api/Serializer/RestXmlSerializerTest.php b/tests/Api/Serializer/RestXmlSerializerTest.php index da806cf5be..5db0a6e040 100644 --- a/tests/Api/Serializer/RestXmlSerializerTest.php +++ b/tests/Api/Serializer/RestXmlSerializerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api\Serializer; use Aws\Api\Serializer\RestXmlSerializer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -10,6 +11,7 @@ */ class RestXmlSerializerTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getRequest($commandName, $input) @@ -42,7 +44,7 @@ public function testEscapesAllXMLCharacters() ], ]); $contents = $request->getBody()->getContents(); - $this->assertContains( + $this->assertStringContainsString( "/@/#/=/;/:/ /,/?/'/"/</>/&/ / /", $contents ); diff --git a/tests/Api/ServiceTest.php b/tests/Api/ServiceTest.php index 0594abd6b5..3458e535ce 100644 --- a/tests/Api/ServiceTest.php +++ b/tests/Api/ServiceTest.php @@ -4,6 +4,7 @@ use Aws\Api\Parser\QueryParser; use Aws\Api\Service; use Aws\Api\StructureShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\TestServiceTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ */ class ServiceTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; use TestServiceTrait; @@ -63,7 +65,7 @@ function () { return []; } public function testReturnsMetadata() { $s = new Service([], function () { return []; }); - $this->assertInternalType('array', $s->getMetadata()); + $this->assertIsArray($s->getMetadata()); $s['metadata'] = [ 'serviceFullName' => 'foo', 'endpointPrefix' => 'bar', @@ -94,11 +96,9 @@ function () { return []; } $this->assertArrayHasKey('foo', $s->getOperations()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresOperationExists() { + $this->expectException(\InvalidArgumentException::class); $s = new Service([], function () { return []; }); $s->getOperation('foo'); } @@ -159,11 +159,9 @@ public function testCreatesRelevantErrorParsers($p, $cl) $this->assertInstanceOf($cl, Service::createErrorParser($p)); } - /** - * @expectedException \UnexpectedValueException - */ public function testThrowsOnUnexpectedProtocol() { + $this->expectException(\UnexpectedValueException::class); Service::createErrorParser('undefined_protocol'); } @@ -180,6 +178,7 @@ public function serializerDataProvider() /** * @dataProvider serializerDataProvider + * @doesNotPerformAssertions */ public function testCreatesSerializer($type, $cl) { @@ -204,6 +203,7 @@ public function parserDataProvider() /** * @dataProvider parserDataProvider + * @doesNotPerformAssertions */ public function testCreatesParsers($type, $cl) { diff --git a/tests/Api/ShapeMapTest.php b/tests/Api/ShapeMapTest.php index a650e3ac69..4bc2ca3e60 100644 --- a/tests/Api/ShapeMapTest.php +++ b/tests/Api/ShapeMapTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Api; use Aws\Api\ShapeMap; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,17 +10,17 @@ */ class ShapeMapTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsShapeName() { $sm = new ShapeMap(['foo' => [], 'baz' => []]); $this->assertEquals(['foo', 'baz'], $sm->getShapeNames()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresShapeExists() { + $this->expectException(\InvalidArgumentException::class); $sm = new ShapeMap([]); $sm->resolve(['shape' => 'missing']); } diff --git a/tests/Api/ShapeTest.php b/tests/Api/ShapeTest.php index 13e128e849..b72125d918 100644 --- a/tests/Api/ShapeTest.php +++ b/tests/Api/ShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -11,6 +12,8 @@ */ class ShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testImplementsArray() { $s = new Shape(['metadata' => ['foo' => 'bar']], new ShapeMap([])); @@ -27,11 +30,9 @@ public function testImplementsArray() $this->assertArrayNotHasKey('abc', $s); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesShapeAt() { + $this->expectException(\InvalidArgumentException::class); $s = new Shape([], new ShapeMap([])); $m = new \ReflectionMethod($s, 'shapeAt'); $m->setAccessible(true); @@ -69,12 +70,10 @@ public function testCreatesNestedShapeReferences() $this->assertSame('float', $s->getType()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Invalid type - */ public function testValidatesShapeTypes() { + $this->expectExceptionMessage("Invalid type"); + $this->expectException(\RuntimeException::class); $s = new Shape( ['foo' => ['type' => 'what?']], new ShapeMap([]) diff --git a/tests/Api/StructureShapeTest.php b/tests/Api/StructureShapeTest.php index 8b37fefc45..c92f6f7c32 100644 --- a/tests/Api/StructureShapeTest.php +++ b/tests/Api/StructureShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\ShapeMap; use Aws\Api\StructureShape; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class StructureShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsWhenMembersAreEmpty() { $s = new StructureShape([], new ShapeMap([])); @@ -36,18 +39,16 @@ public function testReturnsAllMembers() ] ], new ShapeMap([])); $members = $s->getMembers(); - $this->assertInternalType('array', $members); + $this->assertIsArray($members); $this->assertInstanceOf('Aws\Api\Shape', $members['foo']); $this->assertInstanceOf('Aws\Api\Shape', $members['baz']); $this->assertSame('string', $members['foo']->getType()); $this->assertSame('integer', $members['baz']->getType()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresMemberExists() { + $this->expectException(\InvalidArgumentException::class); (new StructureShape([], new ShapeMap([])))->getMember('foo'); } } diff --git a/tests/Api/TimestampShapeTest.php b/tests/Api/TimestampShapeTest.php index 64d757127c..ef4fe70c83 100644 --- a/tests/Api/TimestampShapeTest.php +++ b/tests/Api/TimestampShapeTest.php @@ -3,6 +3,7 @@ use Aws\Api\TimestampShape; use Aws\Api\ShapeMap; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class TimestampShapeTest extends TestCase { + use PHPUnitCompatTrait; + public function formatProvider() { $t = strtotime('january 5, 1999'); @@ -35,20 +38,16 @@ public function testFormatsData($value, $format, $result) $this->assertEquals($result, $s->format($value, $format)); } - /** - * @expectedException \UnexpectedValueException - */ public function testValidatesTimestampFormat() { + $this->expectException(\UnexpectedValueException::class); $s = new TimestampShape([], new ShapeMap([])); $s->format('now', 'foo'); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesTimestampValue() { + $this->expectException(\InvalidArgumentException::class); $s = new TimestampShape([], new ShapeMap([])); $s->format(true, 'iso8601'); } diff --git a/tests/Api/ValidatorTest.php b/tests/Api/ValidatorTest.php index 84dc29c249..caa6fec8a2 100644 --- a/tests/Api/ValidatorTest.php +++ b/tests/Api/ValidatorTest.php @@ -4,6 +4,7 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Aws\Api\Validator; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -12,6 +13,8 @@ */ class ValidatorTest extends TestCase { + use PHPUnitCompatTrait; + public function validationProvider() { return [ @@ -619,6 +622,7 @@ public function testValidatesInput($shape, $input, $result) try { $validator->validate('Foo', $shape, $input); + $this->expectNotToPerformAssertions(); if ($result !== true) { $this->fail('Should have failed with ' . $result); } @@ -631,12 +635,10 @@ public function testValidatesInput($shape, $input, $result) } } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage expected string length to be >= 1, but found string length of 0 - */ public function testValidatesMinByDefault() { + $this->expectExceptionMessage("expected string length to be >= 1, but found string length of 0"); + $this->expectException(\InvalidArgumentException::class); $shape = Shape::create( [ 'type' => 'structure', @@ -648,6 +650,7 @@ public function testValidatesMinByDefault() $validator->validate('Foo', $shape, ['foo' => '']); } + /** @doesNotPerformAssertions */ public function testDoesNotValidateMaxByDefault() { $shape = Shape::create( @@ -661,6 +664,7 @@ public function testDoesNotValidateMaxByDefault() $validator->validate('Foo', $shape, ['foo' => '1234567890']); } + /** @doesNotPerformAssertions */ public function testDoesNotValidatePatternsByDefault() { $validator = new Validator(); @@ -679,6 +683,7 @@ public function testDoesNotValidatePatternsByDefault() $validator->validate('Foo', $shape, ['caps' => 'abc']); } + /** @doesNotPerformAssertions */ public function testCanDisableRequiredTrait() { $validator = new Validator(['required' => false]); diff --git a/tests/AwsClientTest.php b/tests/AwsClientTest.php index 4a37aa0f04..510ef8d2a7 100644 --- a/tests/AwsClientTest.php +++ b/tests/AwsClientTest.php @@ -15,6 +15,7 @@ use Aws\S3\S3Client; use Aws\Signature\SignatureV4; use Aws\Sts\StsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\WrappedHttpHandler; use GuzzleHttp\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; @@ -25,6 +26,7 @@ */ class AwsClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getApiProvider() @@ -61,12 +63,10 @@ public function testHasGetters() $this->assertSame('foo', $client->getApi()->getEndpointPrefix()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Operation not found: Foo - */ public function testEnsuresOperationIsFoundWhenCreatingCommands() { + $this->expectExceptionMessage("Operation not found: Foo"); + $this->expectException(\InvalidArgumentException::class); $this->createClient()->getCommand('foo'); } @@ -86,12 +86,10 @@ public function testReturnsCommandForOperation() ); } - /** - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage Error executing "foo" on "http://us-east-1.foo.amazonaws.com"; AWS HTTP error: Baz Bar! - */ public function testWrapsExceptions() { + $this->expectExceptionMessage("Error executing \"foo\" on \"http://us-east-1.foo.amazonaws.com\"; AWS HTTP error: Baz Bar!"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $parser = function () {}; $errorParser = new JsonRpcErrorParser(); $h = new WrappedHttpHandler( @@ -163,11 +161,9 @@ public function testCanGetIteratorWithoutFullyDefinedPaginator() } } - /** - * @expectedException \UnexpectedValueException - */ public function testGetIteratorFailsForMissingConfig() { + $this->expectException(\UnexpectedValueException::class); $client = $this->createClient(); $client->getIterator('ListObjects'); } @@ -187,21 +183,17 @@ public function testCanGetPaginator() ); } - /** - * @expectedException \UnexpectedValueException - */ public function testGetPaginatorFailsForMissingConfig() { + $this->expectException(\UnexpectedValueException::class); $client = $this->createClient(); $client->getPaginator('ListObjects'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Operation not found - */ public function testCanWaitSynchronously() { + $this->expectExceptionMessage("Operation not found"); + $this->expectException(\InvalidArgumentException::class); $client = $this->createClient(['waiters' => ['PigsFly' => [ 'acceptors' => [], 'delay' => 1, @@ -212,11 +204,9 @@ public function testCanWaitSynchronously() $client->waitUntil('PigsFly'); } - /** - * @expectedException \UnexpectedValueException - */ public function testGetWaiterFailsForMissingConfig() { + $this->expectException(\UnexpectedValueException::class); $client = $this->createClient(); $client->waitUntil('PigsFly'); } @@ -269,9 +259,10 @@ public function testSignsRequestsUsingSigner() $client->describeInstances(); $request = $mock->getLastRequest(); $str = \GuzzleHttp\Psr7\Message::toString($request); - $this->assertContains('AWS4-HMAC-SHA256', $str); + $this->assertStringContainsString('AWS4-HMAC-SHA256', $str); } + /** @doesNotPerformAssertions */ public function testAllowsFactoryMethodForBc() { Ec2Client::factory([ @@ -280,6 +271,7 @@ public function testAllowsFactoryMethodForBc() ]); } + /** @doesNotPerformAssertions */ public function testCanInstantiateAliasedClients() { new SesClient([ @@ -294,15 +286,13 @@ public function testCanGetSignatureProvider() $ref = new \ReflectionMethod($client, 'getSignatureProvider'); $ref->setAccessible(true); $provider = $ref->invoke($client); - $this->assertInternalType('callable', $provider); + $this->assertIsCallable($provider); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Instances of Aws\AwsClient cannot be serialized - */ public function testDoesNotPermitSerialization() { + $this->expectExceptionMessage("Instances of Aws\AwsClient cannot be serialized"); + $this->expectException(\RuntimeException::class); $client = $this->createClient(); \serialize($client); } @@ -395,7 +385,7 @@ public function testUsesCommandContextSigningRegionAndService() CommandInterface $command, RequestInterface $request ) { - $this->assertContains('ap-southeast-1/custom-service', $request->getHeader('Authorization')[0]); + $this->assertStringContainsString('ap-southeast-1/custom-service', $request->getHeader('Authorization')[0]); return new Result; } ] @@ -436,12 +426,10 @@ public function testLoadsAliases() ); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Operation not found: GetConfig - */ public function testCallsAliasedFunction() { + $this->expectExceptionMessage("Operation not found: GetConfig"); + $this->expectException(\InvalidArgumentException::class); $client = $this->createClient([ 'metadata' => [ 'serviceId' => 'TestService', diff --git a/tests/Build/Changelog/ChangelogBuilderTest.php b/tests/Build/Changelog/ChangelogBuilderTest.php index 737222b5a4..3ddf1936d8 100644 --- a/tests/Build/Changelog/ChangelogBuilderTest.php +++ b/tests/Build/Changelog/ChangelogBuilderTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Build\Changelog; use Aws\Build\Changelog\ChangelogBuilder; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,25 +10,22 @@ */ class ChangelogBuilderTest extends TestCase { + use PHPUnitCompatTrait; private $RESOURCE_DIR = "tests/Build/Changelog/resources/"; - /** - * @expectedException \InvalidArgumentException - */ public function testBuildChangelogNoDirectory() { + $this->expectException(\InvalidArgumentException::class); $params = []; $params['base_dir'] = 'wrong-folder'; $obj = new ChangelogBuilder($params); $obj->buildChangelog(); } - /** - * @expectedException \InvalidArgumentException - */ public function testBuildChangelogNoReleaseNotes() { + $this->expectException(\InvalidArgumentException::class); $tempDir = sys_get_temp_dir() . "/"; if (!file_exists($tempDir . "/.changes/nextrelease/")) { mkdir($tempDir . "/.changes/nextrelease/", 0777, true); @@ -40,11 +38,9 @@ public function testBuildChangelogNoReleaseNotes() unlink($tempDir . "/.changes/nextrelease/"); } - /** - * @expectedException \InvalidArgumentException - */ public function testBuildChangelogInvalidChangelog() { + $this->expectException(\InvalidArgumentException::class); $params = []; $params['base_dir'] = $this->RESOURCE_DIR; $params['release_notes_output_dir'] = sys_get_temp_dir() . "/"; diff --git a/tests/Build/Changelog/CurrentChangesTest.php b/tests/Build/Changelog/CurrentChangesTest.php index 828d631e28..d83f1954dc 100644 --- a/tests/Build/Changelog/CurrentChangesTest.php +++ b/tests/Build/Changelog/CurrentChangesTest.php @@ -12,6 +12,7 @@ private function getNameFromFilePath($filePath) return end($portions); } + /** @doesNotPerformAssertions */ public function testVerifyDotChangesFolder() { $files = glob(__DIR__ . '/../../../.changes/*'); @@ -30,6 +31,7 @@ public function testVerifyDotChangesFolder() } } + /** @doesNotPerformAssertions */ public function testVerifyNextreleaseContents() { if (!is_dir(__DIR__ . '/../../../.changes/nextrelease/')) { diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index f3a377cd26..7d96eda0b6 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -16,6 +16,7 @@ use Aws\HandlerList; use Aws\Sdk; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -24,18 +25,18 @@ */ class ClientResolverTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required client configuration options - */ public function testEnsuresRequiredArgumentsAreProvided() { + $this->expectExceptionMessage("Missing required client configuration options"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver(ClientResolver::getDefaultArguments()); $r->resolve([], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testAddsValidationSubscriber() { $c = new DynamoDbClient([ @@ -50,6 +51,7 @@ public function testAddsValidationSubscriber() } catch (\InvalidArgumentException $e) {} } + /** @doesNotPerformAssertions */ public function testCanDisableValidation() { $c = new DynamoDbClient([ @@ -63,6 +65,7 @@ public function testCanDisableValidation() $c->execute($command); } + /** @doesNotPerformAssertions */ public function testCanDisableSpecificValidationConstraints() { $c = new DynamoDbClient([ @@ -161,12 +164,10 @@ public function testPrefersApiProviderNameToPartitionName() $this->assertSame($conf['config']['signing_name'], $signingName); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid configuration value provided for "foo". Expected string, but got int(-1) - */ public function testValidatesInput() { + $this->expectExceptionMessage("Invalid configuration value provided for \"foo\". Expected string, but got int(-1)"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver([ 'foo' => [ 'type' => 'value', @@ -176,12 +177,10 @@ public function testValidatesInput() $r->resolve(['foo' => -1], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid configuration value provided for "foo". Expected callable, but got string(1) "c" - */ public function testValidatesCallables() { + $this->expectExceptionMessage("Invalid configuration value provided for \"foo\". Expected callable, but got string(1) \"c\""); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver([ 'foo' => [ 'type' => 'value', @@ -206,14 +205,14 @@ public function testValidatesCallableClosure() $this->assertSame('callable_test', $res['foo']); } - public function checkCallable() + public static function checkCallable() { return "testcall"; } public function testValidatesNotInvokeStringCallable() { - $callableFunction = '\Aws\test\ClientResolverTest::checkCallable'; + $callableFunction = '\Aws\Test\ClientResolverTest::checkCallable'; $r = new ClientResolver([ 'foo' => [ 'type' => 'value', @@ -222,19 +221,17 @@ public function testValidatesNotInvokeStringCallable() ] ]); $res = $r->resolve([], new HandlerList()); - $this->assertInternalType('callable', $callableFunction); + $this->assertIsCallable($callableFunction); $this->assertSame( - '\Aws\test\ClientResolverTest::checkCallable', + '\Aws\Test\ClientResolverTest::checkCallable', $res['foo'] ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Credentials must be an - */ public function testValidatesCredentials() { + $this->expectExceptionMessage("Credentials must be an"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver([ 'credentials' => ClientResolver::getDefaultArguments()['credentials'] ]); @@ -283,6 +280,7 @@ public function testCreatesFromArray() $this->assertSame($exp, $creds->getExpiration()); } + /** @doesNotPerformAssertions */ public function testCanDisableRetries() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -294,6 +292,7 @@ public function testCanDisableRetries() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testCanEnableRetries() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -305,6 +304,7 @@ public function testCanEnableRetries() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testCanEnableRetriesStandardMode() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -319,6 +319,7 @@ public function testCanEnableRetriesStandardMode() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testCanEnableRetriesAdaptivedMode() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -665,6 +666,7 @@ public function s3EndpointCases() ]; } + /** @doesNotPerformAssertions */ public function testAddsLoggerWithDebugSettings() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -677,6 +679,7 @@ public function testAddsLoggerWithDebugSettings() ], new HandlerList()); } + /** @doesNotPerformAssertions */ public function testAddsDebugListener() { $em = new HandlerList(); @@ -725,6 +728,7 @@ public function testCanAddConfigOptions() $this->assertTrue($c->getConfig('bucket_endpoint')); } + /** @doesNotPerformAssertions */ public function testSkipsNonRequiredKeys() { $r = new ClientResolver([ @@ -736,23 +740,19 @@ public function testSkipsNonRequiredKeys() $r->resolve([], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "version" configuration value is required - */ public function testHasSpecificMessageForMissingVersion() { + $this->expectExceptionMessage("A \"version\" configuration value is required"); + $this->expectException(\InvalidArgumentException::class); $args = ClientResolver::getDefaultArguments()['version']; $r = new ClientResolver(['version' => $args]); $r->resolve(['service' => 'foo'], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "version" configuration value is required - */ public function testHasSpecificMessageForNullRequiredVersion() { + $this->expectExceptionMessage("A \"version\" configuration value is required"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver(ClientResolver::getDefaultArguments()); $list = new HandlerList(); $r->resolve([ @@ -763,23 +763,19 @@ public function testHasSpecificMessageForNullRequiredVersion() ], $list); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "region" configuration value is required for the "foo" service - */ public function testHasSpecificMessageForMissingRegion() { + $this->expectExceptionMessage("A \"region\" configuration value is required for the \"foo\" service"); + $this->expectException(\InvalidArgumentException::class); $args = ClientResolver::getDefaultArguments()['region']; $r = new ClientResolver(['region' => $args]); $r->resolve(['service' => 'foo'], new HandlerList()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A "region" configuration value is required for the "foo" service - */ public function testHasSpecificMessageForNullRequiredRegion() { + $this->expectExceptionMessage("A \"region\" configuration value is required for the \"foo\" service"); + $this->expectException(\InvalidArgumentException::class); $r = new ClientResolver(ClientResolver::getDefaultArguments()); $list = new HandlerList(); $r->resolve([ @@ -802,7 +798,7 @@ public function testAddsTraceMiddleware() 'debug' => ['logfn' => function ($value) use (&$str) { $str .= $value; }] ], $list); $value = $this->readAttribute($list, 'interposeFn'); - $this->assertInternalType('callable', $value); + $this->assertIsCallable($value); } public function testAppliesUserAgent() @@ -817,7 +813,7 @@ public function testAppliesUserAgent() 'ua_append' => 'PHPUnit/Unit', ], $list); $this->assertArrayHasKey('ua_append', $conf); - $this->assertInternalType('array', $conf['ua_append']); + $this->assertIsArray($conf['ua_append']); $this->assertContains('PHPUnit/Unit', $conf['ua_append']); $this->assertContains('aws-sdk-php/' . Sdk::VERSION, $conf['ua_append']); } diff --git a/tests/ClientSideMonitoring/ConfigurationProviderTest.php b/tests/ClientSideMonitoring/ConfigurationProviderTest.php index 5151ccf1ae..73f37683bb 100644 --- a/tests/ClientSideMonitoring/ConfigurationProviderTest.php +++ b/tests/ClientSideMonitoring/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\ClientSideMonitoring\ConfigurationProvider; use Aws\ClientSideMonitoring\Exception\ConfigurationException; use Aws\LruArrayCache; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -16,6 +17,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENABLED) ?: '', @@ -75,7 +78,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENABLED . '=' . self::$originalEnv['enabled']); @@ -235,21 +238,17 @@ public function testCreatesWithDefaultsFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[aws_csm]"; file_put_contents($dir . '/config', $ini); @@ -263,12 +262,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -281,12 +278,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\ClientSideMonitoring\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\ClientSideMonitoring\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -479,12 +474,11 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ConfigurationProvider::unwrap($toUnwrap)->toArray() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid CSM configuration argument. - */ + public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid CSM configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/ClientSideMonitoring/ConfigurationTest.php b/tests/ClientSideMonitoring/ConfigurationTest.php index 1e6b1d4e70..c2db64036a 100644 --- a/tests/ClientSideMonitoring/ConfigurationTest.php +++ b/tests/ClientSideMonitoring/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\ClientSideMonitoring; use Aws\ClientSideMonitoring\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Log\InvalidArgumentException; @@ -12,6 +13,7 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; public function testGetsCorrectValues() { @@ -34,11 +36,9 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException InvalidArgumentException - */ public function testHandlesInvalidPort() { + $this->expectException(\InvalidArgumentException::class); new Configuration(true, 'invalidport', 'FooApp'); } diff --git a/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php b/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php index 2d3cf4b0ed..1739d4c2b5 100644 --- a/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php +++ b/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php @@ -5,10 +5,13 @@ use Aws\HandlerList; use Aws\MonitoringEventsInterface; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; trait MonitoringMiddlewareTestingTrait { + use PHPUnitCompatTrait; + /** * @dataProvider getMonitoringDataTests */ @@ -67,6 +70,6 @@ public function testPopulatesMonitoringData( $this->assertTrue($called); $this->assertArraySubset($expected, $eventData); - $this->assertInternalType('int', $eventData['Timestamp']); + $this->assertIsInt($eventData['Timestamp']); } } \ No newline at end of file diff --git a/tests/CloudFront/CloudFrontClientTest.php b/tests/CloudFront/CloudFrontClientTest.php index 6145956b5f..4ab56beea1 100644 --- a/tests/CloudFront/CloudFrontClientTest.php +++ b/tests/CloudFront/CloudFrontClientTest.php @@ -1,7 +1,9 @@ key = realpath(__DIR__.'/fixtures/test2.pem'); + $this->kp = 'test'; + } + public function testEnsuresKeysArePassed() { + $this->expectException(\InvalidArgumentException::class); $c = new CloudFrontClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -21,45 +32,33 @@ public function testEnsuresKeysArePassed() $c->getSignedUrl([]); } + /** @doesNotPerformAssertions */ public function testCreatesSignedUrl() { - foreach (['CF_PRIVATE_KEY', 'CF_KEY_PAIR_ID'] as $k) { - if (!isset($_SERVER[$k]) || $_SERVER[$k] == 'change_me') { - $this->markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } - $c = new CloudFrontClient([ 'region' => 'us-west-2', 'version' => 'latest' ]); $c->getSignedUrl([ - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $_SERVER['CF_KEY_PAIR_ID'], + 'private_key' => $this->key, + 'key_pair_id' => $this->kp, 'url' => 'https://foo.bar.com', 'expires' => strtotime('+10 minutes'), ]); } + /** @doesNotPerformAssertions */ public function testCreatesSignedCookie() { - foreach (['CF_PRIVATE_KEY', 'CF_KEY_PAIR_ID'] as $k) { - if (!isset($_SERVER[$k]) || $_SERVER[$k] == 'change_me') { - $this->markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } - $c = new CloudFrontClient([ 'region' => 'us-west-2', 'version' => 'latest' ]); $c->getSignedCookie([ - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $_SERVER['CF_KEY_PAIR_ID'], + 'private_key' => $this->key, + 'key_pair_id' => $this->kp, 'url' => 'https://foo.bar.com', 'expires' => strtotime('+10 minutes'), ]); diff --git a/tests/CloudFront/CookieSignerTest.php b/tests/CloudFront/CookieSignerTest.php index ddbdfe3f31..791fcfffa4 100644 --- a/tests/CloudFront/CookieSignerTest.php +++ b/tests/CloudFront/CookieSignerTest.php @@ -3,43 +3,41 @@ use Aws\CloudFront\CookieSigner; use Aws\CloudFront\Policy; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class CookieSignerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + protected $key; + protected $kp; + + public function _setUp() { - foreach (['CF_PRIVATE_KEY', 'CF_KEY_PAIR_ID'] as $k) { - if (!isset($_SERVER[$k]) || $_SERVER[$k] == 'change_me') { - $this->markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } + $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + $this->kp = 'test'; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid or missing URI scheme - */ public function testEnsuresUriSchemeIsPresent() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid or missing URI scheme"); + $this->expectException(\InvalidArgumentException::class); + $s = new CookieSigner('a', $this->key); $s->getSignedCookie('bar.com'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid or missing URI scheme - */ public function testEnsuresUriSchemeIsValid() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid or missing URI scheme"); + $this->expectException(\InvalidArgumentException::class); + $s = new CookieSigner('a', $this->key); $s->getSignedCookie('foo://bar.com', strtotime('+10 minutes')); } public function testAllowsHttpScheme() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie('http://bar.com', strtotime('+10 minutes')); $this->assertNotEmpty($cookie); @@ -47,7 +45,7 @@ public function testAllowsHttpScheme() public function testAllowsHttpsScheme() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie('https://bar.com', strtotime('+10 minutes')); $this->assertNotEmpty($cookie); @@ -55,7 +53,7 @@ public function testAllowsHttpsScheme() public function testAllowsWildcardScheme() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie( 'http*://bar.com/*', null, @@ -67,7 +65,7 @@ public function testAllowsWildcardScheme() public function testReturnsHashWithCookieParameterNamesForCannedPolicy() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie('https://bar.com', strtotime('+10 minutes')); $this->assertArrayHasKey('CloudFront-Signature', $cookie); @@ -78,7 +76,7 @@ public function testReturnsHashWithCookieParameterNamesForCannedPolicy() public function testReturnsHashWithCookieParameterNamesForCustomPolicy() { - $s = new CookieSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new CookieSigner('a', $this->key); $cookie = $s->getSignedCookie( 'http*://bar.com/*', null, diff --git a/tests/CloudFront/SignerTest.php b/tests/CloudFront/SignerTest.php index c3e7354455..7d992a1156 100644 --- a/tests/CloudFront/SignerTest.php +++ b/tests/CloudFront/SignerTest.php @@ -3,17 +3,20 @@ use Aws\CloudFront\Policy; use Aws\CloudFront\Signer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class SignerTest extends TestCase { + use PHPUnitCompatTrait; + /** @var Signer */ private $instance; private $testKeyFile; const PASSPHRASE = "1234"; - public function setUp() + public function _setUp() { $this->testKeyFile =__DIR__ . '/fixtures/test.pem'; $this->instance = new Signer( @@ -25,11 +28,10 @@ public function setUp() /** * Assert that the key variable contents are parsed during construction - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /PK .*Not a real private key/ */ public function testBadPrivateKeyContents() { + $this->expectExceptionMessageMatches("/PK .*Not a real private key/"); + $this->expectException(\InvalidArgumentException::class); $privateKey = "Not a real private key"; $s = new Signer( "not a real keypair id", @@ -39,11 +41,10 @@ public function testBadPrivateKeyContents() { /** * Assert that the key file is parsed during construction - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /PEM .*no start line/ */ public function testBadPrivateKeyPath() { + $this->expectExceptionMessageMatches("/PEM .*no start line/"); + $this->expectException(\InvalidArgumentException::class); $filename = tempnam(sys_get_temp_dir(), 'cloudfront-fake-key'); file_put_contents($filename, "Not a real private key"); try { @@ -56,21 +57,17 @@ public function testBadPrivateKeyPath() { } } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage PK file not found - */ public function testEnsuresPkFileExists() { + $this->expectExceptionMessage("PK file not found"); + $this->expectException(\InvalidArgumentException::class); $s = new Signer('a', 'b'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Either a policy or a resource and an expiration time must be provided. - */ public function testEnsuresExpiresIsSetWhenUsingCannedPolicy() { + $this->expectExceptionMessage("Either a policy or a resource and an expiration time must be provided."); + $this->expectException(\InvalidArgumentException::class); $s = new Signer('a', $this->testKeyFile, self::PASSPHRASE); $s->getSignature('http://foo/bar'); } @@ -103,7 +100,7 @@ public function testReturnsExpiresForCannedPolicies($expires) $signature = $this->instance->getSignature('test.mp4', $expires); $this->assertArrayHasKey('Expires', $signature); - $this->assertInternalType('int', $signature['Expires']); + $this->assertIsInt($signature['Expires']); } public function testReturnsPolicyForCustomPolicies() @@ -134,7 +131,7 @@ public function testSignatureContainsNoForbiddenCharacters() { $signature = $this->instance->getSignature('test.mp4', time() + 1000); - $this->assertNotRegExp('/[\+\=\/]/', $signature['Signature']); + $this->assertDoesNotMatchRegularExpression('/[\+\=\/]/', $signature['Signature']); } public function testPolicyContainsNoForbiddenCharacters() @@ -142,7 +139,7 @@ public function testPolicyContainsNoForbiddenCharacters() $signature = $this->instance ->getSignature(null, null, $this->getCustomPolicy()); - $this->assertNotRegExp('/[\+\=\/]/', $signature['Policy']); + $this->assertDoesNotMatchRegularExpression('/[\+\=\/]/', $signature['Policy']); } /** diff --git a/tests/CloudFront/UrlSignerTest.php b/tests/CloudFront/UrlSignerTest.php index f9933c4d0d..74dbd44b3b 100644 --- a/tests/CloudFront/UrlSignerTest.php +++ b/tests/CloudFront/UrlSignerTest.php @@ -1,8 +1,10 @@ markTestSkipped('$_SERVER[\'' . $k . '\'] not set in ' - . 'phpunit.xml'); - } - } + $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + $this->kp = 'test'; } public function testCreatesUrlSignersForHttp() @@ -28,30 +31,28 @@ public function testCreatesUrlSignersForHttp() 'region' => 'us-west-2', 'version' => 'latest' ]); - $ts = time() + 1000; - $key = $_SERVER['CF_PRIVATE_KEY']; - $kp = $_SERVER['CF_KEY_PAIR_ID']; + $ts = time() + 1000; $url = $client->getSignedUrl([ 'url' => 'http://abc.cloudfront.net/images/image.jpg?color=red', 'expires' => $ts, - 'private_key' => $key, - 'key_pair_id' => $kp + 'private_key' => $this->key, + 'key_pair_id' => $this->kp ]); - $this->assertContains("Key-Pair-Id={$kp}", $url); + $this->assertStringContainsString("Key-Pair-Id={$this->kp}", $url); $this->assertStringStartsWith( "http://abc.cloudfront.net/images/image.jpg?color=red&Expires={$ts}&Signature=", $url ); $urlObject = new Uri($url); - $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); + $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); $signature = $query['Signature']; - $this->assertNotContains('?', $signature); - $this->assertNotContains('=', $signature); - $this->assertNotContains('/', $signature); - $this->assertNotContains('&', $signature); - $this->assertNotContains('+', $signature); + $this->assertStringNotContainsString('?', $signature); + $this->assertStringNotContainsString('=', $signature); + $this->assertStringNotContainsString('/', $signature); + $this->assertStringNotContainsString('&', $signature); + $this->assertStringNotContainsString('+', $signature); } public function testCreatesUrlSignersWithSpecialCharacters() @@ -61,23 +62,21 @@ public function testCreatesUrlSignersWithSpecialCharacters() 'region' => 'us-west-2', 'version' => 'latest' ]); - $ts = time() + 1000; - $key = $_SERVER['CF_PRIVATE_KEY']; - $kp = $_SERVER['CF_KEY_PAIR_ID']; + $ts = time() + 1000; $invalidUri = 'http://abc.cloudfront.net/images/éüàçµñ圌.jpg?query key=query value'; - $uri = new Uri($invalidUri); + $uri = new Uri($invalidUri); $this->assertNotEquals($invalidUri, (string) $uri); $url = $client->getSignedUrl([ 'url' => $invalidUri, 'expires' => $ts, - 'private_key' => $key, - 'key_pair_id' => $kp + 'private_key' => $this->key, + 'key_pair_id' => $this->kp ]); - $this->assertContains("Key-Pair-Id={$kp}", $url); - $this->assertContains((string) $uri, $url); + $this->assertStringContainsString("Key-Pair-Id={$this->kp}", $url); + $this->assertStringContainsString((string) $uri, $url); $this->assertStringStartsWith( "{$uri}&Expires={$ts}&Signature=", $url @@ -91,14 +90,14 @@ public function testCreatesUrlSignersWithCustomPolicy() 'region' => 'us-west-2', 'version' => 'latest' ]); - $url = $client->getSignedUrl(array( - 'url' => 'http://abc.cloudfront.net/images/image.jpg', - 'policy' => '{}', - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $_SERVER['CF_KEY_PAIR_ID'] + $url = $client->getSignedUrl(array( + 'url' => 'http://abc.cloudfront.net/images/image.jpg', + 'policy' => '{}', + 'private_key' => $this->key, + 'key_pair_id' => $this->kp )); $policy = (new Uri($url))->getQuery(); - $this->assertRegExp('/Policy=[0-9a-zA-Z-_~]+/', $policy); + $this->assertMatchesRegularExpression('/Policy=[0-9a-zA-Z-_~]+/', $policy); } public function testCreatesUrlSignersForRtmp() @@ -108,47 +107,42 @@ public function testCreatesUrlSignersForRtmp() 'region' => 'us-west-2', 'version' => 'latest' ]); - $ts = time() + 1000; - $kp = $_SERVER['CF_KEY_PAIR_ID']; - $url = $client->getSignedUrl(array( + $ts = time() + 1000; + $url = $client->getSignedUrl(array( 'url' => 'rtmp://foo.cloudfront.net/test.mp4?a=b', 'expires' => $ts, - 'private_key' => $_SERVER['CF_PRIVATE_KEY'], - 'key_pair_id' => $kp + 'private_key' => $this->key, + 'key_pair_id' => $this->kp )); $this->assertStringStartsWith("test.mp4?a=b&Expires={$ts}&Signature=", $url); - $this->assertContains("Key-Pair-Id={$kp}", $url); + $this->assertStringContainsString("Key-Pair-Id={$this->kp}", $url); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid URI scheme - */ public function testEnsuresUriSchemeIsValid() { - $s = new UrlSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid URI scheme"); + $this->expectException(\InvalidArgumentException::class); + $s = new UrlSigner('a', $this->key); $s->getSignedUrl('foo://bar.com', strtotime('+10 minutes')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid URL: bar.com - */ public function testEnsuresUriSchemeIsPresent() { - $s = new UrlSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $this->expectExceptionMessage("Invalid URL: bar.com"); + $this->expectException(\InvalidArgumentException::class); + $s = new UrlSigner('a', $this->key); $s->getSignedUrl('bar.com'); } /** * @dataProvider urlAndResourceProvider * - * @param string $url - * @param string $resource + * @param string $url + * @param string $resource */ public function testIsolatesResourceIUrls($url, $resource) { - $s = new UrlSigner('a', $_SERVER['CF_PRIVATE_KEY']); + $s = new UrlSigner('a', $this->key); $m = new \ReflectionMethod(get_class($s), 'createResource'); $m->setAccessible(true); diff --git a/tests/CloudFront/fixtures/test2.pem b/tests/CloudFront/fixtures/test2.pem new file mode 100644 index 0000000000..0bfb6e4a57 --- /dev/null +++ b/tests/CloudFront/fixtures/test2.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEAxTbyKHzrPyxD91YYgq5R87tt66oX+OjJrMQI9MGp74t/N7+V +4uCGyPc5pXDgMtPO5JNAaEfkxJUosn3/g+0i/xnl7INOLrLRTLbOSBMAZVusLhlR +2l+iXPeFNrxwPxRSoROx5T9r2/rBvSwhUsDUJREPBz2IyUdbq+893QUytIm7DYSJ +NkgJFL7bIXxzQISZmfZ6ocJ1qpKuOsiAZdUu6Eaox8jdalvSqrgKhPhQ85T3HG6L +nlnEwMJAQHauwhVBaTzOybyycfvKVQNlT+JN1JnKQvdbt9lQxYVtLhZ9CEKcY41Q +3Yqyb+1MBl49C4kppYoZ5ZllIRa8sbHGk3gxgQIDAQABAoIBAQCPrwyXOwwaJqIO +HggVjfPfY/sd6/szOkdVPC5aRI8PG89ASrFlbrhEyvqQ8sAlx/PAzRfr4hVmtFXG +Vc5HzAnnWnMN8kyP8XBUOAvqrw1my3eSzpe4Rl0A5sWDr58IFkJtYPAHWkG3L+bf +cLuGkz79EoSkfcye+QJtLg0gbp0WsspfgnRxF0xKQu7H2MWkzppXzWOehxWc6YtJ +LIlBicnAQGOIbX0tghpguYNe/HsOyM5Mh1Q7AzTj6fhISxX8l/zjE5k/d9qPjk2S +hTYKYGTY11FCF6mhnRSt5hCop/N4lS+jR1ld3rbuKUzDMsuJFGKpM+8Vdn82gP7S +SzFBExzBAoGBAOyjSfKlCjojRtQ9G7D7oc11UnwP0tF73IonVoRrYyPub153/Nlc +DMB5YLCHl8u51TtPLpLH9tK+aQKaCpLoKkGxU1IK/pCGIL9JSJzyAkhajNtg/hmh +kWUdTQ9wckb5a+0VBjDPCgx4xk3sKC9fdWcrmETDs/hpJS8qz3v91N9NAoGBANVZ +4fPREN8rYIRABM/r8sd5+bIHrmFxWTb0iumx/B2Uf1z3HNDDOwUNe/WOSbZiMlsz +wK+3OoUygDT+yGvYpF6ZpjWtpPcuyKLxYQzICnISgjsohpwWt33LjGCqDtxuvcNx +JaDrLj+vZJzMr76PD6+z4KydErcAePoMDWZrfqkFAoGAO/elZbgtP05xRJe3zMH3 +3vk8TfQ0mKGq4dfWNPiBxzlFP8toaCzLjnsz5Yh3D0mon78RLmE+S2m1ctNWmqP7 +EWq+kqv2lulmoxMPM7agnXVU/MM3oYcwMU+bl64HR7UthIcvam8NPNveZSDTji3C +ssJ5c/OkR+9dXPacXe+VYoECgYEAuqxAVVKxznJnqo9RJpOuAvcokKrD2yKQCtOA +z+UZUNBjd/YHUmnftBYORdZPjLLymHX5vEU3gN+k6bmbpzEQ8GzDzue2FUjr6BYG +8mX9Lb4gEJ7u2JfPyNNWaiWhhyGmC+FuKRRdjP9rqv41LyiBcxySErYEb/aL40y0 +VM7tLfkCgYEArKYfLKzkJmicUQ7xzRIEM66DEynUEwH5VeTzHBO3Eszgj5w9C7rj +e+dGdUEJ6ie5J6QVLfT7oUCCuKF7Mrhvho8NLeObtzt2URRxQmQQfWH1TSzaarc0 +GQi4IIkGDLJeTow+7N2RB29zNDW6edh7vkoEJwvqIuC4bj4/wsEdfCI= +-----END RSA PRIVATE KEY----- diff --git a/tests/CloudSearchDomain/CloudSearchDomainTest.php b/tests/CloudSearchDomain/CloudSearchDomainTest.php index 9b06f948da..91beb6b851 100644 --- a/tests/CloudSearchDomain/CloudSearchDomainTest.php +++ b/tests/CloudSearchDomain/CloudSearchDomainTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\CloudSearchDomain; use Aws\CloudSearchDomain\CloudSearchDomainClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; @@ -10,11 +11,11 @@ */ class CloudSearchDomainTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - */ + use PHPUnitCompatTrait; + public function testRequiresEndpoint() { + $this->expectException(\InvalidArgumentException::class); new CloudSearchDomainClient([ 'service' => 'cloudsearchdomain', 'version' => 'latest' diff --git a/tests/CloudTrail/LogFileIteratorTest.php b/tests/CloudTrail/LogFileIteratorTest.php index 7faa9f0422..6941e85062 100644 --- a/tests/CloudTrail/LogFileIteratorTest.php +++ b/tests/CloudTrail/LogFileIteratorTest.php @@ -6,6 +6,7 @@ use Aws\CloudTrail\LogFileIterator; use Aws\Result; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; @@ -15,6 +16,7 @@ */ class LogFileIteratorTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testFactoryCanCreateForTrail() @@ -31,11 +33,9 @@ public function testFactoryCanCreateForTrail() $this->assertInstanceOf('Aws\CloudTrail\LogFileIterator', $files); } - /** - * @expectedException \InvalidArgumentException - */ public function testFactoryErrorsOnUnknownBucket() { + $this->expectException(\InvalidArgumentException::class); $s3Client = $this->getMockS3Client(); $cloudTrailClient = CloudTrailClient::factory([ 'credentials' => ['key' => 'foo', 'secret' => 'bar'], @@ -65,11 +65,9 @@ public function testConstructorWorksWithDates() $this->assertInstanceOf('Aws\CloudTrail\LogFileIterator', $files); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorErrorsOnInvalidDate() { + $this->expectException(\InvalidArgumentException::class); $s3Client = $this->getMockS3Client(); new LogFileIterator($s3Client, 'test-bucket', [ LogFileIterator::START_DATE => true, diff --git a/tests/CognitoIdentity/CognitoIdentityProviderTest.php b/tests/CognitoIdentity/CognitoIdentityProviderTest.php index 05114a61c2..7f1125c328 100644 --- a/tests/CognitoIdentity/CognitoIdentityProviderTest.php +++ b/tests/CognitoIdentity/CognitoIdentityProviderTest.php @@ -5,10 +5,13 @@ use Aws\CognitoIdentity\CognitoIdentityProvider; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class CognitoIdentityProviderTest extends TestCase { + use PHPUnitCompatTrait; + public function testCreatesFromCognitoIdentity() { $options = [ diff --git a/tests/CognitoSync/CognitoSyncClientTest.php b/tests/CognitoSync/CognitoSyncClientTest.php index 922443d641..94a2c6d421 100644 --- a/tests/CognitoSync/CognitoSyncClientTest.php +++ b/tests/CognitoSync/CognitoSyncClientTest.php @@ -1,6 +1,7 @@ assertContains( + $this->assertStringContainsString( urlencode($unencodedString), (string) $request->getUri() ); diff --git a/tests/CommandPoolTest.php b/tests/CommandPoolTest.php index 7b022f6921..97b0884280 100644 --- a/tests/CommandPoolTest.php +++ b/tests/CommandPoolTest.php @@ -5,6 +5,7 @@ use Aws\CommandPool; use Aws\Exception\AwsException; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,26 +13,23 @@ */ class CommandPoolTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Each value yielded by the iterator must be an Aws\CommandInterface - */ public function testEnsuresEachIsCommand() { + $this->expectExceptionMessage("Each value yielded by the iterator must be an Aws\CommandInterface"); + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); $iter = ['a']; $pool = new CommandPool($client, $iter); $pool->promise()->wait(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage before must be callable - */ public function testEnsuresBeforeIsCallable() { + $this->expectExceptionMessage("before must be callable"); + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); new CommandPool($client, [], ['before' => 'foo']); } diff --git a/tests/Credentials/AssumeRoleCredentialProviderTest.php b/tests/Credentials/AssumeRoleCredentialProviderTest.php index f70f79646e..2b4e614449 100644 --- a/tests/Credentials/AssumeRoleCredentialProviderTest.php +++ b/tests/Credentials/AssumeRoleCredentialProviderTest.php @@ -7,6 +7,7 @@ use Aws\Result; use Aws\Sts\StsClient; use Aws\Api\DateTimeResult; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\RejectedPromise; use Aws\Test\UsesServiceTrait; @@ -19,17 +20,18 @@ class AssumeRoleCredentialProviderTest extends TestCase { const SAMPLE_ROLE_ARN = 'arn:aws:iam::012345678910:role/role_name'; + use PHPUnitCompatTrait; use UsesServiceTrait; /** * @dataProvider insufficientArguments * * @param array $config - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required 'AssumeRoleCredentialProvider' configuration option: */ public function testEnsureSourceProfileProvidedForAssumeRole($config) { + $this->expectExceptionMessage("Missing required 'AssumeRoleCredentialProvider' configuration option:"); + $this->expectException(\InvalidArgumentException::class); new AssumeRoleCredentialProvider($config); } @@ -90,16 +92,14 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('bar', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error in retrieving assume role credentials. - */ public function testThrowsExceptionWhenRetrievingAssumeRoleCredentialFails() { + $this->expectExceptionMessage("Error in retrieving assume role credentials."); + $this->expectException(\Aws\Exception\CredentialsException::class); $sts = new StsClient([ 'region' => 'us-west-2', 'version' => 'latest', diff --git a/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php b/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php index 3c300c2fbe..583cc9d911 100644 --- a/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php +++ b/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php @@ -9,6 +9,7 @@ use Aws\Sts\StsClient; use Aws\Sts\Exception\StsException; use Aws\Api\DateTimeResult; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\RejectedPromise; use Aws\Test\UsesServiceTrait; @@ -21,6 +22,7 @@ class AssumeRoleWithWebIdentityCredentialProviderTest extends TestCase { const SAMPLE_ROLE_ARN = 'arn:aws:iam::012345678910:role/role_name'; + use PHPUnitCompatTrait; use UsesServiceTrait; private function clearEnv() @@ -35,36 +37,30 @@ private function clearEnv() return $dir; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option: - */ public function testEnsureRoleArnProvidedForAssumeRole() { + $this->expectExceptionMessage("Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option:"); + $this->expectException(\InvalidArgumentException::class); $config = [ 'WebIdentityTokenFile' => '/path/to/token/file', ]; new AssumeRoleWithWebIdentityCredentialProvider($config); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option: - */ public function testEnsureWebIdentityTokenFileProvidedForAssumeRole() { + $this->expectExceptionMessage("Missing required 'AssumeRoleWithWebIdentityCredentialProvider' configuration option:"); + $this->expectException(\InvalidArgumentException::class); $config = [ 'RoleArn' => self::SAMPLE_ROLE_ARN, ]; new AssumeRoleWithWebIdentityCredentialProvider($config); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage 'WebIdentityTokenFile' must be an absolute path. - */ public function testEnsureWebIdentityTokenFileIsAbsolutePath() { + $this->expectExceptionMessage("'WebIdentityTokenFile' must be an absolute path."); + $this->expectException(\InvalidArgumentException::class); $config = [ 'RoleArn' => self::SAMPLE_ROLE_ARN, 'WebIdentityTokenFile' => '..\foo\path' @@ -106,7 +102,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('bar', $creds->getSecretKey()); $this->assertSame('baz', $creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Error $e) { throw $e; @@ -133,7 +129,7 @@ public function testSetsSessionNameWhenNotProvided() $sts = $this->getTestClient('Sts', ['credentials' => false]); $sts->getHandlerList()->setHandler( function ($c, $r) use ($result) { - $this->assertContains('aws-sdk-php-', $c->toArray()['RoleSessionName']); + $this->assertStringContainsString('aws-sdk-php-', $c->toArray()['RoleSessionName']); return Promise\Create::promiseFor(new Result($result)); } ); @@ -146,12 +142,10 @@ function ($c, $r) use ($result) { unlink($tokenPath); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error reading WebIdentityTokenFile - */ public function testThrowsExceptionWhenReadingTokenFileFails() { + $this->expectExceptionMessage("Error reading WebIdentityTokenFile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $args['RoleArn'] = self::SAMPLE_ROLE_ARN; $args['WebIdentityTokenFile'] = '/foo'; $provider = new AssumeRoleWithWebIdentityCredentialProvider($args); @@ -172,18 +166,16 @@ public function testThrowsExceptionWhenEmptyTokenFile() $this->fail("Should have thrown an exception"); } catch (\Exception $e) { self::assertInstanceOf('\Aws\Exception\CredentialsException', $e); - self::assertContains('Error reading WebIdentityTokenFile', $e->getMessage()); + self::assertStringContainsString('Error reading WebIdentityTokenFile', $e->getMessage()); } finally { unlink($tokenPath); } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error assuming role from web identity credentials - */ public function testThrowsExceptionWhenRetrievingAssumeRoleCredentialFails() { + $this->expectExceptionMessage("Error assuming role from web identity credentials"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $sts = new StsClient([ 'region' => 'us-west-2', @@ -216,12 +208,10 @@ public function testThrowsExceptionWhenRetrievingAssumeRoleCredentialFails() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving web identity credentials: Found 1 error while validating the input provided for the AssumeRoleWithWebIdentity operation: - */ public function testThrowsNonAwsExceptionWhenRetrievingAssumeRoleCredentialFails() { + $this->expectExceptionMessage("Error retrieving web identity credentials: Found 1 error while validating the input provided for the AssumeRoleWithWebIdentity operation:"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $sts = new StsClient([ 'region' => 'us-west-2', @@ -294,7 +284,7 @@ public function testRetryInvalidIdentityToken() $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('bar', $creds->getSecretKey()); $this->assertSame('baz', $creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -303,12 +293,10 @@ public function testRetryInvalidIdentityToken() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage InvalidIdentityToken, retries exhausted - */ public function testThrowsExceptionWhenInvalidIdentityTokenRetriesExhausted() { + $this->expectExceptionMessage("InvalidIdentityToken, retries exhausted"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $result = [ 'Credentials' => [ @@ -353,12 +341,10 @@ public function testThrowsExceptionWhenInvalidIdentityTokenRetriesExhausted() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage InvalidIdentityToken, retries exhausted - */ public function testCanDisableInvalidIdentityTokenRetries() { + $this->expectExceptionMessage("InvalidIdentityToken, retries exhausted"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $result = [ 'Credentials' => [ diff --git a/tests/Credentials/CredentialProviderTest.php b/tests/Credentials/CredentialProviderTest.php index d6ce7adbe8..31f0e2e7ee 100644 --- a/tests/Credentials/CredentialProviderTest.php +++ b/tests/Credentials/CredentialProviderTest.php @@ -9,6 +9,7 @@ use Aws\Middleware; use Aws\Result; use Aws\Sts\StsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -28,6 +29,7 @@ class CredentialProviderTest extends TestCase aws_session_token = baz EOT; + use PHPUnitCompatTrait; use UsesServiceTrait; private function clearEnv() @@ -65,7 +67,7 @@ private function clearEnv() return $dir; } - public function setUp() + public function _setUp() { $this->home = getenv('HOME'); $this->homedrive = getenv('HOMEDRIVE'); @@ -75,7 +77,7 @@ public function setUp() $this->profile = getenv(CredentialProvider::ENV_PROFILE); } - public function tearDown() + public function _tearDown() { putenv('HOME=' . $this->home); putenv('HOMEDRIVE=' . $this->homedrive); @@ -264,12 +266,10 @@ public function testUsesIniWithUseAwsConfigFileTrue() unlink($dir . '/credentials'); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credentials from the instance profile metadata service - */ public function testIgnoresIniWithUseAwsConfigFileFalse() { + $this->expectExceptionMessage("Error retrieving credentials from the instance profile metadata service"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/credentials', self::$standardIni); $expectedCreds = [ @@ -287,12 +287,10 @@ public function testIgnoresIniWithUseAwsConfigFileFalse() unlink($dir . '/credentials'); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Invalid credentials file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid credentials file:"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/credentials', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -305,21 +303,17 @@ public function testEnsuresIniFileIsValid() } } - /** - * @expectedException \Aws\Exception\CredentialsException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Exception\CredentialsException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(CredentialProvider::ini())->wait(); } - /** - * @expectedException \Aws\Exception\CredentialsException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = "[default]\naws_access_key_id = foo\n" . "aws_secret_access_key = baz\n[foo]"; @@ -334,12 +328,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/credentials', ''); putenv('HOME=' . dirname($dir)); @@ -484,12 +476,10 @@ public function testCreatesTemporaryFromProcessCredential() $this->assertSame($expires, $creds->getExpiration()); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage No credential_process present in INI profile - */ public function testEnsuresProcessCredentialIsPresent() { + $this->expectExceptionMessage("No credential_process present in INI profile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("credential_process does not return Version == 1"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("credential_process returned expired credentials"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("credential_process returned invalid expiration"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<wait(); $body = (string) $history->getLastRequest()->getBody(); - $this->assertContains('RoleSessionName=foobar', $body); + $this->assertStringContainsString('RoleSessionName=foobar', $body); $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -645,12 +629,10 @@ public function testCreatesFromRoleArn() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Circular source_profile reference found. - */ public function testCreatesFromRoleArnCatchesCircular() { + $this->expectExceptionMessage("Circular source_profile reference found."); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<getLastRequest(); $body = (string) $history->getLastRequest()->getBody(); - $this->assertRegExp('/RoleSessionName=aws-sdk-php-\d{13}/', $body); + $this->assertMatchesRegularExpression('/RoleSessionName=aws-sdk-php-\d{13}/', $body); } catch (\Exception $e) { throw $e; } finally { @@ -727,12 +709,10 @@ public function testSetsRoleSessionNameToDefault() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Role assumption profiles are disabled. Failed to load profile assume - */ public function testEnsuresAssumeRoleCanBeDisabled() { + $this->expectExceptionMessage("Role assumption profiles are disabled. Failed to load profile assume"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("Either source_profile or credential_source must be set using profile assume, but not both"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("A role_arn must be provided with credential_source in"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv(CredentialProvider::ENV_KEY . '=abc'); putenv(CredentialProvider::ENV_SESSION . ''); @@ -819,12 +795,10 @@ public function testAssumeRoleInConfigFromCredentialSourceNoRoleArn() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Could not find environment variable credentials in AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY - */ public function testAssumeRoleInConfigFromFailingCredentialsSource() { + $this->expectExceptionMessage("Could not find environment variable credentials in AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv(CredentialProvider::ENV_KEY . '=abc'); putenv(CredentialProvider::ENV_SESSION . ''); @@ -883,12 +857,10 @@ public function testAssumeRoleInConfigFromCredentialsSourceEnvironment() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credentials from the instance profile metadata service - */ public function testAssumeRoleInConfigFromCredentialsSourceEc2InstanceMetadata() { + $this->expectExceptionMessage("Error retrieving credentials from the instance profile metadata service"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $credentials = <<expectExceptionMessage("Error retrieving credential from ECS"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $credentials = <<expectExceptionMessage("Invalid credential_source found in config file: InvalidSource. Valid inputs include Environment, Ec2InstanceMetadata, and EcsContainer."); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $credentials = <<expectExceptionMessage("Either source_profile or credential_source must be set using profile assume, but not both"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("source_profile default using profile assume does not exist"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("No credentials present in INI profile 'default'"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("must contain an access token and an expiration"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("Profile nonExistingProfile does not exist in"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<expectExceptionMessage("Cannot read credentials from"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $filename = $dir . '/config'; @@ -1319,12 +1275,10 @@ public function testSsoProfileProviderBadFile() } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage must contain the following keys: sso_start_url, sso_region, sso_account_id, and sso_role_name - */ public function testSsoProfileProviderMissingData() { + $this->expectExceptionMessage("must contain the following keys: sso_start_url, sso_region, sso_account_id, and sso_role_name"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); $ini = <<assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1436,7 +1390,7 @@ public function testAssumeRoleInCredentialsFromSourceInConfig() $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1486,7 +1440,7 @@ public function testAssumeRoleInConfigFromSourceInCredentials() $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1540,7 +1494,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1592,7 +1546,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1644,7 +1598,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1696,7 +1650,7 @@ function ($c, $r) use ($result) { $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('assumedSecret', $creds->getSecretKey()); $this->assertNull($creds->getSecurityToken()); - $this->assertInternalType('int', $creds->getExpiration()); + $this->assertIsInt($creds->getExpiration()); $this->assertFalse($creds->isExpired()); } catch (\Exception $e) { throw $e; @@ -1706,12 +1660,10 @@ function ($c, $r) use ($result) { } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unknown profile: fooProfile - */ public function testEnsuresAssumeRoleWebIdentityProfileIsPresent() { + $this->expectExceptionMessage("Unknown profile: fooProfile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv('AWS_PROFILE=fooProfile'); @@ -1733,12 +1685,10 @@ public function testEnsuresAssumeRoleWebIdentityProfileIsPresent() } } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unknown profile: fooProfile - */ public function testEnsuresAssumeRoleWebIdentityProfileInDefaultFiles() { + $this->expectExceptionMessage("Unknown profile: fooProfile"); + $this->expectException(\Aws\Exception\CredentialsException::class); $dir = $this->clearEnv(); putenv('AWS_PROFILE=fooProfile'); touch($dir . '/credentials'); diff --git a/tests/Credentials/EcsCredentialProviderTest.php b/tests/Credentials/EcsCredentialProviderTest.php index d761baf9aa..56d9df6390 100644 --- a/tests/Credentials/EcsCredentialProviderTest.php +++ b/tests/Credentials/EcsCredentialProviderTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Credentials; use Aws\Credentials\EcsCredentialProvider; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\ClientInterface; use GuzzleHttp\Client; use GuzzleHttp\Promise; @@ -15,6 +16,8 @@ */ class EcsCredentialProviderTest extends TestCase { + use PHPUnitCompatTrait; + private $uripath; private function clearEnv() @@ -29,26 +32,24 @@ private function clearEnv() unset($_SERVER[EcsCredentialProvider::ENV_AUTH_TOKEN]); } - public function setUp() + public function _setUp() { $this->uripath = getenv(EcsCredentialProvider::ENV_URI); $this->fulluripath = getenv(EcsCredentialProvider::ENV_FULL_URI); $this->authtokenpath = getenv(EcsCredentialProvider::ENV_AUTH_TOKEN); } - public function tearDown() + public function _tearDown() { $this->uripath = getenv(EcsCredentialProvider::ENV_URI); $this->fulluripath = getenv(EcsCredentialProvider::ENV_FULL_URI); $this->authtokenpath = getenv(EcsCredentialProvider::ENV_AUTH_TOKEN); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credential from ECS - */ public function testRejectsIfUriPathIsNotAvailable() { + $this->expectExceptionMessage("Error retrieving credential from ECS"); + $this->expectException(\Aws\Exception\CredentialsException::class); $client = function () use (&$responses) { return Promise\Create::rejectionFor([ 'exception' => new \Exception('error') @@ -58,12 +59,10 @@ public function testRejectsIfUriPathIsNotAvailable() $p()->wait(); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unexpected ECS credential value - */ public function testThrowsExceptionOnInvalidEcsCredential() { + $this->expectExceptionMessage("Unexpected ECS credential value"); + $this->expectException(\Aws\Exception\CredentialsException::class); $this->getTestCreds( $this->getCredentialArray(null, null, null, null, false) )->wait(); @@ -81,6 +80,7 @@ public function testLoadsCredentialsAndProfile() $this->assertSame($t, $c->getExpiration()); } + /** @doesNotPerformAssertions */ public function testDoesNotRequireConfig() { new EcsCredentialProvider(); diff --git a/tests/Credentials/InstanceProfileProviderTest.php b/tests/Credentials/InstanceProfileProviderTest.php index 7711d9cf90..27f7fed545 100644 --- a/tests/Credentials/InstanceProfileProviderTest.php +++ b/tests/Credentials/InstanceProfileProviderTest.php @@ -9,6 +9,7 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\Sdk; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Promise; use GuzzleHttp\Psr7; @@ -22,15 +23,17 @@ */ class InstanceProfileProviderTest extends TestCase { + use PHPUnitCompatTrait; + static $originalFlag; - public static function setUpBeforeClass() + public static function _setUpBeforeClass() { self::$originalFlag = getenv(InstanceProfileProvider::ENV_DISABLE) ?: ''; putenv(InstanceProfileProvider::ENV_DISABLE. '=false'); } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(InstanceProfileProvider::ENV_DISABLE. '=' . self::$originalFlag); } @@ -178,7 +181,7 @@ private function getSecureTestClient( Psr7\Utils::streamFor( json_encode(call_user_func_array( [$this, 'getCredentialArray'], - $creds + array_values($creds) )) ) ) @@ -797,12 +800,10 @@ public function failureTestCases() ]; } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Error retrieving credentials from the instance profile metadata service. (999 Expected Exception) - */ 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(); $getRequest = new $requestClass('GET', '/latest/meta-data/foo'); @@ -899,23 +900,23 @@ public function testSeedsInitialCredentials() $this->assertSame($t, $c->getExpiration()); } - /** - * @expectedException \Aws\Exception\CredentialsException - * @expectedExceptionMessage Unexpected instance profile response - */ public function testThrowsExceptionOnInvalidMetadata() { + $this->expectExceptionMessage("Unexpected instance profile response"); + $this->expectException(\Aws\Exception\CredentialsException::class); $this->getTestCreds( $this->getCredentialArray(null, null, null, null, false), 'foo' )->wait(); } + /** @doesNotPerformAssertions */ public function testDoesNotRequireConfig() { new InstanceProfileProvider(); } + /** @doesNotPerformAssertions */ public function testEnvDisableFlag() { $flag = getenv(InstanceProfileProvider::ENV_DISABLE); diff --git a/tests/Crypto/AesDecryptingStreamTest.php b/tests/Crypto/AesDecryptingStreamTest.php index 382b24deb8..b713c2488b 100644 --- a/tests/Crypto/AesDecryptingStreamTest.php +++ b/tests/Crypto/AesDecryptingStreamTest.php @@ -4,6 +4,7 @@ use Aws\Crypto\AesDecryptingStream; use Aws\Crypto\Cipher\Cbc; use Aws\Crypto\Cipher\CipherMethod; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ class AesDecryptingStreamTest extends TestCase const KB = 1024; const MB = 1048576; + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** @@ -142,11 +144,9 @@ public function testIsNotWritable() $this->assertFalse($stream->isWritable()); } - /** - * @expectedException \LogicException - */ public function testDoesNotSupportArbitrarySeeking() { + $this->expectException(\LogicException::class); $stream = new AesDecryptingStream( new RandomByteStream(124 * self::MB), 'foo', diff --git a/tests/Crypto/AesEncryptingStreamTest.php b/tests/Crypto/AesEncryptingStreamTest.php index 3001c2c8c7..ecf406c745 100644 --- a/tests/Crypto/AesEncryptingStreamTest.php +++ b/tests/Crypto/AesEncryptingStreamTest.php @@ -5,6 +5,7 @@ use Aws\Crypto\AesEncryptingStream; use Aws\Crypto\Cipher\Cbc; use Aws\Crypto\Cipher\CipherMethod; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; @@ -14,6 +15,7 @@ class AesEncryptingStreamTest extends TestCase const KB = 1024; const MB = 1048576; + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** @@ -172,11 +174,10 @@ public function testReturnsPaddedOrEmptyStringWhenSourceStreamEmpty( * @dataProvider cipherMethodProvider * * @param CipherMethod $cipherMethod - * - * @expectedException \LogicException */ public function testDoesNotSupportSeekingFromEnd(CipherMethod $cipherMethod) { + $this->expectException(\LogicException::class); $stream = new AesEncryptingStream(Psr7\Utils::streamFor('foo'), 'foo', $cipherMethod); $stream->seek(1, SEEK_END); diff --git a/tests/Crypto/AesGcmDecryptingStreamTest.php b/tests/Crypto/AesGcmDecryptingStreamTest.php index eaa9199281..11b1bbdead 100644 --- a/tests/Crypto/AesGcmDecryptingStreamTest.php +++ b/tests/Crypto/AesGcmDecryptingStreamTest.php @@ -2,12 +2,14 @@ namespace Aws\Test\Crypto; use Aws\Crypto\AesGcmDecryptingStream; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; class AesGcmDecryptingStreamTest extends TestCase { + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** @@ -61,8 +63,6 @@ public function testStreamOutputSameAsOpenSSL( /** * @dataProvider cartesianJoinInputKeySizeProvider - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object could not be decrypted due to an invalid authentication tag * * @param StreamInterface $plainText * @param int $keySize @@ -71,6 +71,8 @@ public function testThrowsForInvalidTag( StreamInterface $plainText, $keySize ) { + $this->expectExceptionMessage("The requested object could not be decrypted due to an invalid authentication tag"); + $this->expectException(\Aws\Exception\CryptoException::class); if (version_compare(PHP_VERSION, '7.1', '<')) { $this->markTestSkipped( 'AES-GCM decryption is only supported in PHP 7.1 or greater' diff --git a/tests/Crypto/AesGcmEncryptingStreamTest.php b/tests/Crypto/AesGcmEncryptingStreamTest.php index eefe3a8a93..0a03fa1ecd 100644 --- a/tests/Crypto/AesGcmEncryptingStreamTest.php +++ b/tests/Crypto/AesGcmEncryptingStreamTest.php @@ -2,15 +2,17 @@ namespace Aws\Test\Crypto; use Aws\Crypto\AesGcmEncryptingStream; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; class AesGcmEncryptingStreamTest extends TestCase { + use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; - protected function setUp() + protected function _setUp() { if (version_compare(PHP_VERSION, '7.1', '<')) { $this->markTestSkipped( diff --git a/tests/Crypto/Cipher/CbcTest.php b/tests/Crypto/Cipher/CbcTest.php index c9786d87e6..79d252c763 100644 --- a/tests/Crypto/Cipher/CbcTest.php +++ b/tests/Crypto/Cipher/CbcTest.php @@ -2,10 +2,13 @@ namespace Aws\Test\Crypto\Cipher; use Aws\Crypto\Cipher\Cbc; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class CbcTest extends TestCase { + use PHPUnitCompatTrait; + public function testShouldReportCipherMethodOfCBC() { $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); @@ -35,11 +38,9 @@ public function testUpdateShouldSetCurrentIvToEndOfCipherBlock() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testShouldThrowWhenIvOfInvalidLengthProvided() { + $this->expectException(\InvalidArgumentException::class); new Cbc(openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc') + 1)); } @@ -54,11 +55,9 @@ public function testShouldSupportSeekingToBeginning() $this->assertSame($ivString, $iv->getCurrentIv()); } - /** - * @expectedException \LogicException - */ public function testShouldThrowWhenNonZeroOffsetProvidedToSeek() { + $this->expectException(\LogicException::class); $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $iv = new Cbc($ivString); $cipherTextBlock = openssl_random_pseudo_bytes(1024); @@ -67,11 +66,9 @@ public function testShouldThrowWhenNonZeroOffsetProvidedToSeek() $iv->seek(1); } - /** - * @expectedException \LogicException - */ public function testShouldThrowWhenSeekCurProvidedToSeek() { + $this->expectException(\LogicException::class); $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $iv = new Cbc($ivString); $cipherTextBlock = openssl_random_pseudo_bytes(1024); @@ -80,11 +77,9 @@ public function testShouldThrowWhenSeekCurProvidedToSeek() $iv->seek(0, SEEK_CUR); } - /** - * @expectedException \LogicException - */ public function testShouldThrowWhenSeekEndProvidedToSeek() { + $this->expectException(\LogicException::class); $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $iv = new Cbc($ivString); $cipherTextBlock = openssl_random_pseudo_bytes(1024); diff --git a/tests/Crypto/KmsMaterialsProviderV2Test.php b/tests/Crypto/KmsMaterialsProviderV2Test.php index 4dad52c9d1..4c8c90bf60 100644 --- a/tests/Crypto/KmsMaterialsProviderV2Test.php +++ b/tests/Crypto/KmsMaterialsProviderV2Test.php @@ -5,6 +5,7 @@ use Aws\Kms\KmsClient; use Aws\Middleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ */ class KmsMaterialsProviderV2Test extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testProviderBasics() @@ -83,12 +85,10 @@ public function testGeneratesCek() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage A KMS key id is required for encryption with KMS keywrap - */ public function testGenerateThrowsForNoKmsId() { + $this->expectExceptionMessage("A KMS key id is required for encryption with KMS keywrap"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client); @@ -105,12 +105,10 @@ public function testGenerateThrowsForNoKmsId() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage '@KmsEncryptionContext' is a required argument when using KmsMaterialsProviderV2 - */ public function testGenerateThrowsForNoEncryptionContext() { + $this->expectExceptionMessage("'@KmsEncryptionContext' is a required argument when using KmsMaterialsProviderV2"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client, 'foo'); @@ -123,12 +121,10 @@ public function testGenerateThrowsForNoEncryptionContext() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage Conflict in reserved @KmsEncryptionContext key aws:x-amz-cek-alg - */ public function testGenerateThrowsForContextConflict() { + $this->expectExceptionMessage("Conflict in reserved @KmsEncryptionContext key aws:x-amz-cek-alg"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client, 'foo'); @@ -182,12 +178,10 @@ public function testDecryptCek() ); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage KMS CMK ID was not specified and the operation is not opted-in to attempting to use any valid CMK - */ public function testDecryptCekThrowsForNoKmsId() { + $this->expectExceptionMessage("KMS CMK ID was not specified and the operation is not opted-in to attempting to use any valid CMK"); + $this->expectException(\Aws\Exception\CryptoException::class); /** @var KmsClient $client */ $client = $this->getTestClient('Kms', []); $provider = new KmsMaterialsProviderV2($client); diff --git a/tests/Crypto/MetadataEnvelopeTest.php b/tests/Crypto/MetadataEnvelopeTest.php index eb19d45af7..95d1c5127d 100644 --- a/tests/Crypto/MetadataEnvelopeTest.php +++ b/tests/Crypto/MetadataEnvelopeTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Crypto; use Aws\Crypto\MetadataEnvelope; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,7 @@ */ class MetadataEnvelopeTest extends TestCase { + use PHPUnitCompatTrait; use UsesMetadataEnvelopeTrait; /** @@ -40,11 +42,10 @@ public function testSetsAllFields($allValidFields) /** * @dataProvider getIndividualInvalidMetadataFields - * - * @expectedException \InvalidArgumentException */ public function testThrowsOnInvalidMetadataField($field, $value) { + $this->expectException(\InvalidArgumentException::class); $envelope = new MetadataEnvelope(); $envelope[$field] = $value; } diff --git a/tests/Crypto/Polyfill/KeyTest.php b/tests/Crypto/Polyfill/KeyTest.php index 74afd1e5e5..b05424804c 100644 --- a/tests/Crypto/Polyfill/KeyTest.php +++ b/tests/Crypto/Polyfill/KeyTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Crypto\Polyfill; use Aws\Crypto\Polyfill\Key; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class KeyTest extends TestCase { + use PHPUnitCompatTrait; + public function testConstructor() { $this->assertInstanceOf(Key::class, new Key('test')); @@ -26,7 +29,7 @@ public function testDebugInfo() ob_start(); var_dump($key); $output = ob_get_clean(); - $this->assertNotContains($test, $output, 'debugInfo() did not suppress output'); + $this->assertStringNotContainsString($test, $output, 'debugInfo() did not suppress output'); } public function testReturnTypeValue() @@ -34,7 +37,7 @@ public function testReturnTypeValue() $test = 'some unique test string'; $key = new Key($test); - $this->assertInternalType('string', $key->get()); + $this->assertIsString($key->get()); $this->assertSame($test, $key->get()); } } diff --git a/tests/DocDb/DocDbClientTest.php b/tests/DocDb/DocDbClientTest.php index 161b46b0b2..cb43941b43 100644 --- a/tests/DocDb/DocDbClientTest.php +++ b/tests/DocDb/DocDbClientTest.php @@ -5,6 +5,7 @@ use Aws\Credentials\Credentials; use Aws\DocDB\DocDBClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -14,13 +15,15 @@ */ class DocDbClientTestClientTest extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; @@ -67,7 +70,7 @@ public function testCorrectPresignDocDbUrls( if (!empty($expectedUrl)) { self::assertSame($expectedUrl, $url); } else if (!empty($expectedSignature)) { - $this->assertContains("X-Amz-Signature={$expectedSignature}", $url); + $this->assertStringContainsString("X-Amz-Signature={$expectedSignature}", $url); } else { self::assertNull($url); } diff --git a/tests/DynamoDb/DynamoDbClientTest.php b/tests/DynamoDb/DynamoDbClientTest.php index df731e5b20..1a24aa489c 100644 --- a/tests/DynamoDb/DynamoDbClientTest.php +++ b/tests/DynamoDb/DynamoDbClientTest.php @@ -7,6 +7,7 @@ use Aws\Exception\AwsException; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Response; @@ -18,6 +19,7 @@ */ class DynamoDbClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testRegisterSessionHandlerReturnsHandler() diff --git a/tests/DynamoDb/MarshalerTest.php b/tests/DynamoDb/MarshalerTest.php index ebdef3ff82..8dcf6ac3a9 100644 --- a/tests/DynamoDb/MarshalerTest.php +++ b/tests/DynamoDb/MarshalerTest.php @@ -5,6 +5,7 @@ use Aws\DynamoDb\BinaryValue; use Aws\DynamoDb\NumberValue; use Aws\DynamoDb\SetValue; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -13,6 +14,8 @@ */ class MarshalerTest extends TestCase { + use PHPUnitCompatTrait; + const ERROR = 'ERROR'; /** @@ -233,11 +236,9 @@ public function testMarshalingJsonAndItems() $this->assertEquals($expected, $m->marshalItem($array)); } - /** - * @expectedException \InvalidArgumentException - */ public function testErrorIfMarshalingBadJsonDoc() { + $this->expectException(\InvalidArgumentException::class); (new Marshaler)->marshalJson('foo'); } @@ -297,11 +298,9 @@ public function testCanUnmarshalToObjectFormat() $this->assertSame('b', $result->a); } - /** - * @expectedException \UnexpectedValueException - */ public function testErrorIfUnmarshalingUnknownType() { + $this->expectException(\UnexpectedValueException::class); $m = new Marshaler; $m->unmarshalValue(['BOMB' => 'BOOM']); } diff --git a/tests/DynamoDb/SessionHandlerTest.php b/tests/DynamoDb/SessionHandlerTest.php index e81ea5a23b..0041a0d806 100644 --- a/tests/DynamoDb/SessionHandlerTest.php +++ b/tests/DynamoDb/SessionHandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\DynamoDb; use Aws\DynamoDb\SessionHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -10,6 +11,7 @@ */ class SessionHandlerTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testCanCreateSessionHandler() diff --git a/tests/DynamoDb/StandardSessionConnectionTest.php b/tests/DynamoDb/StandardSessionConnectionTest.php index 37c75ce0d0..9d2b659408 100644 --- a/tests/DynamoDb/StandardSessionConnectionTest.php +++ b/tests/DynamoDb/StandardSessionConnectionTest.php @@ -5,6 +5,7 @@ use Aws\DynamoDb\StandardSessionConnection; use Aws\Middleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ */ class StandardSessionConnectionTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testStandardConfig() @@ -154,11 +156,9 @@ public function testWriteReturnsFalseOnFailure() $this->assertFalse($return); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testWriteTriggersWarningOnFailure() { + $this->expectWarning(); $client = $this->getTestSdk()->createDynamoDb(); $this->addMockResults($client, [ $this->createMockAwsException('ERROR', 'Aws\DynamoDb\Exception\DynamoDbException') @@ -190,11 +190,9 @@ public function testDeleteReturnsBoolBasedOnSuccess() $this->assertFalse($return); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testDeleteTriggersWarningOnFailure() { + $this->expectWarning(); $client = $this->getTestSdk()->createDynamoDb(); $this->addMockResults($client, [ new Result([]), diff --git a/tests/DynamoDb/WriteRequestBatchTest.php b/tests/DynamoDb/WriteRequestBatchTest.php index e71498a7c2..7d4db5c6d9 100644 --- a/tests/DynamoDb/WriteRequestBatchTest.php +++ b/tests/DynamoDb/WriteRequestBatchTest.php @@ -6,6 +6,7 @@ use Aws\MockHandler; use Aws\Result; use Aws\DynamoDb\WriteRequestBatch; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -14,6 +15,7 @@ */ class WriteRequestBatchTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testInstantiateWriteRequestBatch() @@ -25,10 +27,10 @@ public function testInstantiateWriteRequestBatch() /** * @dataProvider getInvalidArgUseCases - * @expectedException \InvalidArgumentException */ public function testInstantiationFailsOnInvalidArgs($config) { + $this->expectException(\InvalidArgumentException::class); new WriteRequestBatch($this->getTestClient('DynamoDb'), $config); } @@ -65,11 +67,9 @@ public function testAddItems() ); } - /** - * @expectedException \RuntimeException - */ public function testMustProvideTable() { + $this->expectException(\RuntimeException::class); $batch = new WriteRequestBatch($this->getTestClient('DynamoDb')); $batch->put(['a' => 'b']); } diff --git a/tests/Endpoint/EndpointProviderTest.php b/tests/Endpoint/EndpointProviderTest.php index 06bd5faffe..78e72aa979 100644 --- a/tests/Endpoint/EndpointProviderTest.php +++ b/tests/Endpoint/EndpointProviderTest.php @@ -3,6 +3,7 @@ use Aws\Endpoint\EndpointProvider; use Aws\Endpoint\PartitionEndpointProvider; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,19 +11,17 @@ */ class EndpointProviderTest extends TestCase { - /** - * @expectedException \Aws\Exception\UnresolvedEndpointException - */ + use PHPUnitCompatTrait; + public function testThrowsWhenUnresolved() { + $this->expectException(\Aws\Exception\UnresolvedEndpointException::class); EndpointProvider::resolve(function() {}, []); } - /** - * @expectedException \Aws\Exception\UnresolvedEndpointException - */ public function testThrowsWhenNotArray() { + $this->expectException(\Aws\Exception\UnresolvedEndpointException::class); EndpointProvider::resolve(function() { return 'foo'; }, []); } diff --git a/tests/Endpoint/PartitionTest.php b/tests/Endpoint/PartitionTest.php index 7d4b000fb6..09bb87cd52 100644 --- a/tests/Endpoint/PartitionTest.php +++ b/tests/Endpoint/PartitionTest.php @@ -5,6 +5,7 @@ use Aws\Endpoint\PartitionInterface; use Aws\Endpoint\UseDualstackEndpoint; use Aws\Endpoint\UseFipsEndpoint; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,6 +13,8 @@ */ class PartitionTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider partitionDefinitionProvider * @@ -29,12 +32,11 @@ public function testAcceptsValidDefinitions(array $definition) * @dataProvider invalidPartitionDefinitionProvider * * @param array $invalidDefinition - * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /missing required \w+ field/ */ public function testRejectsInvalidDefinitions(array $invalidDefinition) { + $this->expectExceptionMessageMatches("/missing required \w+ field/"); + $this->expectException(\InvalidArgumentException::class); new Partition($invalidDefinition); } @@ -63,7 +65,7 @@ public function testFipsEndpoint(array $definition) { $partition = new Partition($definition); $resolved = $partition(['region' => 'fips-aws-global', 'service' => 'service']); - self::assertContains('service-fips.amazonaws.com', $resolved['endpoint']); + self::assertStringContainsString('service-fips.amazonaws.com', $resolved['endpoint']); } public function partitionDefinitionProvider() diff --git a/tests/EndpointDiscovery/ConfigurationProviderTest.php b/tests/EndpointDiscovery/ConfigurationProviderTest.php index c97b757b55..ef98cdbc45 100644 --- a/tests/EndpointDiscovery/ConfigurationProviderTest.php +++ b/tests/EndpointDiscovery/ConfigurationProviderTest.php @@ -8,6 +8,7 @@ use Aws\EndpointDiscovery\ConfigurationProvider; use Aws\EndpointDiscovery\Exception\ConfigurationException; use Aws\LruArrayCache; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -16,6 +17,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENABLED) ?: '', @@ -59,7 +62,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENABLED . '=' . self::$originalEnv['enabled']); @@ -202,21 +205,17 @@ public function testCreatesWithDefaultsFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -230,12 +229,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -248,12 +245,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\EndpointDiscovery\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\EndpointDiscovery\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -323,11 +318,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -488,12 +481,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid endpoint_discovery configuration argument. - */ public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid endpoint_discovery configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/EndpointDiscovery/ConfigurationTest.php b/tests/EndpointDiscovery/ConfigurationTest.php index 4c60d1d5d8..309a651f8e 100644 --- a/tests/EndpointDiscovery/ConfigurationTest.php +++ b/tests/EndpointDiscovery/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\EndpointDiscovery; use Aws\EndpointDiscovery\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Log\InvalidArgumentException; @@ -11,6 +12,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration(true, 2000); @@ -28,11 +31,9 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException InvalidArgumentException - */ public function testHandlesInvalidCacheLimit() { + $this->expectException(\InvalidArgumentException::class); new Configuration(true, 'not_a_cache_limit'); } diff --git a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php index d3a7aa5949..1791fcc1b9 100644 --- a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php +++ b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php @@ -13,6 +13,7 @@ use Aws\Result; use Aws\ResultInterface; use Aws\Sdk; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; @@ -25,6 +26,7 @@ */ class EndpointDiscoveryMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; /** * @backupStaticAttributes enabled @@ -55,7 +57,7 @@ public function testCorrectlyModifiesRequest( } $expectedUserAgentParts = explode(' ', $expected->getHeader('User-Agent')[0]); foreach ($expectedUserAgentParts as $expectedUserAgentPart) { - $this->assertContains( + $this->assertStringContainsString( $expectedUserAgentPart, $req->getHeader('User-Agent')[0] ); @@ -751,11 +753,11 @@ public function testThrowsExceptionWhenMarkedAsEndpointOperation() /** * @backupStaticAttributes enabled - * @expectedException \Aws\Exception\UnresolvedEndpointException - * @expectedExceptionMessage This operation requires the use of endpoint discovery, but this has been disabled */ public function testThrowsExceptionForRequiredOpWhenDisabled() { + $this->expectExceptionMessage("This operation requires the use of endpoint discovery, but this has been disabled"); + $this->expectException(\Aws\Exception\UnresolvedEndpointException::class); $client = $this->generateTestClient( $this->generateTestService(), [ diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 62ad7674ba..0e8a1c1c7a 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -90,7 +90,7 @@ public function testCorrectlyOutputsHost( }); $handler = $list->resolve(); - $handler($command, new Request('POST', $endpoint)); + $handler($command, new Request('POST', $endpoint))->wait(false); } public function getTestCases() diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index 7d4c5d8ba7..fd8f2b6110 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -5,10 +5,13 @@ use Aws\MockHandler; use Aws\Result; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class FunctionsTest extends TestCase { + use PHPUnitCompatTrait; + /** * @covers Aws\recursive_dir_iterator() */ @@ -67,12 +70,11 @@ public function testCreatesConstantlyFunctions() } /** - * @expectedException \InvalidArgumentException - * * @covers Aws\load_compiled_json() */ public function testUsesJsonCompiler() { + $this->expectException(\InvalidArgumentException::class); Aws\load_compiled_json('/path/to/not/here.json'); } @@ -317,10 +319,10 @@ public function testAliasManifest() /** * @covers Aws\manifest() - * @expectedException \InvalidArgumentException */ public function testInvalidManifest() { + $this->expectException(\InvalidArgumentException::class); Aws\manifest('notarealservicename'); } diff --git a/tests/Glacier/GlacierClientTest.php b/tests/Glacier/GlacierClientTest.php index d7bbcce9c7..b1bda13762 100644 --- a/tests/Glacier/GlacierClientTest.php +++ b/tests/Glacier/GlacierClientTest.php @@ -3,6 +3,7 @@ use Aws\Exception\CouldNotCreateChecksumException; use Aws\Glacier\GlacierClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7; @@ -13,6 +14,7 @@ */ class GlacierClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testAppliesAllMiddleware() @@ -45,11 +47,9 @@ public function testAppliesAllMiddleware() $this->assertSame($hash, $request->getHeaderLine('x-amz-sha256-tree-hash')); } - /** - * @expectedException \Aws\Exception\CouldNotCreateChecksumException - */ public function testErrorWhenHashingNonSeekableStream() { + $this->expectException(\Aws\Exception\CouldNotCreateChecksumException::class); $this->getTestClient('Glacier')->uploadArchive([ 'vaultName' => 'foo', 'body' => new NoSeekStream(Psr7\Utils::streamFor('foo')), diff --git a/tests/Glacier/MultipartUploaderTest.php b/tests/Glacier/MultipartUploaderTest.php index 641b6ef81b..eb32d8aad1 100644 --- a/tests/Glacier/MultipartUploaderTest.php +++ b/tests/Glacier/MultipartUploaderTest.php @@ -18,7 +18,7 @@ class MultipartUploaderTest extends TestCase const MB = 1048576; const FILENAME = '_aws-sdk-php-glacier-mup-test-dots.txt'; - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { @unlink(sys_get_temp_dir() . '/' . self::FILENAME); } @@ -28,7 +28,7 @@ public static function tearDownAfterClass() */ public function testGlacierMultipartUploadWorkflow( array $uploadOptions = [], - StreamInterface $source, + StreamInterface $source = null, $error = false ) { $client = $this->getTestClient('glacier'); diff --git a/tests/Glacier/TreeHashTest.php b/tests/Glacier/TreeHashTest.php index f7f3bf755d..2d68d17873 100644 --- a/tests/Glacier/TreeHashTest.php +++ b/tests/Glacier/TreeHashTest.php @@ -2,10 +2,13 @@ namespace Aws\Test\Glacier; use Aws\Glacier\TreeHash; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; class TreeHashTest extends TestCase { + use PHPUnitCompatTrait; + /** * @covers Aws\Glacier\TreeHash::__construct * @covers Aws\Glacier\TreeHash::update @@ -38,11 +41,11 @@ public function testHashingIsHappeningCorrectly() } /** - * @expectedException \LogicException * @covers Aws\Glacier\TreeHash::update */ public function testCannotUpdateAfterHashCalculation() { + $this->expectException(\LogicException::class); $hash = new TreeHash('sha256'); $hash->update('foo'); $hash->complete(); @@ -51,11 +54,11 @@ public function testCannotUpdateAfterHashCalculation() } /** - * @expectedException \LogicException * @covers Aws\Glacier\TreeHash::addChecksum */ public function testCannotAddChecksumsAfterHashCalculation() { + $this->expectException(\LogicException::class); $hash = new TreeHash('sha256'); $hash->update('foo'); $hash->complete(); diff --git a/tests/Handler/GuzzleV5/HandlerTest.php b/tests/Handler/GuzzleV5/HandlerTest.php index e1fd58961d..e58deabe08 100644 --- a/tests/Handler/GuzzleV5/HandlerTest.php +++ b/tests/Handler/GuzzleV5/HandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Handler\GuzzleV5; use Aws\Handler\GuzzleV5\GuzzleHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; @@ -24,7 +25,9 @@ */ class HandlerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Handler/GuzzleV5/StreamTest.php b/tests/Handler/GuzzleV5/StreamTest.php index d0f32d9928..11605024bb 100644 --- a/tests/Handler/GuzzleV5/StreamTest.php +++ b/tests/Handler/GuzzleV5/StreamTest.php @@ -3,6 +3,7 @@ use Aws\Handler\GuzzleV5\GuzzleStream as GuzzleStreamAdapter; use Aws\Handler\GuzzleV5\PsrStream as PsrStreamAdapter; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Stream\Stream as GuzzleStream; use PHPUnit\Framework\TestCase; @@ -13,7 +14,9 @@ */ class StreamTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Handler/GuzzleV6/HandlerTest.php b/tests/Handler/GuzzleV6/HandlerTest.php index ffdc7b60c0..636e714cee 100644 --- a/tests/Handler/GuzzleV6/HandlerTest.php +++ b/tests/Handler/GuzzleV6/HandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Handler\GuzzleV6; use Aws\Handler\GuzzleV6\GuzzleHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Handler\MockHandler; @@ -17,7 +18,9 @@ */ class HandlerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\HandlerStack')) { $this->markTestSkipped(); @@ -140,7 +143,7 @@ public function testHandlerWorksWithErroredRequest() $error = $e->getReason(); $this->assertInstanceOf(\Error::class, $error['exception']); $this->assertFalse($error['connection_error']); - $this->assertContains("error message", $error['exception']->getMessage()); + $this->assertStringContainsString("error message", $error['exception']->getMessage()); } $this->assertTrue($wasRejected, 'Reject callback was not triggered.'); diff --git a/tests/HandlerListTest.php b/tests/HandlerListTest.php index a84caea69a..745818a1ba 100644 --- a/tests/HandlerListTest.php +++ b/tests/HandlerListTest.php @@ -5,6 +5,7 @@ use Aws\CommandInterface; use Aws\HandlerList; use Aws\Middleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; @@ -13,11 +14,11 @@ */ class HandlerListTest extends TestCase { - /** - * @expectedException \LogicException - */ + use PHPUnitCompatTrait; + public function testEnsuresHandlerIsSet() { + $this->expectException(\LogicException::class); $list = new HandlerList(); $this->assertFalse($list->hasHandler()); $list->resolve(); @@ -60,6 +61,7 @@ public function testCanRemoveByInstance() $this->assertSame($handler, $list->resolve()); } + /** @doesNotPerformAssertions */ public function testIgnoreWhenNameNotFound() { $list = new HandlerList(); @@ -135,11 +137,11 @@ public function testCanPrintStack() $list->setHandler(function () {}); $lines = explode("\n", (string) $list); $this->assertCount(6, $lines); - $this->assertContains('0) Step: init, Name: foo, Function: callable(', $lines[0]); + $this->assertStringContainsString('0) Step: init, Name: foo, Function: callable(', $lines[0]); $this->assertSame("1) Step: init, Name: bar, Function: callable(['Aws\\Test\\HandlerListTest', 'bar'])", $lines[1]); $this->assertSame('2) Step: validate, Function: callable(Aws\Test\HandlerListTest::foo)', $lines[2]); $this->assertSame("3) Step: sign, Name: baz, Function: callable(['Aws\\Middleware', 'tap'])", $lines[3]); - $this->assertContains('4) Handler: callable(', $lines[4]); + $this->assertStringContainsString('4) Handler: callable(', $lines[4]); } public static function foo() {} @@ -152,8 +154,8 @@ public function testCanAddBefore() $list->appendBuild(function () {}, 'test'); $list->before('test', 'a', function () {}); $lines = explode("\n", (string) $list); - $this->assertContains("1) Step: build, Name: a", $lines[1]); - $this->assertContains("2) Step: build, Name: test", $lines[2]); + $this->assertStringContainsString("1) Step: build, Name: a", $lines[1]); + $this->assertStringContainsString("2) Step: build, Name: test", $lines[2]); } public function testCanAddAfter() @@ -164,16 +166,14 @@ public function testCanAddAfter() $list->appendInit(function () {}); $list->after('test', 'a', function () {}); $lines = explode("\n", (string) $list); - $this->assertContains("1) Step: build, Name: test", $lines[1]); - $this->assertContains("2) Step: build, Name: a", $lines[2]); - $this->assertContains("3) Step: build, Name: after_test", $lines[3]); + $this->assertStringContainsString("1) Step: build, Name: test", $lines[1]); + $this->assertStringContainsString("2) Step: build, Name: a", $lines[2]); + $this->assertStringContainsString("3) Step: build, Name: after_test", $lines[3]); } - /** - * @expectedException \InvalidArgumentException - */ public function testMustExistByNameToPrependOrAppend() { + $this->expectException(\InvalidArgumentException::class); $list = new HandlerList(); $list->before('foo', '', function () {}); } diff --git a/tests/HistoryTest.php b/tests/HistoryTest.php index 57174142e7..04c1d12d45 100644 --- a/tests/HistoryTest.php +++ b/tests/HistoryTest.php @@ -13,6 +13,8 @@ */ class HistoryTest extends TestCase { + use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; + public function testIsCountable() { $h = new History(); @@ -64,41 +66,33 @@ public function testCanAddException() $this->assertSame($e, $h->getLastReturn()); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoEntriesForLastResult() { + $this->expectException(\LogicException::class); $h = new History(); $h->getLastReturn(); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoReturnForLastReturn() { + $this->expectException(\LogicException::class); $h = new History(); $h->start(new Command('foo'), new Request('GET', 'http://foo.com')); $h->getLastReturn(); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenTicketAlreadyComplete() { + $this->expectException(\LogicException::class); $h = new History(); $t = $h->start(new Command('foo'), new Request('GET', 'http://foo.com')); $h->finish($t, new Aws\Result()); $h->finish($t, new Aws\Result()); } - /** - * @expectedException \InvalidArgumentException - */ public function testThrowsWhenTicketIsNotFound() { + $this->expectException(\InvalidArgumentException::class); $h = new History(); $h->finish('foo', new Aws\Result()); } @@ -135,20 +129,16 @@ public function testReturnsLastRequest() $this->assertSame($r, $h->getLastRequest()); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoCommands() { + $this->expectException(\LogicException::class); $h = new History(); $h->getLastCommand(); } - /** - * @expectedException \LogicException - */ public function testThrowsWhenNoRequests() { + $this->expectException(\LogicException::class); $h = new History(); $h->getLastRequest(); } diff --git a/tests/IdempotencyTokenMiddlewareTest.php b/tests/IdempotencyTokenMiddlewareTest.php index f797ccb21e..9d5c27fd9c 100644 --- a/tests/IdempotencyTokenMiddlewareTest.php +++ b/tests/IdempotencyTokenMiddlewareTest.php @@ -3,6 +3,7 @@ use Aws\IdempotencyTokenMiddleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Aws\HandlerList; use Aws\Api\ApiProvider; @@ -16,6 +17,8 @@ */ class IdempotencyTokenMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; + public function testAutoFillsMemberWithIdempotencyTrait() { $list = new HandlerList(); @@ -23,7 +26,7 @@ public function testAutoFillsMemberWithIdempotencyTrait() $called = true; $this->assertNotNull($command['ClientToken']); $regex = '/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/'; - $this->assertRegExp($regex, $command['ClientToken']); + $this->assertMatchesRegularExpression($regex, $command['ClientToken']); return Promise\Create::promiseFor(new Result([])); }); diff --git a/tests/Integ/GuzzleV5HandlerTest.php b/tests/Integ/GuzzleV5HandlerTest.php index 4ff30cedd3..041439cc24 100644 --- a/tests/Integ/GuzzleV5HandlerTest.php +++ b/tests/Integ/GuzzleV5HandlerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Integ; use Aws\Handler\GuzzleV5\GuzzleHandler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise\RejectionException; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; @@ -10,7 +11,9 @@ class GuzzleV5HandlerTest extends TestCase { - public function setUp() + use PHPUnitCompatTrait; + + public function _setUp() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Integ/GuzzleV6StreamHandlerTest.php b/tests/Integ/GuzzleV6StreamHandlerTest.php index f221cc42ad..924e68d0a9 100644 --- a/tests/Integ/GuzzleV6StreamHandlerTest.php +++ b/tests/Integ/GuzzleV6StreamHandlerTest.php @@ -1,14 +1,16 @@ markTestSkipped(); diff --git a/tests/JsonCompilerTest.php b/tests/JsonCompilerTest.php index 393db2d328..993eb6c6a6 100644 --- a/tests/JsonCompilerTest.php +++ b/tests/JsonCompilerTest.php @@ -2,6 +2,7 @@ namespace Aws\Test; use Aws\JsonCompiler; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,9 +10,11 @@ */ class JsonCompilerTest extends TestCase { + use PHPUnitCompatTrait; + private $models; - public function setup() + public function _setUp() { $this->models = realpath(__DIR__ . '/../src/data'); } @@ -20,14 +23,12 @@ public function testDecodesJsonToArray() { $c = new JsonCompiler(); $data = $c->load($this->models . '/endpoints.json'); - $this->assertInternalType('array', $data); + $this->assertIsArray($data); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresFileExists() { + $this->expectException(\InvalidArgumentException::class); $c = new JsonCompiler(); $c->load($this->models . '/not_there.json'); } diff --git a/tests/Lambda/LambdaClientTest.php b/tests/Lambda/LambdaClientTest.php index 46e9c586d9..850f34ce4d 100644 --- a/tests/Lambda/LambdaClientTest.php +++ b/tests/Lambda/LambdaClientTest.php @@ -3,11 +3,14 @@ use Aws\Lambda\LambdaClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; class LambdaClientTest extends TestCase { + use PHPUnitCompatTrait; + function testsAddsDefaultCurlOptions() { if (!extension_loaded('curl')) { diff --git a/tests/MiddlewareTest.php b/tests/MiddlewareTest.php index 54080d5c78..592e730d07 100644 --- a/tests/MiddlewareTest.php +++ b/tests/MiddlewareTest.php @@ -15,6 +15,7 @@ use Aws\Result; use Aws\ResultInterface; use Aws\Signature\SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Promise; @@ -26,7 +27,9 @@ */ class MiddlewareTest extends TestCase { - public function setup() + use PHPUnitCompatTrait; + + public function _setUp() { \GuzzleHttp\Promise\queue()->run(); } @@ -123,12 +126,10 @@ public function testBuildsRequests() $this->assertTrue($called); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage [a] is missing and is a required parameter - */ public function testValidatesCommands() { + $this->expectExceptionMessage("[a] is missing and is a required parameter"); + $this->expectException(\InvalidArgumentException::class); $list = new HandlerList(); $list->setHandler(new MockHandler([new Result()])); $api = new Service( diff --git a/tests/MockHandlerTest.php b/tests/MockHandlerTest.php index 94cc77acf4..e9706a8227 100644 --- a/tests/MockHandlerTest.php +++ b/tests/MockHandlerTest.php @@ -6,6 +6,7 @@ use Aws\Exception\AwsException; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Promise; @@ -16,12 +17,12 @@ */ class MockHandlerTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Expected an Aws\ResultInterface or Exception - */ + use PHPUnitCompatTrait; + public function testValidatesEachResult() { + $this->expectExceptionMessage("Expected an Aws\ResultInterface or Exception"); + $this->expectException(\InvalidArgumentException::class); new MockHandler(['foo']); } @@ -44,24 +45,20 @@ public function testReturnsMockResultsFromQueue() $this->assertSame($r2, $h($cmd, $request)->wait()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty - */ public function testThrowsWhenNoResultsInQueue() { + $this->expectExceptionMessage("Mock queue is empty"); + $this->expectException(\RuntimeException::class); $h = new MockHandler(); $cmd = new Command('foo'); $request = new Request('GET', 'http://www.example.com'); $h($cmd, $request); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessage Error - */ public function testThrowsExceptionsFromQueue() { + $this->expectExceptionMessage("Error"); + $this->expectException(\Aws\Exception\AwsException::class); $cmd = new Command('foo'); $e = new AwsException('Error', $cmd); $request = new Request('GET', 'http://www.example.com'); diff --git a/tests/MultiRegionClientTest.php b/tests/MultiRegionClientTest.php index d913e14a53..1ce01cc553 100644 --- a/tests/MultiRegionClientTest.php +++ b/tests/MultiRegionClientTest.php @@ -10,6 +10,7 @@ use Aws\MockHandler; use Aws\MultiRegionClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; @@ -17,12 +18,14 @@ class MultiRegionClientTest extends TestCase { + use PHPUnitCompatTrait; + /** @var MultiRegionClient */ private $instance; /** @var \PHPUnit_Framework_MockObject_MockObject */ private $mockRegionalClient; - public function setUp() + public function _setUp() { $this->mockRegionalClient = $this->getMockBuilder(AwsClient::class) ->disableOriginalConstructor() @@ -138,11 +141,9 @@ public function testDefaultsToAwsPartition() $this->assertSame('aws', $mrc->getConfig('partition')->getName()); } - /** - * @expectedException \InvalidArgumentException - */ public function testRejectsUnrecognizedPartitions() { + $this->expectException(\InvalidArgumentException::class); new MultiRegionClient([ 'service' => 'ec2', 'partition' => 'foo', diff --git a/tests/Multipart/AbstractUploaderTest.php b/tests/Multipart/AbstractUploaderTest.php index 1c8e7e73ae..c52d8f6be8 100644 --- a/tests/Multipart/AbstractUploaderTest.php +++ b/tests/Multipart/AbstractUploaderTest.php @@ -6,6 +6,7 @@ use Aws\Exception\MultipartUploadException; use Aws\Multipart\UploadState; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -15,6 +16,7 @@ */ class AbstractUploaderTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getUploaderWithState($status, array $results = [], $source = null) @@ -44,22 +46,18 @@ private function getTestUploader( return new TestUploader($client, $source ?: Psr7\Utils::streamFor(), $config); } - /** - * @expectedException \Aws\S3\Exception\S3MultipartUploadException - */ public function testThrowsExceptionOnBadInitiateRequest() { + $this->expectException(\Aws\S3\Exception\S3MultipartUploadException::class); $uploader = $this->getUploaderWithState(UploadState::CREATED, [ new AwsException('Failed', new Command('Initiate')), ]); $uploader->upload(); } - /** - * @expectedException \LogicException - */ public function testThrowsExceptionIfStateIsCompleted() { + $this->expectException(\LogicException::class); $uploader = $this->getUploaderWithState(UploadState::COMPLETED); $this->assertTrue($uploader->getState()->isCompleted()); $uploader->upload(); @@ -78,11 +76,9 @@ public function testSuccessfulCompleteReturnsResult() $this->assertTrue($uploader->getState()->isCompleted()); } - /** - * @expectedException \Aws\S3\Exception\S3MultipartUploadException - */ public function testThrowsExceptionOnBadCompleteRequest() { + $this->expectException(\Aws\S3\Exception\S3MultipartUploadException::class); $uploader = $this->getUploaderWithState(UploadState::CREATED, [ new Result(), // Initiate new Result(), // Upload @@ -107,8 +103,8 @@ public function testThrowsExceptionOnBadUploadRequest() $this->fail('No exception was thrown.'); } catch (MultipartUploadException $e) { $message = $e->getMessage(); - $this->assertContains('Failed[1]', $message); - $this->assertContains('Failed[4]', $message); + $this->assertStringContainsString('Failed[1]', $message); + $this->assertStringContainsString('Failed[4]', $message); $uploadedParts = $e->getState()->getUploadedParts(); $this->assertCount(3, $uploadedParts); $this->assertArrayHasKey(2, $uploadedParts); @@ -160,11 +156,9 @@ public function testAsyncUpload() $this->assertSame(6, $called); } - /** - * @expectedException \InvalidArgumentException - */ public function testRequiresIdParams() { + $this->expectException(\InvalidArgumentException::class); $this->getTestUploader(Psr7\Utils::streamFor()); } diff --git a/tests/Neptune/NeptuneClientTest.php b/tests/Neptune/NeptuneClientTest.php index 6522cd75ad..b365d61b4f 100644 --- a/tests/Neptune/NeptuneClientTest.php +++ b/tests/Neptune/NeptuneClientTest.php @@ -5,6 +5,7 @@ use Aws\Credentials\Credentials; use Aws\Neptune\NeptuneClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -14,13 +15,15 @@ */ class NeptuneClientTest extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; @@ -71,7 +74,7 @@ function ( if (!empty($expectedUrl)) { self::assertSame($expectedUrl, $url); } else if (!empty($expectedSignature)) { - $this->assertContains("X-Amz-Signature={$expectedSignature}", $url); + $this->assertStringContainsString("X-Amz-Signature={$expectedSignature}", $url); } else { self::assertNull($url); } diff --git a/tests/Polly/PollyClientTest.php b/tests/Polly/PollyClientTest.php index 23c760ede6..62a821f859 100644 --- a/tests/Polly/PollyClientTest.php +++ b/tests/Polly/PollyClientTest.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Polly\PollyClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class PollyClientTest extends TestCase { + use PHPUnitCompatTrait; + public function testCanGeneratePreSignedUrlForSynthesizeSpeech() { $polly = new PollyClient([ @@ -26,19 +29,19 @@ public function testCanGeneratePreSignedUrlForSynthesizeSpeech() 'VoiceId' => 'Ewa' ]; $url = $polly->createSynthesizeSpeechPreSignedUrl($args); - $this->assertContains('https://polly.us-west-2.amazonaws.com/v1/speech', $url); - $this->assertContains('LexiconNames=mno&LexiconNames=abc', $url); - $this->assertContains('OutputFormat=mp3', $url); - $this->assertContains('SampleRate=128', $url); - $this->assertContains('Text=Hello%20World', $url); - $this->assertContains('TextType=text', $url); - $this->assertContains('VoiceId=Ewa', $url); - $this->assertContains('X-Amz-Algorithm=AWS4-HMAC-SHA256', $url); - $this->assertContains('X-Amz-Credential=akid', $url); - $this->assertContains('X-Amz-Date=', $url); - $this->assertContains('X-Amz-Expires=900', $url); - $this->assertContains('X-Amz-SignedHeaders=host', $url); - $this->assertContains('X-Amz-Signature=', $url); - $this->assertContains('X-Amz-Date=', $url); + $this->assertStringContainsString('https://polly.us-west-2.amazonaws.com/v1/speech', $url); + $this->assertStringContainsString('LexiconNames=mno&LexiconNames=abc', $url); + $this->assertStringContainsString('OutputFormat=mp3', $url); + $this->assertStringContainsString('SampleRate=128', $url); + $this->assertStringContainsString('Text=Hello%20World', $url); + $this->assertStringContainsString('TextType=text', $url); + $this->assertStringContainsString('VoiceId=Ewa', $url); + $this->assertStringContainsString('X-Amz-Algorithm=AWS4-HMAC-SHA256', $url); + $this->assertStringContainsString('X-Amz-Credential=akid', $url); + $this->assertStringContainsString('X-Amz-Date=', $url); + $this->assertStringContainsString('X-Amz-Expires=900', $url); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Date=', $url); } } diff --git a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php new file mode 100644 index 0000000000..9af1c4707f --- /dev/null +++ b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php @@ -0,0 +1,131 @@ +setExpectedException( $exception, $this->exceptionMessage, $this->exceptionCode ); + } + + public function expectExceptionMessage( $message ) { + $this->exceptionMessage = $message; + + $exception = $this->getExpectedException(); + $this->setExpectedException( $exception, $message, $this->exceptionCode ); + } + + public function _setUp() + { + } + + public function setUp() + { + $this->_setUp(); + } + + public function _tearDown() + { + } + + public function tearDown() + { + $this->_tearDown(); + } + + public static function setUpBeforeClass() + { + self::_setUpBeforeClass(); + } + + public static function tearDownAfterClass() + { + self::_tearDownAfterClass(); + } + + public static function _tearDownAfterClass() + { + } + + public static function _setUpBeforeClass() + { + } + + public function expectNotToPerformAssertions() + { + } + + public function expectWarning() + { + $this->expectException(\PHPUnit_Framework_Error_Warning::class); + } + + public function expectExceptionMessageMatches($regularExpression) + { + $this->expectExceptionMessageRegExp($regularExpression); + } + + public function expectExceptionMessageRegExp($messageRegExp) + { + $exception = $this->getExpectedException(); + $this->setExpectedExceptionRegExp($exception, $messageRegExp, $this->exceptionCode); + } + + public function assertStringContainsString($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message); + } + + public function assertStringNotContainsString($expected, $actual, $message = '') + { + $this->assertNotContains($expected, $actual, $message); + } + + public function assertStringContainsStringIgnoringCase($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message, true); + } + + public function assertIsInt($actual, $message = '') + { + $this->assertInternalType('int', $actual, $message); + } + + public function assertIsArray($actual, $message = '') + { + $this->assertInternalType('array', $actual, $message); + } + + public function assertIsCallable($actual, $message = '') + { + $this->assertInternalType('callable', $actual, $message); + } + + public function assertIsString($actual, $message = '') + { + $this->assertInternalType('string', $actual, $message); + } + + public function assertIsResource($actual, $message = '') + { + $this->assertInternalType('resource', $actual, $message); + } + + public function assertMatchesRegularExpression($pattern, $string, $message = '') + { + $this->assertRegExp($pattern, $string, $message); + } + + public function assertDoesNotMatchRegularExpression($pattern, $string, $message = '') + { + $this->assertNotRegExp($pattern, $string, $message); + } + + public function assertFileDoesNotExist($file, $message = '') + { + $this->assertFileNotExists($file, $message); + } +} \ No newline at end of file diff --git a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php new file mode 100644 index 0000000000..35eb03eccc --- /dev/null +++ b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php @@ -0,0 +1,119 @@ +_setUp(); + } + + public function _tearDown() + { + } + + public function tearDown() + { + $this->_tearDown(); + } + + public static function setUpBeforeClass() + { + self::_setUpBeforeClass(); + } + + public static function tearDownAfterClass() + { + self::_tearDownAfterClass(); + } + + public static function _tearDownAfterClass() + { + } + + public static function _setUpBeforeClass() + { + } + + public function expectNotToPerformAssertions() + { + } + + public function expectWarning() + { + $this->expectException(\PHPUnit_Framework_Error_Warning::class); + } + + public function expectExceptionMessageMatches($regularExpression) + { + $this->expectExceptionMessageRegExp($regularExpression); + } + + public function expectExceptionMessageRegExp($messageRegExp) + { + $exception = $this->getExpectedException(); + $this->setExpectedExceptionRegExp($exception, $messageRegExp, $this->exceptionCode); + } + + public function assertStringContainsString($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message); + } + + public function assertStringNotContainsString($expected, $actual, $message = '') + { + $this->assertNotContains($expected, $actual, $message); + } + + public function assertStringContainsStringIgnoringCase($expected, $actual, $message = '') + { + $this->assertContains($expected, $actual, $message, true); + } + + public function assertIsInt($actual, $message = '') + { + $this->assertInternalType('int', $actual, $message); + } + + public function assertIsArray($actual, $message = '') + { + $this->assertInternalType('array', $actual, $message); + } + + public function assertIsCallable($actual, $message = '') + { + $this->assertInternalType('callable', $actual, $message); + } + + public function assertIsString($actual, $message = '') + { + $this->assertInternalType('string', $actual, $message); + } + + public function assertIsResource($actual, $message = '') + { + $this->assertInternalType('resource', $actual, $message); + } + + public function assertMatchesRegularExpression($pattern, $string, $message = '') + { + $this->assertRegExp($pattern, $string, $message); + } + + public function assertDoesNotMatchRegularExpression($pattern, $string, $message = '') + { + $this->assertNotRegExp($pattern, $string, $message); + } + + public function assertFileDoesNotExist($file, $message = '') + { + $this->assertFileNotExists($file, $message); + } +} \ No newline at end of file diff --git a/tests/Polyfill/PHPUnit9/ArraySubset.php b/tests/Polyfill/PHPUnit9/ArraySubset.php new file mode 100644 index 0000000000..308dfe9402 --- /dev/null +++ b/tests/Polyfill/PHPUnit9/ArraySubset.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace Aws\Test\Polyfill\PHPUnit9; + +use PHPUnit\Framework\Constraint\Constraint; +use PHPUnit\Framework\ExpectationFailedException; +use PHPUnit\Util\Exception; +use SebastianBergmann\Comparator\ComparisonFailure; + +/** + * Constraint that asserts that the array it is evaluated for has a specified subset. + * + * Uses array_replace_recursive() to check if a key value subset is part of the + * subject array. + */ +class ArraySubset extends Constraint +{ + /** + * @var iterable + */ + private $subset; + + /** + * @var bool + */ + private $strict; + + public function __construct(iterable $subset, bool $strict = false) + { + $this->strict = $strict; + $this->subset = $subset; + } + + /** + * Evaluates the constraint for parameter $other + * + * If $returnResult is set to false (the default), an exception is thrown + * in case of a failure. null is returned otherwise. + * + * If $returnResult is true, the result of the evaluation is returned as + * a boolean value instead: true in case of success, false in case of a + * failure. + * + * @param mixed $other value or object to evaluate + * @param string $description Additional information about the test + * @param bool $returnResult Whether to return a result or throw an exception + * + * @throws ExpectationFailedException + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function evaluate($other, string $description = '', $returnResult = false): ?bool + { + //type cast $other & $this->subset as an array to allow + //support in standard array functions. + $other = $this->toArray($other); + $this->subset = $this->toArray($this->subset); + + $patched = \array_replace_recursive($other, $this->subset); + + if ($this->strict) { + $result = $other === $patched; + } else { + $result = $other == $patched; + } + + if ($returnResult) { + return $result; + } + + if (!$result) { + $f = new ComparisonFailure( + $patched, + $other, + \var_export($patched, true), + \var_export($other, true) + ); + + $this->fail($other, $description, $f); + } + + return null; + } + + /** + * Returns a string representation of the constraint. + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + public function toString(): string + { + throw new Exception('Not implemented'); + } + + /** + * Returns the description of the failure + * + * The beginning of failure messages is "Failed asserting that" in most + * cases. This method should return the second part of that sentence. + * + * @param mixed $other evaluated value or object + * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + */ + protected function failureDescription($other): string + { + return 'an array ' . $this->toString(); + } + + private function toArray($other) + { + if (\is_array($other)) { + return $other; + } + + if ($other instanceof \ArrayObject) { + return $other->getArrayCopy(); + } + + if ($other instanceof \Traversable) { + return \iterator_to_array($other); + } + + // Keep BC even if we know that array would not be the expected one + return (array) $other; + } +} diff --git a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php new file mode 100644 index 0000000000..f10106183e --- /dev/null +++ b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php @@ -0,0 +1,130 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Aws\Test\Polyfill\PHPUnit; + +use ArrayAccess; +use Exception; +use ReflectionException; +use ReflectionObject; +use ReflectionProperty; +use Aws\Test\Polyfill\PHPUnit9\ArraySubset; + +trait PHPUnitCompatTrait +{ + public function _setUp() + { + } + + public function setUp(): void + { + $this->_setUp(); + } + + public function _tearDown() + { + } + + public function tearDown(): void + { + $this->_tearDown(); + } + + public static function setUpBeforeClass(): void + { + self::_setUpBeforeClass(); + } + + public static function tearDownAfterClass(): void + { + self::_tearDownAfterClass(); + } + + public static function _tearDownAfterClass() + { + } + + public static function _setUpBeforeClass() + { + } + + public function readAttribute($object, $attributeName) + { + try { + $attribute = new ReflectionProperty($object, $attributeName); + } catch (ReflectionException $e) { + $reflector = new ReflectionObject($object); + + while ($reflector = $reflector->getParentClass()) { + try { + $attribute = $reflector->getProperty($attributeName); + break; + } catch (ReflectionException $e) { + } + } + } + + if (isset($attribute)) { + if ( ! $attribute || $attribute->isPublic()) { + return $object->$attributeName; + } + $attribute->setAccessible(true); + $value = $attribute->getValue($object); + $attribute->setAccessible(false); + + return $value; + } + + throw new Exception( + sprintf( + 'Attribute "%s" not found in object.', + $attributeName + ) + ); + } + + public static function invalidArgumentHelper($argument, $type, $value = null) + { + $stack = debug_backtrace(false); + + return new \PHPUnit\Framework\Exception( + sprintf( + 'Argument #%d%sof %s::%s() must be a %s', + $argument, + $value !== null ? ' ('.$value.')' : ' ', + $stack[1]['class'], + $stack[1]['function'], + $type + ) + ); + } + + public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = '') + { + if ( ! (\is_array($subset) || $subset instanceof ArrayAccess)) { + throw self::invalidArgumentHelper( + 1, + 'array or ArrayAccess' + ); + } + + if ( ! (\is_array($array) || $array instanceof ArrayAccess)) { + throw self::invalidArgumentHelper( + 2, + 'array or ArrayAccess' + ); + } + + $constraint = new ArraySubset($subset, $checkForObjectIdentity); + + static::assertThat($array, $constraint, $message); + } +} \ No newline at end of file diff --git a/tests/PresignUrlMiddlewareTest.php b/tests/PresignUrlMiddlewareTest.php index e2d3262940..58b01d66c9 100644 --- a/tests/PresignUrlMiddlewareTest.php +++ b/tests/PresignUrlMiddlewareTest.php @@ -8,6 +8,7 @@ use Aws\Neptune\NeptuneClient; use Aws\Rds\RdsClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -16,6 +17,7 @@ */ class PresignUrlMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testDoesNotAddPresignedUrlForNonRequiredOperations() @@ -47,10 +49,10 @@ public function testAddsPresignedUrlForRequiredOperations() 'handler' => function (CommandInterface $cmd, RequestInterface $r) { $url = $cmd['PresignedUrl']; $this->assertNotNull($url); - $this->assertContains('https://ec2.eu-west-1.amazonaws.com', $url); - $this->assertContains('SourceSnapshotId=foo', $url); - $this->assertContains('SourceRegion=eu-west-1', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('https://ec2.eu-west-1.amazonaws.com', $url); + $this->assertStringContainsString('SourceSnapshotId=foo', $url); + $this->assertStringContainsString('SourceRegion=eu-west-1', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); $this->assertSame('us-east-2', $cmd['DestinationRegion']); return new Result; @@ -67,12 +69,12 @@ public function testAddsPresignedUrlForRequiredOperations() 'handler' => function (CommandInterface $cmd, RequestInterface $r) { $url = $cmd['PreSignedUrl']; $this->assertNotNull($url); - $this->assertContains('https://rds.eu-west-1.amazonaws.com', $url); - $this->assertContains('KmsKeyId=', $url); - $this->assertContains('SourceDBSnapshotIdentifier=', $url); - $this->assertContains('TargetDBSnapshotIdentifier=my-snapshot-copy', $url); - $this->assertContains('eu-west-1', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('https://rds.eu-west-1.amazonaws.com', $url); + $this->assertStringContainsString('KmsKeyId=', $url); + $this->assertStringContainsString('SourceDBSnapshotIdentifier=', $url); + $this->assertStringContainsString('TargetDBSnapshotIdentifier=my-snapshot-copy', $url); + $this->assertStringContainsString('eu-west-1', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); $this->assertSame('us-east-2', $cmd['DestinationRegion']); return new Result; diff --git a/tests/Psr16CacheAdapterTest.php b/tests/Psr16CacheAdapterTest.php index d3eb05eaaa..adf00ff7e9 100644 --- a/tests/Psr16CacheAdapterTest.php +++ b/tests/Psr16CacheAdapterTest.php @@ -2,17 +2,20 @@ namespace Aws\Test; use Aws\Psr16CacheAdapter; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\SimpleCache\CacheInterface; use PHPUnit\Framework\TestCase; class Psr16CacheAdapterTest extends TestCase { + use PHPUnitCompatTrait; + /** @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedCache */ private $wrapped; /** @var Psr16CacheAdapter */ private $instance; - public function setUp() + public function _setUp() { $this->wrapped = $this->getMockBuilder(CacheInterface::class)->getMock(); $this->instance = new Psr16CacheAdapter($this->wrapped); diff --git a/tests/PsrCacheAdapterTest.php b/tests/PsrCacheAdapterTest.php index 2b0db7fb06..ac7bde272d 100644 --- a/tests/PsrCacheAdapterTest.php +++ b/tests/PsrCacheAdapterTest.php @@ -2,18 +2,21 @@ namespace Aws\Test; use Aws\PsrCacheAdapter; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; use PHPUnit\Framework\TestCase; class PsrCacheAdapterTest extends TestCase { + use PHPUnitCompatTrait; + /** @var CacheItemPoolInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedCache */ private $wrapped; /** @var PsrCacheAdapter */ private $instance; - public function setUp() + public function _setUp() { $this->wrapped = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock(); $this->instance = new PsrCacheAdapter($this->wrapped); diff --git a/tests/Rds/AuthTokenGeneratorTest.php b/tests/Rds/AuthTokenGeneratorTest.php index 21135d3a6b..a1ced2279c 100644 --- a/tests/Rds/AuthTokenGeneratorTest.php +++ b/tests/Rds/AuthTokenGeneratorTest.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Rds\AuthTokenGenerator; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -11,6 +12,8 @@ */ class AuthTokenGeneratorTest extends TestCase { + use PHPUnitCompatTrait; + public function testCanCreateAuthTokenWthCredentialInstance() { $creds = new Credentials('foo', 'bar', 'baz'); @@ -21,13 +24,13 @@ public function testCanCreateAuthTokenWthCredentialInstance() 'myDBUser' ); - $this->assertContains('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); - $this->assertContains('us-west-2', $token); - $this->assertContains('X-Amz-Credential=foo', $token); - $this->assertContains('X-Amz-Expires=900', $token); - $this->assertContains('X-Amz-SignedHeaders=host', $token); - $this->assertContains('DBUser=myDBUser', $token); - $this->assertContains('Action=connect', $token); + $this->assertStringContainsString('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); + $this->assertStringContainsString('us-west-2', $token); + $this->assertStringContainsString('X-Amz-Credential=foo', $token); + $this->assertStringContainsString('X-Amz-Expires=900', $token); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $token); + $this->assertStringContainsString('DBUser=myDBUser', $token); + $this->assertStringContainsString('Action=connect', $token); } public function testCanCreateAuthTokenWthCredentialProvider() @@ -47,13 +50,13 @@ public function testCanCreateAuthTokenWthCredentialProvider() 'myDBUser' ); - $this->assertContains('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); - $this->assertContains('us-west-2', $token); - $this->assertContains('X-Amz-Credential=AKID', $token); - $this->assertContains('X-Amz-Expires=900', $token); - $this->assertContains('X-Amz-SignedHeaders=host', $token); - $this->assertContains('DBUser=myDBUser', $token); - $this->assertContains('Action=connect', $token); + $this->assertStringContainsString('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); + $this->assertStringContainsString('us-west-2', $token); + $this->assertStringContainsString('X-Amz-Credential=AKID', $token); + $this->assertStringContainsString('X-Amz-Expires=900', $token); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $token); + $this->assertStringContainsString('DBUser=myDBUser', $token); + $this->assertStringContainsString('Action=connect', $token); } public function lifetimeProvider() @@ -82,13 +85,13 @@ public function testCanCreateAuthTokenWthNonDefaultLifetime($lifetime) $lifetime ); $lifetimeInSeconds = $lifetime * 60; - $this->assertContains('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); - $this->assertContains('us-west-2', $token); - $this->assertContains('X-Amz-Credential=foo', $token); - $this->assertContains("X-Amz-Expires={$lifetimeInSeconds}", $token); - $this->assertContains('X-Amz-SignedHeaders=host', $token); - $this->assertContains('DBUser=myDBUser', $token); - $this->assertContains('Action=connect', $token); + $this->assertStringContainsString('prod-instance.us-east-1.rds.amazonaws.com:3306', $token); + $this->assertStringContainsString('us-west-2', $token); + $this->assertStringContainsString('X-Amz-Credential=foo', $token); + $this->assertStringContainsString("X-Amz-Expires={$lifetimeInSeconds}", $token); + $this->assertStringContainsString('X-Amz-SignedHeaders=host', $token); + $this->assertStringContainsString('DBUser=myDBUser', $token); + $this->assertStringContainsString('Action=connect', $token); } public function lifetimeFailureProvider() @@ -106,13 +109,13 @@ public function lifetimeFailureProvider() /** * @dataProvider lifetimeFailureProvider - * @param $lifetime * - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Lifetime must be a positive number less than or equal to 15, was + * @param $lifetime */ public function testThrowsExceptionWithInvalidLifetime($lifetime) { + $this->expectExceptionMessage("Lifetime must be a positive number less than or equal to 15, was"); + $this->expectException(\InvalidArgumentException::class); $creds = new Credentials('foo', 'bar', 'baz'); $connect = new AuthTokenGenerator($creds); $connect->createToken( diff --git a/tests/Rds/RdsClientTest.php b/tests/Rds/RdsClientTest.php index 76e2e0b5cf..cfcc8176eb 100644 --- a/tests/Rds/RdsClientTest.php +++ b/tests/Rds/RdsClientTest.php @@ -6,6 +6,7 @@ use Aws\Rds\RdsClient; use Aws\MockHandler; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -15,13 +16,15 @@ */ class RdsClientTest extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; @@ -37,7 +40,7 @@ public function testAddsCopySnapshotMiddleware() $mock = new MockHandler([ function ($command, $request) { $this->assertNotNull($command['PreSignedUrl']); - $this->assertContains('us-west-2', $command['PreSignedUrl']); + $this->assertStringContainsString('us-west-2', $command['PreSignedUrl']); $this->assertSame('us-east-1', $command['DestinationRegion']); return new Result(); } @@ -101,7 +104,7 @@ public function testCorrectPresignRdsUrls( if (!empty($expectedUrl)) { self::assertSame($expectedUrl, $url); } else if (!empty($expectedSignature)) { - $this->assertContains("X-Amz-Signature={$expectedSignature}", $url); + $this->assertStringContainsString("X-Amz-Signature={$expectedSignature}", $url); } else { self::assertNull($url); } diff --git a/tests/ResultPaginatorTest.php b/tests/ResultPaginatorTest.php index d5134d294a..ecefbbcea2 100644 --- a/tests/ResultPaginatorTest.php +++ b/tests/ResultPaginatorTest.php @@ -5,6 +5,7 @@ use Aws\CommandInterface; use Aws\DynamoDb\DynamoDbClient; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -14,6 +15,7 @@ */ class ResultPaginatorTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; private function getCustomClientProvider(array $config) diff --git a/tests/ResultTest.php b/tests/ResultTest.php index 27c3901047..38cb5f01db 100644 --- a/tests/ResultTest.php +++ b/tests/ResultTest.php @@ -2,6 +2,7 @@ namespace Aws\Test; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ResultTest extends TestCase { + use PHPUnitCompatTrait; + public function testHasData() { $c = new Result(['a' => 'b', 'c' => 'd']); @@ -18,7 +21,7 @@ public function testHasData() $this->assertTrue($c->hasKey('c')); $this->assertFalse($c->hasKey('f')); $this->assertSame('b', $c->search('a')); - $this->assertContains('Model Data', (string) $c); + $this->assertStringContainsString('Model Data', (string) $c); } public function testCanIndirectlyModifyLikeAnArray() diff --git a/tests/Retry/ConfigurationProviderTest.php b/tests/Retry/ConfigurationProviderTest.php index a5f54c9a39..5e4a134b30 100644 --- a/tests/Retry/ConfigurationProviderTest.php +++ b/tests/Retry/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\Retry\ConfigurationInterface; use Aws\Retry\ConfigurationProvider; use Aws\Retry\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_MAX_ATTEMPTS) ?: '', @@ -59,7 +62,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_MAX_ATTEMPTS . '=' . self::$originalEnv['max_attempts']); @@ -176,21 +179,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -204,12 +203,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -222,12 +219,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -297,11 +292,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -419,12 +412,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid retry configuration argument - */ public function testThrowsForInvalidUnwrapArgument() { + $this->expectExceptionMessage("Not a valid retry configuration argument"); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap('some_string'); } } diff --git a/tests/Retry/ConfigurationTest.php b/tests/Retry/ConfigurationTest.php index 176674ea10..48c0df944e 100644 --- a/tests/Retry/ConfigurationTest.php +++ b/tests/Retry/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\Retry; use Aws\Retry\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('adaptive', 8); @@ -27,21 +30,17 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage The 'maxAttempts' parameter has to be an integer >= 1 - */ public function testHandlesInvalidMaxAttempts() { + $this->expectExceptionMessage("The 'maxAttempts' parameter has to be an integer >= 1"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); new Configuration('standard', 0); } - /** - * @expectedException \Aws\Retry\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' is not a valid mode - */ public function testHandlesInvalidMode() { + $this->expectExceptionMessage("'foo' is not a valid mode"); + $this->expectException(\Aws\Retry\Exception\ConfigurationException::class); new Configuration('foo', 5); } } diff --git a/tests/RetryMiddlewareTest.php b/tests/RetryMiddlewareTest.php index d84bfafb4b..c9a3b6b2ff 100644 --- a/tests/RetryMiddlewareTest.php +++ b/tests/RetryMiddlewareTest.php @@ -7,6 +7,7 @@ use Aws\MockHandler; use Aws\Result; use Aws\RetryMiddleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise\RejectedPromise; @@ -20,6 +21,8 @@ */ class RetryMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; + public function testAddRetryHeader() { $nextHandler = function (CommandInterface $command, RequestInterface $request) { @@ -380,7 +383,7 @@ function () use (&$called) { $called[] = func_get_args(); } $this->fail(); } catch (AwsException $e) { $this->assertCount(1, $called); - $this->assertContains('foo', $e->getMessage()); + $this->assertStringContainsString('foo', $e->getMessage()); } } diff --git a/tests/RetryMiddlewareV2Test.php b/tests/RetryMiddlewareV2Test.php index e0d1147e87..a3f5fd99f7 100644 --- a/tests/RetryMiddlewareV2Test.php +++ b/tests/RetryMiddlewareV2Test.php @@ -12,6 +12,7 @@ use Aws\Retry\QuotaManager; use Aws\Retry\RateLimiter; use Aws\RetryMiddlewareV2; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; @@ -24,6 +25,7 @@ */ class RetryMiddlewareV2Test extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -764,7 +766,7 @@ public function testUsesCustomDelayer() $this->fail(); } catch (AwsException $e) { $this->assertSame(3, $attempts); - $this->assertContains('foo', $e->getMessage()); + $this->assertStringContainsString('foo', $e->getMessage()); } } @@ -885,7 +887,7 @@ function () use (&$called) { $called[] = func_get_args(); } $this->fail(); } catch (AwsException $e) { $this->assertCount(1, $called); - $this->assertContains('foo', $e->getMessage()); + $this->assertStringContainsString('foo', $e->getMessage()); } } diff --git a/tests/Route53/RouteClient53Test.php b/tests/Route53/RouteClient53Test.php index 5d64680dbd..9362e7a671 100644 --- a/tests/Route53/RouteClient53Test.php +++ b/tests/Route53/RouteClient53Test.php @@ -2,6 +2,7 @@ namespace Aws\Test\Route53; use Aws\Route53\Route53Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class RouteClient53Test extends TestCase { + use PHPUnitCompatTrait; + public function testCleansIds() { $client = new Route53Client([ @@ -34,8 +37,8 @@ public function testCleansIds() $request = \Aws\serialize($command); $requestUri = (string) $request->getUri(); - $this->assertContains('/hostedzone/foo/rrset/', $requestUri); - $this->assertNotContains('/hostedzone/hostedzone', $requestUri); + $this->assertStringContainsString('/hostedzone/foo/rrset/', $requestUri); + $this->assertStringNotContainsString('/hostedzone/hostedzone', $requestUri); $command = $client->getCommand('GetReusableDelegationSet', [ 'Id' => '/delegationset/foo', @@ -43,8 +46,8 @@ public function testCleansIds() $request = \Aws\serialize($command); $requestUri = (string) $request->getUri(); - $this->assertContains('/delegationset/foo', $requestUri); - $this->assertNotContains('/delegationset/delegationset', $requestUri); + $this->assertStringContainsString('/delegationset/foo', $requestUri); + $this->assertStringNotContainsString('/delegationset/delegationset', $requestUri); $command = $client->getCommand('CreateHostedZone', [ 'Name' => 'foo', @@ -53,7 +56,7 @@ public function testCleansIds() ]); $request = \Aws\serialize($command); - $this->assertContains( + $this->assertStringContainsString( 'bar', $request->getBody()->getContents() ); diff --git a/tests/S3/AmbiguousSuccessParserTest.php b/tests/S3/AmbiguousSuccessParserTest.php index f2cc6ea7f5..d9e0d20cbf 100644 --- a/tests/S3/AmbiguousSuccessParserTest.php +++ b/tests/S3/AmbiguousSuccessParserTest.php @@ -7,15 +7,18 @@ use Aws\CommandInterface; use Aws\S3\AmbiguousSuccessParser; use Aws\S3\Exception\S3Exception; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\ResponseInterface; use PHPUnit\Framework\TestCase; class AmbiguousSuccessParserTest extends TestCase { + use PHPUnitCompatTrait; + private $instance; - public function setUp() + public function _setUp() { $parser = function () {}; $errorParser = function () { @@ -31,13 +34,13 @@ public function setUp() /** * @dataProvider opsWithAmbiguousSuccessesProvider - * @param string $operation * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage Sorry! + * @param string $operation */ public function testConvertsAmbiguousSuccessesToExceptions($operation) { + $this->expectExceptionMessage("Sorry!"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $command = $this->getMockBuilder(CommandInterface::class)->getMock(); $command->expects($this->any()) ->method('getName') @@ -54,6 +57,7 @@ public function testConvertsAmbiguousSuccessesToExceptions($operation) /** * @dataProvider opsWithoutAmbiguousSuccessesProvider * @param string $operation + * @doesNotPerformAssertions */ public function testIgnoresAmbiguousSuccessesOnUnaffectedOperations($operation) { @@ -72,12 +76,11 @@ public function testIgnoresAmbiguousSuccessesOnUnaffectedOperations($operation) /** * @dataProvider opsWithAmbiguousSuccessesProvider - * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage An error connecting to the service occurred while performing the */ public function testThrowsConnectionErrorForEmptyBody($operation) { + $this->expectExceptionMessage("An error connecting to the service occurred while performing the"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $parser = function() {}; $errorParser = new XmlErrorParser(); $instance = new AmbiguousSuccessParser( diff --git a/tests/S3/BatchDeleteTest.php b/tests/S3/BatchDeleteTest.php index 64cc5fd57b..6a26d85ced 100644 --- a/tests/S3/BatchDeleteTest.php +++ b/tests/S3/BatchDeleteTest.php @@ -6,30 +6,28 @@ use Aws\Result; use Aws\S3\BatchDelete; use Aws\S3\Exception\DeleteMultipleObjectsException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; /** - * @covers Aws\S3\BatchDelete + * @covers \Aws\S3\BatchDelete */ class BatchDeleteTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesBatchSizeIsGreatherThanZero() { + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); BatchDelete::fromIterator($client, 'foo', new \ArrayIterator(), ['batch_size' => 0]); } - /** - * @expectedException \InvalidArgumentException - */ public function testValidatesBeforeIsCallable() { + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('s3'); BatchDelete::fromIterator($client, 'foo', new \ArrayIterator(), ['before' => 0]); } diff --git a/tests/S3/BucketEndpointArnMiddlewareTest.php b/tests/S3/BucketEndpointArnMiddlewareTest.php index 80495b8f15..704179ff17 100644 --- a/tests/S3/BucketEndpointArnMiddlewareTest.php +++ b/tests/S3/BucketEndpointArnMiddlewareTest.php @@ -9,6 +9,7 @@ use Aws\Result; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -19,6 +20,7 @@ */ class BucketEndpointArnMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -71,7 +73,7 @@ public function testCorrectlyModifiesUri( ); } - $this->assertContains( + $this->assertStringContainsString( "/{$signingRegion}/s3", $req->getHeader('Authorization')[0] ); diff --git a/tests/S3/Crypto/S3EncryptionClientTest.php b/tests/S3/Crypto/S3EncryptionClientTest.php index 6f59ac570a..28794aebc9 100644 --- a/tests/S3/Crypto/S3EncryptionClientTest.php +++ b/tests/S3/Crypto/S3EncryptionClientTest.php @@ -15,6 +15,7 @@ use Aws\S3\Crypto\HeadersMetadataStrategy; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTrait; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Promise; @@ -25,6 +26,7 @@ class S3EncryptionClientTest extends TestCase { + use PHPUnitCompatTrait; use S3EncryptionClientTestingTrait; use UsesCryptoParamsTrait; use UsesMetadataEnvelopeTrait; @@ -264,6 +266,8 @@ public function testPutObjectValidatesCipher( if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $s3 = $this->getS3Client(); @@ -299,6 +303,8 @@ public function testPutObjectValidatesKeySize( ) { if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $cipherOptions = [ @@ -422,12 +428,10 @@ public function testPutObjectWrapsBodyInAesGcmEncryptingStream() $this->assertTrue($this->mockQueueEmpty()); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Unrecognized or unsupported AESName for reverse lookup. - */ public function testGetObjectThrowsOnInvalidCipher() { + $this->expectExceptionMessage("Unrecognized or unsupported AESName for reverse lookup."); + $this->expectException(\RuntimeException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProvider($kms); $this->addMockResults($kms, [ @@ -457,12 +461,10 @@ public function testGetObjectThrowsOnInvalidCipher() $this->assertInstanceOf(AesDecryptingStream::class, $result['Body']); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Not able to detect the materials description. - */ public function testFromDecryptionEnvelopeEmptyKmsMaterialException() { + $this->expectExceptionMessage("Not able to detect the materials description."); + $this->expectException(\RuntimeException::class); $kms = $this->getKmsClient(); $keyId = '11111111-2222-3333-4444-555555555555'; $provider = new KmsMaterialsProvider($kms, $keyId); @@ -471,12 +473,10 @@ public function testFromDecryptionEnvelopeEmptyKmsMaterialException() $provider->fromDecryptionEnvelope($envelope); } - /** - * @expectedException RuntimeException - * @expectedExceptionMessage Not able to detect kms_cmk_id (legacy implementation) - */ public function testFromDecryptionEnvelopeInvalidKmsMaterialException() { + $this->expectExceptionMessage("Not able to detect kms_cmk_id (legacy implementation)"); + $this->expectException(\RuntimeException::class); $kms = $this->getKmsClient(); $keyId = '11111111-2222-3333-4444-555555555555'; $provider = new KmsMaterialsProvider($kms, $keyId); @@ -727,12 +727,11 @@ public function testGetObjectSavesFile() * Note that outside of PHPUnit, normal code execution will continue through * this warning unless configured otherwise. PHPUnit throws it as an * exception here for testing. - * - * @expectedException PHPUnit_Framework_Error_Warning - * @expectedExceptionMessage 'Aad' has been supplied for content encryption with AES/GCM/NoPadding */ public function testTriggersWarningForGcmEncryptionWithAad() { + $this->expectExceptionMessage("'Aad' has been supplied for content encryption with AES/GCM/NoPadding"); + $this->expectWarning(); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -781,7 +780,7 @@ public function testAddsCryptoUserAgent() 'region' => 'us-west-2', 'version' => 'latest', 'http_handler' => function (RequestInterface $req) use ($provider) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionClient::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Crypto/S3EncryptionClientV2Test.php b/tests/S3/Crypto/S3EncryptionClientV2Test.php index 023f91e55b..f9c7e14226 100644 --- a/tests/S3/Crypto/S3EncryptionClientV2Test.php +++ b/tests/S3/Crypto/S3EncryptionClientV2Test.php @@ -12,17 +12,18 @@ use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\S3\Crypto\S3EncryptionClientV2; use Aws\Test\Crypto\UsesCryptoParamsTraitV2; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; -use PHPUnit_Framework_Error_Warning; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; class S3EncryptionClientV2Test extends TestCase { + use PHPUnitCompatTrait; use S3EncryptionClientTestingTrait; use UsesCryptoParamsTraitV2; use UsesMetadataEnvelopeTrait; @@ -273,6 +274,8 @@ public function testPutObjectValidatesCipher( ) { if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $s3 = $this->getS3Client(); @@ -312,6 +315,8 @@ public function testPutObjectValidatesKeySize( ) { if ($exception) { $this->setupProvidedExpectedException($exception); + } else { + $this->expectNotToPerformAssertions(); } $cipherOptions = [ @@ -409,12 +414,11 @@ public function testPutObjectWrapsBodyInAesGcmEncryptingStream() * Note that outside of PHPUnit, normal code execution will continue through * this warning unless configured otherwise. PHPUnit throws it as an * exception here for testing. - * - * @expectedException PHPUnit_Framework_Error_Warning - * @expectedExceptionMessage 'Aad' has been supplied for content encryption with AES/GCM/NoPadding */ public function testTriggersWarningForGcmEncryptionWithAad() { + $this->expectExceptionMessage("'Aad' has been supplied for content encryption with AES/GCM/NoPadding"); + $this->expectWarning(); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -503,12 +507,10 @@ public function testAddsEncryptionContextForKms() $this->assertTrue($this->mockQueueEmpty()); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage Unrecognized or unsupported AESName for reverse lookup. - */ public function testGetObjectThrowsOnInvalidCipher() { + $this->expectExceptionMessage("Unrecognized or unsupported AESName for reverse lookup."); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -539,12 +541,10 @@ public function testGetObjectThrowsOnInvalidCipher() $this->assertInstanceOf(AesDecryptingStream::class, $result['Body']); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object is encrypted with the keywrap schema 'my_first_keywrap' - */ public function testGetObjectThrowsOnInvalidKeywrap() { + $this->expectExceptionMessage("The requested object is encrypted with the keywrap schema 'my_first_keywrap'"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -574,12 +574,10 @@ public function testGetObjectThrowsOnInvalidKeywrap() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2 - */ public function testGetObjectThrowsOnLegacyKeywrap() { + $this->expectExceptionMessage("The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -609,12 +607,10 @@ public function testGetObjectThrowsOnLegacyKeywrap() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage There is a mismatch in specified content encryption algrithm between the materials description value and the metadata envelope value - */ public function testGetObjectThrowsOnMismatchAlgorithm() { + $this->expectExceptionMessage("There is a mismatch in specified content encryption algrithm between the materials description value and the metadata envelope value"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $provider = new KmsMaterialsProviderV2($kms, 'foo'); $this->addMockResults($kms, [ @@ -908,12 +904,10 @@ public function testGetObjectSavesFile() $this->assertStringEqualsFile($file, (string)$result['Body']); } - /** - * @expectedException PHPUnit_Framework_Error_Warning - * @expectedExceptionMessage This S3 Encryption Client operation is configured to read encrypted data with legacy encryption modes - */ public function testEmitsWarningForLegacySecurityProfile() { + $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) { @@ -955,12 +949,10 @@ public function testEmitsWarningForLegacySecurityProfile() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2 - */ public function testThrowsForV2ProfileAndLegacyObject() { + $this->expectExceptionMessage("The requested object is encrypted with V1 encryption schemas that have been disabled by client configuration @SecurityProfile=V2"); + $this->expectException(\Aws\Exception\CryptoException::class); $kms = $this->getKmsClient(); $list = $kms->getHandlerList(); $list->setHandler(function($cmd, $req) { @@ -1003,12 +995,10 @@ public function testThrowsForV2ProfileAndLegacyObject() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage @SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY' - */ public function testThrowsForNoSecurityProfile() { + $this->expectExceptionMessage("@SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY'"); + $this->expectException(\Aws\Exception\CryptoException::class); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -1024,12 +1014,10 @@ public function testThrowsForNoSecurityProfile() ]); } - /** - * @expectedException \Aws\Exception\CryptoException - * @expectedExceptionMessage @SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY' - */ public function testThrowsForIncorrectSecurityProfile() { + $this->expectExceptionMessage("@SecurityProfile is required and must be set to 'V2' or 'V2_AND_LEGACY'"); + $this->expectException(\Aws\Exception\CryptoException::class); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -1058,7 +1046,7 @@ public function testAddsCryptoUserAgent() 'region' => 'us-west-2', 'version' => 'latest', 'http_handler' => function (RequestInterface $req) use ($provider) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionClientV2::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php index 97cc411f15..f99ef4916a 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php @@ -7,6 +7,7 @@ use Aws\Crypto\KmsMaterialsProvider; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTrait; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Psr7; @@ -14,7 +15,7 @@ class S3EncryptionMultipartUploaderTest extends TestCase { - use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTrait; + use PHPUnitCompatTrait, UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTrait; const MB = 1048576; const TEST_URL = 'http://foo.s3.amazonaws.com/bar'; @@ -451,7 +452,7 @@ public function testAddsCryptoUserAgent() ]); $list = $s3->getHandlerList(); $list->appendSign(Middleware::tap(function($cmd, $req) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionMultipartUploader::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php index 42273a4f76..c901f9c5b0 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php @@ -8,6 +8,7 @@ use Aws\Crypto\KmsMaterialsProviderV2; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTraitV2; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Psr7; @@ -16,7 +17,7 @@ class S3EncryptionMultipartUploaderV2Test extends TestCase { - use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTraitV2; + use PHPUnitCompatTrait, UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTraitV2; const MB = 1048576; const TEST_URL = 'http://foo.s3.amazonaws.com/bar'; @@ -502,7 +503,7 @@ public function testAddsCryptoUserAgent() ]); $list = $s3->getHandlerList(); $list->appendSign(Middleware::tap(function($cmd, $req) { - $this->assertContains( + $this->assertStringContainsString( 'feat/s3-encrypt/' . S3EncryptionMultipartUploaderV2::CRYPTO_VERSION, $req->getHeaderLine('User-Agent') ); diff --git a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php index ee8c02a60d..ade2ce7f5d 100644 --- a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php +++ b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\S3\Exception; use Aws\S3\Exception\DeleteMultipleObjectsException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class DeleteMultipleObjectsExceptionTest extends TestCase { + use PHPUnitCompatTrait; + public function testReturnsData() { $del = [['Key' => 'foo']]; @@ -16,7 +19,7 @@ public function testReturnsData() $e = new DeleteMultipleObjectsException($del, $err); $this->assertSame($del, $e->getDeleted()); $this->assertSame($err, $e->getErrors()); - $this->assertContains( + $this->assertStringContainsString( 'Unable to delete certain keys when executing a', $e->getMessage() ); diff --git a/tests/S3/MultipartUploaderTest.php b/tests/S3/MultipartUploaderTest.php index e0614b405d..1fda627565 100644 --- a/tests/S3/MultipartUploaderTest.php +++ b/tests/S3/MultipartUploaderTest.php @@ -4,6 +4,7 @@ use Aws\S3\MultipartUploader; use Aws\Result; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7; @@ -15,12 +16,13 @@ */ class MultipartUploaderTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; const MB = 1048576; const FILENAME = '_aws-sdk-php-s3-mup-test-dots.txt'; - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { @unlink(sys_get_temp_dir() . '/' . self::FILENAME); } @@ -31,7 +33,7 @@ public static function tearDownAfterClass() public function testS3MultipartUploadWorkflow( array $clientOptions = [], array $uploadOptions = [], - StreamInterface $source, + StreamInterface $source = null, $error = false ) { $client = $this->getTestClient('s3', $clientOptions); @@ -135,6 +137,7 @@ public function testCanUseCaseInsensitiveConfigKeys() $this->assertSame($configProp->getValue($classicMup), $configProp->getValue($putObjectMup)); } + /** @doesNotPerformAssertions */ public function testMultipartSuccessStreams() { $size = 12 * self::MB; @@ -265,12 +268,10 @@ public function testS3MultipartContentTypeSetting( $this->assertSame($url, $result['ObjectURL']); } - /** - * @expectedException \Aws\S3\Exception\S3MultipartUploadException - * @expectedExceptionMessage An exception occurred while uploading parts to a multipart upload - */ public function testAppliesAmbiguousSuccessParsing() { + $this->expectExceptionMessage("An exception occurred while uploading parts to a multipart upload"); + $this->expectException(\Aws\S3\Exception\S3MultipartUploadException::class); $counter = 0; $httpHandler = function ($request, array $options) use (&$counter) { diff --git a/tests/S3/PermanentRedirectMiddlewareTest.php b/tests/S3/PermanentRedirectMiddlewareTest.php index 894aa18b58..4ffb7c9ccd 100644 --- a/tests/S3/PermanentRedirectMiddlewareTest.php +++ b/tests/S3/PermanentRedirectMiddlewareTest.php @@ -1,27 +1,28 @@ expectExceptionMessage("Encountered a permanent redirect while requesting"); + $this->expectException(\Aws\S3\Exception\PermanentRedirectException::class); $s3 = $this->getTestClient('s3'); $this->addMockResults($s3, [['@metadata' => ['statusCode' => 301]]]); $s3->getObject(['Bucket' => 'test', 'Key' => 'key']); } + /** @doesNotPerformAssertions */ public function testPassesThroughUntouched() { $s3 = $this->getTestClient('s3'); diff --git a/tests/S3/PostObjectTest.php b/tests/S3/PostObjectTest.php index dafc598215..de31cff2bd 100644 --- a/tests/S3/PostObjectTest.php +++ b/tests/S3/PostObjectTest.php @@ -4,6 +4,7 @@ use Aws\Credentials\Credentials; use Aws\S3\PostObject; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -12,12 +13,13 @@ */ class PostObjectTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ protected $client; - public function setUp() + public function _setUp() { $this->client = $this->getTestClient( 's3', diff --git a/tests/S3/PostObjectV4Test.php b/tests/S3/PostObjectV4Test.php index 82ef1661f7..bb20c011b4 100644 --- a/tests/S3/PostObjectV4Test.php +++ b/tests/S3/PostObjectV4Test.php @@ -4,6 +4,7 @@ use Aws\Credentials\Credentials; use Aws\S3\PostObjectV4; use Aws\S3\S3Client; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; require_once __DIR__ . '/sig_hack.php'; @@ -14,12 +15,13 @@ */ class PostObjectV4Test extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ protected $client; - public function setUp() + public function _setUp() { $this->client = new S3Client([ 'version' => 'latest', @@ -30,6 +32,14 @@ public function setUp() ], ]); } + + public function _tearDown() + { + parent::tearDown(); + + unset($_SERVER['aws_time']); + } + /** * Executes the SigV4 POST example from the S3 documentation. * diff --git a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php index 43c6a6fbba..f6d6845496 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\S3\RegionalEndpoint\ConfigurationInterface; use Aws\S3\RegionalEndpoint\ConfigurationProvider; use Aws\S3\RegionalEndpoint\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', @@ -56,7 +59,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '=' . self::$originalEnv['endpoints_type']); @@ -155,21 +158,17 @@ public function testCreatesFromNonLowercaseValue() unlink($dir . '/config'); } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -183,12 +182,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -201,12 +198,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\RegionalEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\S3\RegionalEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -309,12 +304,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid S3 regional endpoint configuration argument. - */ public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid S3 regional endpoint configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/S3/RegionalEndpoint/ConfigurationTest.php b/tests/S3/RegionalEndpoint/ConfigurationTest.php index 367a5f7e72..585e87a3f0 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\S3\RegionalEndpoint; use Aws\Sts\RegionalEndpoints\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('regional'); @@ -31,12 +34,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new Configuration('invalid_type'); } } diff --git a/tests/S3/RetryableMalformedResponseParserTest.php b/tests/S3/RetryableMalformedResponseParserTest.php index 498dc1db0f..82997ee344 100644 --- a/tests/S3/RetryableMalformedResponseParserTest.php +++ b/tests/S3/RetryableMalformedResponseParserTest.php @@ -6,17 +6,18 @@ use Aws\CommandInterface; use Aws\S3\Exception\S3Exception; use Aws\S3\RetryableMalformedResponseParser; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\ResponseInterface; use PHPUnit\Framework\TestCase; class RetryableMalformedResponseParserTest extends TestCase { - /** - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage Sorry! - */ + use PHPUnitCompatTrait; + public function testConvertsParserExceptionsToRetryableExceptions() { + $this->expectExceptionMessage("Sorry!"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $parser = function () { throw new ParserException('Sorry!'); }; $instance = new RetryableMalformedResponseParser( diff --git a/tests/S3/S3ClientTest.php b/tests/S3/S3ClientTest.php index 5821ce1b3a..5c00ac551b 100644 --- a/tests/S3/S3ClientTest.php +++ b/tests/S3/S3ClientTest.php @@ -15,6 +15,7 @@ use Aws\S3\S3Client; use Aws\S3\UseArnRegion\Configuration as UseArnRegionConfiguration; use Aws\Signature\SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; @@ -35,6 +36,7 @@ */ class S3ClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testCanUseBucketEndpoint() @@ -89,9 +91,9 @@ public function testCreatesPresignedRequests() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://foo.s3.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsWithAccessPointArn() @@ -110,9 +112,9 @@ public function testCreatesPresignedRequestsWithAccessPointArn() ); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://myendpoint-123456789012.s3-accesspoint.us-east-1.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsWithStartTime() @@ -129,9 +131,9 @@ public function testCreatesPresignedRequestsWithStartTime() ['start_time' => 1562349366] )->getUri(); $this->assertStringStartsWith('https://foo.s3.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=1200', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=61a9940ecdd901be8e36833f6d47123c0c719fc6aa82042144a6c5cf44a25988', $url); + $this->assertStringContainsString('X-Amz-Expires=1200', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=61a9940ecdd901be8e36833f6d47123c0c719fc6aa82042144a6c5cf44a25988', $url); } public function testCreatesPresignedRequestsWithPathStyleFallback() @@ -144,9 +146,9 @@ public function testCreatesPresignedRequestsWithPathStyleFallback() $command = $client->getCommand('GetObject', ['Bucket' => 'foo.baz', 'Key' => 'bar']); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://s3.amazonaws.com/foo.baz/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsWithPathStyle() @@ -160,9 +162,9 @@ public function testCreatesPresignedRequestsWithPathStyle() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://s3.amazonaws.com/foo/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatingPresignedUrlDoesNotPermanentlyRemoveSigner() @@ -414,12 +416,10 @@ public function testReturnsObjectUrlViaPathWithPathStyle() ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The DeleteObject operation requires non-empty parameter: Bucket - */ public function testEnsuresMandatoryInputVariables() { + $this->expectExceptionMessage("The DeleteObject operation requires non-empty parameter: Bucket"); + $this->expectException(\InvalidArgumentException::class); /** @var S3Client $client */ $client = $this->getTestClient('S3'); $client->deleteObject([ @@ -428,11 +428,9 @@ public function testEnsuresMandatoryInputVariables() ); } - /** - * @expectedException \RuntimeException - */ public function testEnsuresPrefixOrRegexSuppliedForDeleteMatchingObjects() { + $this->expectException(\RuntimeException::class); /** @var S3Client $client */ $client = $this->getTestClient('S3'); $client->deleteMatchingObjects('foo'); @@ -470,42 +468,34 @@ public function testDeletesMatchingObjectsByPrefixAndRegex() $this->assertEquals(['foo/bar/baz', 'foo/bar/bam'], $agg); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a PutObject - */ public function testProxiesToTransferObjectPut() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a PutObject"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->uploadDirectory(__DIR__, 'test'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a ListObjects - */ public function testProxiesToTransferObjectGet() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a ListObjects"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->downloadBucket(__DIR__, 'test'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a PutObject - */ public function testProxiesToObjectUpload() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a PutObject"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->upload('bucket', 'key', 'body'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Mock queue is empty. Trying to send a HeadObject - */ public function testProxiesToObjectCopy() { + $this->expectExceptionMessage("Mock queue is empty. Trying to send a HeadObject"); + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('S3'); $client->copy('from-bucket', 'fromKey', 'to-bucket', 'toKey'); } @@ -525,9 +515,9 @@ public function testAddsLocationConstraintAutomatically($region, $target, $comma $text = "{$target}"; $body = (string) \Aws\serialize($command)->getBody(); if ($contains) { - $this->assertContains($text, $body); + $this->assertStringContainsString($text, $body); } else { - $this->assertNotContains($text, $body); + $this->assertStringNotContainsString($text, $body); } } @@ -567,7 +557,7 @@ public function testRequestSucceedsWithColon() $key = 'aaa:bbb'; $s3 = $this->getTestClient('S3', [ 'http_handler' => function (RequestInterface $request) use ($key) { - $this->assertContains( + $this->assertStringContainsString( urlencode($key), (string) $request->getUri() ); @@ -880,12 +870,11 @@ private function getWellFormedXml() * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessageRegExp /Your socket connection to the server/ */ public function testClientSocketTimeoutErrorsAreNotRetriedIndefinitely($retrySettings) { + $this->expectExceptionMessageMatches("/Your socket connection to the server/"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $client = new S3Client([ 'version' => 'latest', 'region' => 'us-west-2', @@ -963,12 +952,11 @@ public function testNetworkingErrorsAreRetriedOnIdempotentCommands($retrySetting * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - * - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessageRegExp /CompleteMultipartUpload/ */ public function testNetworkingErrorsAreNotRetriedOnNonIdempotentCommands($retrySettings) { + $this->expectExceptionMessageMatches("/CompleteMultipartUpload/"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $networkingError = $this->getMockBuilder(RequestException::class) ->disableOriginalConstructor() ->setMethods([]) @@ -1232,11 +1220,9 @@ public function testCanDetermineRegionOfBucket() $this->assertSame('us-west-2', $client->determineBucketRegion('bucket')); } - /** - * @expectedException \Aws\Exception\AwsException - */ public function testDetermineBucketRegionExposeException() { + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -1477,12 +1463,10 @@ public function testAppliesS3EndpointMiddlewareDualstackWithPathStyle() ]); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid configuration value provided for "use_arn_region" - */ public function testAddsUseArnRegionArgument() { + $this->expectExceptionMessage("Invalid configuration value provided for \"use_arn_region\""); + $this->expectException(\InvalidArgumentException::class); new S3Client([ 'region' => 'us-east-1', 'version' => 'latest', @@ -1557,12 +1541,10 @@ public function testCopyOperationCorrectlyPopulates() $client->execute($command); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testAddsS3RegionalEndpointArgument() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new S3Client([ 'region' => 'us-east-1', 'version' => 'latest', @@ -1695,12 +1677,10 @@ public function optionsToEndpointsCases() ]; } - /** - * @expectedException \Aws\S3\Exception\S3Exception - * @expectedExceptionMessage An error connecting to the service occurred while performing the CopyObject operation - */ public function testAppliesAmbiguousSuccessParsing() { + $this->expectExceptionMessage("An error connecting to the service occurred while performing the CopyObject operation"); + $this->expectException(\Aws\S3\Exception\S3Exception::class); $httpHandler = function ($request, array $options) { return Promise\Create::promiseFor( new Psr7\Response(200, [], "\n\n\n") @@ -1856,7 +1836,7 @@ public function testMrapExceptions( $e instanceof UnresolvedEndpointException || $e instanceof S3Exception ); - self::assertContains($expectedException, $e->getMessage()); + self::assertStringContainsString($expectedException, $e->getMessage()); } } @@ -1900,7 +1880,7 @@ public function testAccessPointFailures ( $e instanceof UnresolvedEndpointException || $e instanceof S3Exception ); - self::assertContains($expectedException, $e->getMessage()); + self::assertStringContainsString($expectedException, $e->getMessage()); } } public function AccessPointFailureProvider() @@ -1958,7 +1938,7 @@ public function testPresignedMrapFailure (){ self::fail("exception should have been thrown"); } catch (\Exception $e) { self::assertTrue($e instanceof UnresolvedEndpointException); - self::assertContains($expectedException, $e->getMessage()); + self::assertStringContainsString($expectedException, $e->getMessage()); } } diff --git a/tests/S3/S3EndpointMiddlewareTest.php b/tests/S3/S3EndpointMiddlewareTest.php index 873c7bee32..30ede0aa0b 100644 --- a/tests/S3/S3EndpointMiddlewareTest.php +++ b/tests/S3/S3EndpointMiddlewareTest.php @@ -6,6 +6,7 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\S3\S3EndpointMiddleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Request; @@ -15,6 +16,7 @@ class S3EndpointMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -396,8 +398,8 @@ private function noAcceleratePatternAssertingHandler(CommandInterface $command, CommandInterface $toHandle, RequestInterface $req ) use ($command, $pattern) { - $this->assertNotContains($pattern, (string)$req->getUri()); - $this->assertContains($command['Bucket'], $req->getUri()->getHost()); + $this->assertStringNotContainsString($pattern, (string)$req->getUri()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getHost()); }; } @@ -411,7 +413,7 @@ private function acceleratePatternAssertingHandler(CommandInterface $command, $p "{$command['Bucket']}.{$pattern}.amazonaws.com", $req->getUri()->getHost() ); - $this->assertNotContains($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringNotContainsString($command['Bucket'], $req->getUri()->getPath()); }; } @@ -425,8 +427,8 @@ private function dualStackAssertingHandler(CommandInterface $command) "bucket.s3.dualstack.us-west-2.amazonaws.com", $req->getUri()->getHost() ); - $this->assertNotContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringNotContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -440,8 +442,8 @@ private function dualStackPathStyleFallbackAssertingHandler(CommandInterface $co "s3.dualstack.us-west-2.amazonaws.com", $req->getUri()->getHost() ); - $this->assertContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -455,8 +457,8 @@ private function dualStackWithPathStyleAssertingHandler(CommandInterface $comman "s3.dualstack.us-west-2.amazonaws.com", $req->getUri()->getHost() ); - $this->assertContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -466,9 +468,9 @@ private function noDualStackAssertingHandler(CommandInterface $command) CommandInterface $cmd, RequestInterface $req ) use ($command) { - $this->assertNotContains('s3.dualstack', (string)$req->getUri()); - $this->assertContains($command['Bucket'], $req->getUri()->getHost()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringNotContainsString('s3.dualstack', (string)$req->getUri()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getHost()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -482,8 +484,8 @@ private function ipAddressPathStyleFallbackAssertingHandler(CommandInterface $co "127.250.250.250", $req->getUri()->getHost() ); - $this->assertContains($command['Bucket'], $req->getUri()->getPath()); - $this->assertContains('key=query', $req->getUri()->getQuery()); + $this->assertStringContainsString($command['Bucket'], $req->getUri()->getPath()); + $this->assertStringContainsString('key=query', $req->getUri()->getQuery()); }; } @@ -660,7 +662,7 @@ public function testObjectLambdaArnFailures( $client->execute($command); $this->fail("did not catch exception: " . $expectedException); } catch (\Exception $e) { - $this->assertContains($expectedException, $e->getMessage()); + $this->assertStringContainsString($expectedException, $e->getMessage()); } } diff --git a/tests/S3/S3MultiRegionClientTest.php b/tests/S3/S3MultiRegionClientTest.php index f015b5ae8a..a1fb4c24ca 100644 --- a/tests/S3/S3MultiRegionClientTest.php +++ b/tests/S3/S3MultiRegionClientTest.php @@ -8,6 +8,7 @@ use Aws\ResultInterface; use Aws\S3\S3ClientInterface; use Aws\S3\S3MultiRegionClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7; @@ -19,6 +20,7 @@ class S3MultiRegionClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testWillRecoverFromPermanentRedirect() @@ -107,17 +109,15 @@ public function testCreatesPresignedRequestsForCorrectRegion() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string)$client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://foo.s3.us-west-2.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /AWS HTTP error/ - */ public function testRethrowsOnNoResponseException() { + $this->expectExceptionMessageMatches("/AWS HTTP error/"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', @@ -139,12 +139,10 @@ public function testRethrowsOnNoResponseException() $client->createPresignedRequest($command, 1342138769)->getUri(); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /The authorization header is malformed/ - */ public function testRethrowsOnAuthHeaderMalformedWithoutRegion() { + $this->expectExceptionMessageMatches("/The authorization header is malformed/"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', @@ -194,9 +192,9 @@ public function testRedirectsOnNonRedirectExceptionWithHeader() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string)$client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://foo.s3.us-west-2.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesPresignedRequestsForCorrectRegionWithPathStyle() @@ -218,9 +216,9 @@ public function testCreatesPresignedRequestsForCorrectRegionWithPathStyle() $command = $client->getCommand('GetObject', ['Bucket' => 'foo', 'Key' => 'bar']); $url = (string)$client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://s3.us-west-2.amazonaws.com/foo/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testCreatesObjectUrlsForCorrectRegion() @@ -291,12 +289,10 @@ public function testCachesBucketLocation() $this->assertSame('us-west-2', $this->readAttribute($client, 'cache')->get('aws:s3:foo:location')); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /Your socket connection to the server was not read from or written to within the timeout period./ - */ public function testRethrowsAwsExceptionViaMiddleware() { + $this->expectExceptionMessageMatches("/Your socket connection to the server was not read from or written to within the timeout period./"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', @@ -318,12 +314,10 @@ public function testRethrowsAwsExceptionViaMiddleware() $client->getObject(['Bucket' => 'foo', 'Key' => 'bar']); } - /** - * @expectedException \Aws\Exception\AwsException - * @expectedExceptionMessageRegExp /The authorization header is malformed/ - */ public function testRethrowsOnAuthHeaderMalformedWithoutRegionViaMiddleware() { + $this->expectExceptionMessageMatches("/The authorization header is malformed/"); + $this->expectException(\Aws\Exception\AwsException::class); $client = new S3MultiRegionClient([ 'region' => 'us-east-1', 'version' => 'latest', diff --git a/tests/S3/S3UriParserTest.php b/tests/S3/S3UriParserTest.php index aa15364e4a..73525d70ff 100644 --- a/tests/S3/S3UriParserTest.php +++ b/tests/S3/S3UriParserTest.php @@ -3,6 +3,7 @@ use Aws\Arn\Exception\InvalidArnException; use Aws\S3\S3UriParser; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class S3UriParserTest extends TestCase { + use PHPUnitCompatTrait; + public function uriProvider() { return [ @@ -101,10 +104,12 @@ public function testParsesUrls($uri, $result, $isError = false) ksort($actual); $this->assertSame($result, $actual); } catch (\InvalidArgumentException $e) { + $this->expectNotToPerformAssertions(); if (!$isError) { throw $e; } } catch (InvalidArnException $e) { + $this->expectNotToPerformAssertions(); if (!$isError) { throw $e; } diff --git a/tests/S3/SSECMiddlewareTest.php b/tests/S3/SSECMiddlewareTest.php index 86b54d84cc..a988d19109 100644 --- a/tests/S3/SSECMiddlewareTest.php +++ b/tests/S3/SSECMiddlewareTest.php @@ -3,6 +3,7 @@ use Aws\Middleware; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -11,6 +12,7 @@ */ class SSECMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @@ -75,11 +77,9 @@ public function getListenerTestCases() ]; } - /** - * @expectedException \RuntimeException - */ public function testCannotUseWithoutHttps() { + $this->expectException(\RuntimeException::class); $client = $this->getTestClient('s3', ['scheme' => 'http']); $client->listBuckets([ 'SSECustomerKey' => 'foo', @@ -87,6 +87,7 @@ public function testCannotUseWithoutHttps() ]); } + /** @doesNotPerformAssertions */ public function testCanUseWithoutHttpsForNonSse() { $client = $this->getTestClient('s3', ['scheme' => 'http']); diff --git a/tests/S3/StreamWrapperPathStyleTest.php b/tests/S3/StreamWrapperPathStyleTest.php index a1b4d4f10a..162070dfc7 100644 --- a/tests/S3/StreamWrapperPathStyleTest.php +++ b/tests/S3/StreamWrapperPathStyleTest.php @@ -9,6 +9,7 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -18,6 +19,7 @@ */ class StreamWrapperPathStyleTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -26,7 +28,7 @@ class StreamWrapperPathStyleTest extends TestCase /** @var LruArrayCache */ private $cache; - public function setUp() + public function _setUp() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -38,7 +40,7 @@ public function setUp() $this->client->registerStreamWrapper(); } - public function tearDown() + public function _tearDown() { stream_wrapper_unregister('s3'); $this->client = null; @@ -51,34 +53,29 @@ public function testRegistersStreamWrapperOnlyOnce() StreamWrapper::register($this->client); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Cannot open a bucket - */ public function testCannotOpenBuckets() { + $this->expectExceptionMessage("Cannot open a bucket"); + $this->expectWarning(); fopen('s3://bucket', 'r'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Mode not supported - */ public function testSupportsOnlyReadWriteXA() { + $this->expectExceptionMessage("Mode not supported"); + $this->expectWarning(); fopen('s3://bucket/key', 'c'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage s3://bucket/key already exists on Amazon S3 - */ 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'); } + /** @doesNotPerformAssertions */ public function testSuccessfulXMode() { $this->addMockResults( @@ -173,12 +170,10 @@ public function testCanOpenWriteOnlyStreams() $this->assertSame('test', (string) $cmd['Body']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } ]); @@ -244,12 +239,10 @@ public function testCanUnlinkFiles() $this->assertSame('s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testThrowsErrorsWhenUnlinkFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -261,22 +254,18 @@ public function testCreatingBucketWithNoBucketReturnsFalse() $this->assertFalse(mkdir('s3://')); } - /** - * @expectedExceptionMessage Bucket already exists: s3://already-existing-bucket - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Bucket already exists: s3://already-existing-bucket"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket'); } - /** - * @expectedExceptionMessage Subfolder already exists: s3://already-existing-bucket/key - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketForKeyRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Subfolder already exists: s3://already-existing-bucket/key"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket/key'); } @@ -329,24 +318,20 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $entries = $history->toArray(); $this->assertSame('HEAD', $entries[0]['request']->getMethod()); $this->assertSame('PUT', $entries[1]['request']->getMethod()); - $this->assertContains('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); + $this->assertStringContainsString('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage specify a bucket - */ public function testCannotDeleteS3() { + $this->expectExceptionMessage("specify a bucket"); + $this->expectWarning(); rmdir('s3://'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testRmDirWithExceptionTriggersError() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -386,7 +371,7 @@ public function testCanDeleteObjectWithRmDir($path) $this->assertCount(1, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); } public function testCanDeleteNestedFolderWithRmDir() @@ -406,36 +391,30 @@ public function testCanDeleteNestedFolderWithRmDir() $this->assertCount(2, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); $this->assertSame('DELETE', $entries[1]['request']->getMethod()); $this->assertSame('/foo/bar/', $entries[1]['request']->getUri()->getPath()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage rename(): Cannot rename a file across wrapper types - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage The Amazon S3 stream wrapper only supports copying objects - */ public function testRenameEnsuresKeyIsSet() { + $this->expectExceptionMessage("The Amazon S3 stream wrapper only supports copying objects"); + $this->expectWarning(); rename('s3://foo/bar', 's3://baz'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ public function testRenameWithExceptionThrowsError() { + $this->expectExceptionMessage("Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -532,12 +511,10 @@ public function testCanPullStatDataFromCache() $this->assertSame(123, filesize('s3://foo/bar')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ 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); }, @@ -547,12 +524,10 @@ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } stat('s3://bucket/key'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket - */ 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); }, ]); @@ -594,12 +569,10 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $this->assertSame(0040777, $stat['mode']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket/prefix - */ 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() @@ -669,12 +642,16 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) $this->assertCount(count($queue), $history); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage cannot represent a stream of type user-space - */ 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->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) ]); @@ -684,12 +661,10 @@ public function testStreamCastIsNotPossible() stream_select($read, $write, $except, 0); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage No client in stream context - */ public function testEnsuresClientIsSet() { + $this->expectExceptionMessage("No client in stream context"); + $this->expectWarning(); fopen('s3://bucket/key', 'r', false, stream_context_create([ 's3' => ['client' => null] ])); @@ -708,7 +683,7 @@ public function testDoesNotErrorOnFileExists() $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('404', $cmd); }, ]); - $this->assertFileNotExists('s3://bucket/key'); + $this->assertFileDoesNotExist('s3://bucket/key'); } public function testProvidesDirectoriesForS3() @@ -775,7 +750,7 @@ public function testProvidesDirectoriesForS3() $dir = 's3://bucket/key/'; $r = opendir($dir); - $this->assertInternalType('resource', $r); + $this->assertIsResource($r); $files = []; while (($file = readdir($r)) !== false) { @@ -793,6 +768,7 @@ public function testProvidesDirectoriesForS3() closedir($r); } + /** @doesNotPerformAssertions */ public function testCanSetDelimiterStreamContext() { $this->addMockResults($this->client, [ diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index 03f9640b6d..3cbc902d51 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -9,6 +9,7 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; @@ -19,6 +20,7 @@ */ class StreamWrapperTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -27,7 +29,7 @@ class StreamWrapperTest extends TestCase /** @var LruArrayCache */ private $cache; - public function setUp() + public function _setUp() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -36,7 +38,7 @@ public function setUp() $this->client->registerStreamWrapper(); } - public function tearDown() + public function _tearDown() { stream_wrapper_unregister('s3'); $this->client = null; @@ -49,43 +51,36 @@ public function testRegistersStreamWrapperOnlyOnce() StreamWrapper::register($this->client); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Cannot open a bucket - */ public function testCannotOpenBuckets() { + $this->expectExceptionMessage("Cannot open a bucket"); + $this->expectWarning(); fopen('s3://bucket', 'r'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Mode not supported - */ public function testSupportsOnlyReadWriteXA() { + $this->expectExceptionMessage("Mode not supported"); + $this->expectWarning(); fopen('s3://bucket/key', 'c'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage s3://bucket/key already exists on Amazon S3 - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Bucket parameter parsed as ARN and failed with: Provided ARN was not a valid S3 access point ARN - */ public function testValidatesArn() { + $this->expectExceptionMessage("Bucket parameter parsed as ARN and failed with: Provided ARN was not a valid S3 access point ARN"); + $this->expectWarning(); fopen('s3://arn:aws:s3:us-east-1:123456789012:foo:myaccess/test_key', 'r'); } + /** @doesNotPerformAssertions */ public function testSuccessfulXMode() { $this->addMockResults( @@ -285,12 +280,10 @@ public function testCanWriteEmptyFileToStream() $this->assertSame('', (string) $cmd['Body']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } ]); @@ -356,12 +349,10 @@ public function testCanUnlinkFiles() $this->assertSame('bucket.s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testThrowsErrorsWhenUnlinkFails() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -373,22 +364,18 @@ public function testCreatingBucketWithNoBucketReturnsFalse() $this->assertFalse(mkdir('s3://')); } - /** - * @expectedExceptionMessage Bucket already exists: s3://already-existing-bucket - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Bucket already exists: s3://already-existing-bucket"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket'); } - /** - * @expectedExceptionMessage Subfolder already exists: s3://already-existing-bucket/key - * @expectedException \PHPUnit\Framework\Error\Warning - */ public function testCreatingAlreadyExistingBucketForKeyRaisesError() { + $this->expectWarning(); + $this->expectExceptionMessage("Subfolder already exists: s3://already-existing-bucket/key"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket/key'); } @@ -441,24 +428,20 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $entries = $history->toArray(); $this->assertSame('HEAD', $entries[0]['request']->getMethod()); $this->assertSame('PUT', $entries[1]['request']->getMethod()); - $this->assertContains('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); + $this->assertStringContainsString('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage specify a bucket - */ public function testCannotDeleteS3() { + $this->expectExceptionMessage("specify a bucket"); + $this->expectWarning(); rmdir('s3://'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testRmDirWithExceptionTriggersError() { + $this->expectExceptionMessage("403 Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -498,7 +481,7 @@ public function testCanDeleteObjectWithRmDir($path) $this->assertCount(1, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); } public function testCanDeleteNestedFolderWithRmDir() @@ -518,37 +501,31 @@ public function testCanDeleteNestedFolderWithRmDir() $this->assertCount(2, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); $this->assertSame('DELETE', $entries[1]['request']->getMethod()); $this->assertSame('/bar/', $entries[1]['request']->getUri()->getPath()); - $this->assertContains('foo', $entries[1]['request']->getUri()->getHost()); + $this->assertStringContainsString('foo', $entries[1]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage rename(): Cannot rename a file across wrapper types - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage The Amazon S3 stream wrapper only supports copying objects - */ public function testRenameEnsuresKeyIsSet() { + $this->expectExceptionMessage("The Amazon S3 stream wrapper only supports copying objects"); + $this->expectWarning(); rename('s3://foo/bar', 's3://baz'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ public function testRenameWithExceptionThrowsError() { + $this->expectExceptionMessage("Forbidden"); + $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -646,12 +623,10 @@ public function testCanPullStatDataFromCache() $this->assertSame(123, filesize('s3://foo/bar')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ 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); }, @@ -661,12 +636,10 @@ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } stat('s3://bucket/key'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket - */ 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); }, ]); @@ -708,12 +681,10 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, $this->assertSame(0040777, $stat['mode']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket/prefix - */ 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() @@ -783,12 +754,16 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) $this->assertCount(count($queue), $history); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage cannot represent a stream of type user-space - */ 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->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) ]); @@ -798,12 +773,10 @@ public function testStreamCastIsNotPossible() stream_select($read, $write, $except, 0); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage No client in stream context - */ public function testEnsuresClientIsSet() { + $this->expectExceptionMessage("No client in stream context"); + $this->expectWarning(); fopen('s3://bucket/key', 'r', false, stream_context_create([ 's3' => ['client' => null] ])); @@ -822,7 +795,7 @@ public function testDoesNotErrorOnFileExists() $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('404', $cmd); }, ]); - $this->assertFileNotExists('s3://bucket/key'); + $this->assertFileDoesNotExist('s3://bucket/key'); } public function testProvidesDirectoriesForS3() @@ -889,7 +862,7 @@ public function testProvidesDirectoriesForS3() $dir = 's3://bucket/key/'; $r = opendir($dir); - $this->assertInternalType('resource', $r); + $this->assertIsResource($r); $files = []; while (($file = readdir($r)) !== false) { @@ -907,6 +880,7 @@ public function testProvidesDirectoriesForS3() closedir($r); } + /** @doesNotPerformAssertions */ public function testCanSetDelimiterStreamContext() { $this->addMockResults($this->client, [ diff --git a/tests/S3/TransferTest.php b/tests/S3/TransferTest.php index 0ebf8474d3..99f74c5740 100644 --- a/tests/S3/TransferTest.php +++ b/tests/S3/TransferTest.php @@ -6,6 +6,7 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\S3\Transfer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; @@ -17,75 +18,61 @@ */ class TransferTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage base_dir - */ public function testEnsuresBaseDirIsAvailable() { + $this->expectExceptionMessage("base_dir"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, new \ArrayIterator([]), 's3://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot copy from s3 to s3. - */ public function testCannotCopyS3ToS3() { + $this->expectExceptionMessage("You cannot copy from s3 to s3."); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, 's3://baz/bam', 's3://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot copy from file to file. - */ public function testCannotCopyLocal() { + $this->expectExceptionMessage("You cannot copy from file to file."); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, __DIR__); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage mup_threshold must be >= 5MB - */ public function testEnsuresMupSizeIsValid() { + $this->expectExceptionMessage("mup_threshold must be >= 5MB"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, 's3://foo/bar', ['mup_threshold' => 10]); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage source must be the path to a directory or an - * iterator that yields file names - */ public function testEnsuresSourceIsValid() { + $this->expectExceptionMessage("source must be the path to a directory or an iterator that yields file names"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, false, 's3://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Scheme must be "s3" or "file" - */ public function testEnsuresValidScheme() { + $this->expectExceptionMessage("Scheme must be \"s3\" or \"file\""); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, 'monkey://foo/bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage before must be a callable - */ public function testEnsuresBeforeIsCallable() { + $this->expectExceptionMessage("before must be a callable"); + $this->expectException(\InvalidArgumentException::class); $s3 = $this->getTestClient('s3'); new Transfer($s3, __DIR__, 's3://foo/bar', ['before' => 'cheese']); } @@ -123,7 +110,7 @@ public function testCanSetBeforeOptionForUploadsAndUsedWithDebug() $this->assertSame('PutObject', $test->getName()); $this->assertSame('foo', $test['Bucket']); $this->assertStringStartsWith('bar/', $test['Key']); - $this->assertContains($test['SourceFile'] . ' -> s3://foo/bar', $output); + $this->assertStringContainsString($test['SourceFile'] . ' -> s3://foo/bar', $output); } } @@ -157,7 +144,7 @@ public function testDoesMultipartForLargeFiles() $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); + $this->assertStringContainsString("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); `rm -rf $dir`; } @@ -191,7 +178,7 @@ public function testDoesMultipartForLargeFilesWithFileInfoAsSource() $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); + $this->assertStringContainsString("Transferring $filename -> s3://foo/bar/large.txt (UploadPart) : Part=1", $output); `rm -rf $dir`; } @@ -218,7 +205,7 @@ public function testDownloadsObjects() $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains('s3://foo/bar/c//d -> ', $output); + $this->assertStringContainsString('s3://foo/bar/c//d -> ', $output); `rm -rf $dir`; } @@ -283,19 +270,18 @@ function (CommandInterface $cmd, RequestInterface $req) { $t->transfer(); rewind($res); $output = stream_get_contents($res); - $this->assertContains('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/../bar/a/b -> ', $output); - $this->assertContains('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/c//d -> ', $output); - $this->assertContains('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/../bar//c/../a/b/.. -> ', $output); + $this->assertStringContainsString('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/../bar/a/b -> ', $output); + $this->assertStringContainsString('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/bar/c//d -> ', $output); + $this->assertStringContainsString('s3://arn:aws:s3:us-east-1:123456789012:accesspoint:myaccess/../bar//c/../a/b/.. -> ', $output); `rm -rf $dir`; } /** * @dataProvider providedPathsOutsideTarget - * - * @expectedException \Aws\Exception\AwsException */ public function testCannotDownloadObjectsOutsideTarget($key) { + $this->expectException(\Aws\Exception\AwsException::class); $s3 = $this->getTestClient('s3'); $lso = [ 'IsTruncated' => false, diff --git a/tests/S3/UseArnRegion/ConfigurationProviderTest.php b/tests/S3/UseArnRegion/ConfigurationProviderTest.php index 895aa13440..b61a9c27d1 100644 --- a/tests/S3/UseArnRegion/ConfigurationProviderTest.php +++ b/tests/S3/UseArnRegion/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\S3\UseArnRegion\ConfigurationInterface; use Aws\S3\UseArnRegion\ConfigurationProvider; use Aws\S3\UseArnRegion\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_ARN_REGION) ?: '', @@ -53,7 +56,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_ARN_REGION . '=' . self::$originalEnv['use_arn_region']); @@ -168,21 +171,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -196,12 +195,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -214,12 +211,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -288,11 +283,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } diff --git a/tests/S3/UseArnRegion/ConfigurationTest.php b/tests/S3/UseArnRegion/ConfigurationTest.php index 760a75d405..d7d69bbf4a 100644 --- a/tests/S3/UseArnRegion/ConfigurationTest.php +++ b/tests/S3/UseArnRegion/ConfigurationTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\S3\UseArnRegion; use Aws\S3\UseArnRegion\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider correctValueCases * @@ -44,12 +47,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\S3\UseArnRegion\Exception\ConfigurationException - * @expectedExceptionMessage 'use_arn_region' config option must be a boolean value. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectExceptionMessage("'use_arn_region' config option must be a boolean value."); + $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); new Configuration('not a boolean'); } } diff --git a/tests/S3Control/EndpointArnMiddlewareTest.php b/tests/S3Control/EndpointArnMiddlewareTest.php index 21e95ba2cf..4f02d08544 100644 --- a/tests/S3Control/EndpointArnMiddlewareTest.php +++ b/tests/S3Control/EndpointArnMiddlewareTest.php @@ -6,6 +6,7 @@ use Aws\Exception\InvalidRegionException; use Aws\Exception\UnresolvedEndpointException; use Aws\Middleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\S3Control\S3ControlTestingTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Response; @@ -17,6 +18,7 @@ */ class EndpointArnMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; use S3ControlTestingTrait; /** @@ -58,7 +60,7 @@ public function testCorrectlyModifiesRequestAndCommand( $req->getUri()->getHost() ); $this->assertSame("/{$target}", $req->getRequestTarget()); - $this->assertContains( + $this->assertStringContainsString( "/{$signingRegion}/{$signingService}", $req->getHeader('Authorization')[0] ); diff --git a/tests/SdkTest.php b/tests/SdkTest.php index 66975b9270..e000f7df33 100644 --- a/tests/SdkTest.php +++ b/tests/SdkTest.php @@ -5,6 +5,7 @@ use Aws\MultiRegionClient; use Aws\S3\S3MultiRegionClient; use Aws\Sdk; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -12,11 +13,11 @@ */ class SdkTest extends TestCase { - /** - * @expectedException \BadMethodCallException - */ + use PHPUnitCompatTrait; + public function testEnsuresMissingMethodThrowsException() { + $this->expectException(\BadMethodCallException::class); (new Sdk)->foo(); } diff --git a/tests/Signature/S3SignatureV4Test.php b/tests/Signature/S3SignatureV4Test.php index 76f68a591e..0cf7198ac6 100644 --- a/tests/Signature/S3SignatureV4Test.php +++ b/tests/Signature/S3SignatureV4Test.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Signature\S3SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; require_once __DIR__ . '/sig_hack.php'; @@ -13,11 +14,18 @@ */ class S3SignatureV4Test extends TestCase { - public static function setUpBeforeClass() + use PHPUnitCompatTrait; + + public static function _setUpBeforeClass() { $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC'); } + public static function _tearDownAfterClass() + { + unset($_SERVER['aws_time']); + } + private function getFixtures() { $request = new Request('GET', 'http://foo.com'); @@ -90,7 +98,7 @@ public function testCreatesPresignedDatesFromDateTime() $credentials, new \DateTime('December 11, 2013 00:00:00 UTC') )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testCreatesPresignedDatesFromUnixTimestamp() @@ -101,7 +109,7 @@ public function testCreatesPresignedDatesFromUnixTimestamp() $credentials, 1386720000 )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testCreatesPresignedDateFromStrtotime() @@ -112,7 +120,7 @@ public function testCreatesPresignedDateFromStrtotime() $credentials, 'December 11, 2013 00:00:00 UTC' )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testCreatesPresignedDateFromStrtotimeRelativeTimeBase() @@ -124,7 +132,7 @@ public function testCreatesPresignedDateFromStrtotimeRelativeTimeBase() '+6 days', ['start_time' => $_SERVER['aws_time']] )->getUri(); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testAddsSecurityTokenIfPresent() @@ -140,8 +148,8 @@ public function testAddsSecurityTokenIfPresent() $credentials, 1386720000 )->getUri(); - $this->assertContains('X-Amz-Security-Token=123', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Security-Token=123', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testUsesStartDateIfSpecified() @@ -152,15 +160,13 @@ public function testUsesStartDateIfSpecified() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresSigV4DurationIsLessThanOneWeek() { + $this->expectException(\InvalidArgumentException::class); list($request, $credentials, $signature) = $this->getFixtures(); $signature->presign( $request, diff --git a/tests/Signature/SignatureProviderTest.php b/tests/Signature/SignatureProviderTest.php index b50cfee170..e04fb2cd94 100644 --- a/tests/Signature/SignatureProviderTest.php +++ b/tests/Signature/SignatureProviderTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Signature; use Aws\Signature\SignatureProvider; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class SignatureProviderTest extends TestCase { + use PHPUnitCompatTrait; + public function versionProvider() { return [ @@ -53,11 +56,9 @@ public function testResolvesSignaturesSuccessfully() ); } - /** - * @expectedException \Aws\Exception\UnresolvedSignatureException - */ public function testResolvesSignaturesWithException() { + $this->expectException(\Aws\Exception\UnresolvedSignatureException::class); $fn = SignatureProvider::defaultProvider(); SignatureProvider::resolve($fn, 'foooo', '', ''); } diff --git a/tests/Signature/SignatureV4Test.php b/tests/Signature/SignatureV4Test.php index a746107ba2..0ccb6ffad8 100644 --- a/tests/Signature/SignatureV4Test.php +++ b/tests/Signature/SignatureV4Test.php @@ -3,6 +3,7 @@ use Aws\Credentials\Credentials; use Aws\Signature\SignatureV4; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\NoSeekStream; @@ -15,15 +16,24 @@ */ class SignatureV4Test extends TestCase { + use PHPUnitCompatTrait; + const DEFAULT_KEY = 'AKIDEXAMPLE'; const DEFAULT_SECRET = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'; const DEFAULT_DATETIME = 'Mon, 09 Sep 2011 23:36:00 GMT'; - public function setup() + public function _setUp() { $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC'); } + public function _tearDown() + { + parent::tearDown(); + + unset($_SERVER['aws_time']); + } + public function testReturnsRegionAndService() { $s = new SignatureV4('foo', 'bar'); @@ -125,7 +135,7 @@ public function testCreatesPresignedDatesFromDateTime($dateTime) $credentials, $dateTime )->getUri(); - $this->assertContains('X-Amz-Expires=518400',$url); + $this->assertStringContainsString('X-Amz-Expires=518400',$url); } @@ -135,7 +145,7 @@ public function testCreatesPresignedDatesFromUnixTimestamp() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request,$credentials,1386720000)->getUri(); - $this->assertContains('X-Amz-Expires=518400',$url); + $this->assertStringContainsString('X-Amz-Expires=518400',$url); } public function testCreatesPresignedDateFromStrtotime() @@ -148,7 +158,7 @@ public function testCreatesPresignedDateFromStrtotime() $credentials, 'December 11, 2013 00:00:00 UTC' )->getUri(); - $this->assertContains('X-Amz-Expires=518400',$url); + $this->assertStringContainsString('X-Amz-Expires=518400',$url); } public function testAddsSecurityTokenIfPresentInPresigned() @@ -159,8 +169,8 @@ public function testAddsSecurityTokenIfPresentInPresigned() $request = $signature->presign($request, $credentials, 1386720000); $this->assertEmpty($request->getHeader('X-Amz-Security-Token')); $url = (string) $request->getUri(); - $this->assertContains('X-Amz-Security-Token=123', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Security-Token=123', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function getStartDateTimeInterfaceInputs() @@ -186,8 +196,8 @@ public function testUsesStartDateFromDateTimeIfPresent($dateTime) list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testUsesStartDateFromUnixTimestampIfPresent() @@ -198,8 +208,8 @@ public function testUsesStartDateFromUnixTimestampIfPresent() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } public function testUsesStartDateFromStrtotimeIfPresent() @@ -210,15 +220,13 @@ public function testUsesStartDateFromStrtotimeIfPresent() list($request, $credentials, $signature) = $this->getFixtures(); $credentials = new Credentials('foo', 'bar', '123'); $url = (string) $signature->presign($request, $credentials, 1386720000, $options)->getUri(); - $this->assertContains('X-Amz-Date=20131205T000000Z', $url); - $this->assertContains('X-Amz-Expires=518400', $url); + $this->assertStringContainsString('X-Amz-Date=20131205T000000Z', $url); + $this->assertStringContainsString('X-Amz-Expires=518400', $url); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresSigV4DurationIsLessThanOneWeek() { + $this->expectException(\InvalidArgumentException::class); $_SERVER['override_v4_time'] = true; list($request, $credentials, $signature) = $this->getFixtures(); $signature->presign($request, $credentials, 'December 31, 2013 00:00:00 UTC'); @@ -254,11 +262,9 @@ public function testConvertsPostToGet() $this->assertSame('foo=bar&baz=bam', $request->getUri()->getQuery()); } - /** - * @expectedException \InvalidArgumentException - */ public function testEnsuresMethodIsPost() { + $this->expectException(\InvalidArgumentException::class); $request = new Request('PUT', 'http://foo.com'); SignatureV4::convertPostToGet($request); } @@ -274,7 +280,7 @@ public function testSignSpecificHeaders() 'content-md5' => 'bogus' ]); $signed = $sig->signRequest($req, $creds); - $this->assertContains('content-md5;host;x-amz-date;x-amz-foo', $signed->getHeaderLine('Authorization')); + $this->assertStringContainsString('content-md5;host;x-amz-date;x-amz-foo', $signed->getHeaderLine('Authorization')); } public function testPresignSpecificHeaders() @@ -290,7 +296,7 @@ public function testPresignSpecificHeaders() 'x-amz-content-sha256' => 'abc', ]); $presigned = $sig->presign($req, $creds, '+5 minutes'); - $this->assertContains(urlencode('host;x-amz-foo;content-md5;x-amz-meta-foo'), (string)$presigned->getUri()); + $this->assertStringContainsString(urlencode('host;x-amz-foo;content-md5;x-amz-meta-foo'), (string)$presigned->getUri()); } public function testPresignBlacklistedHeaders() @@ -303,27 +309,23 @@ public function testPresignBlacklistedHeaders() 'Content-Type' => 'text/html', ]); $presigned = $sig->presign($req, $creds, '+5 minutes'); - $this->assertNotContains('user-agent', (string)$presigned->getUri()); - $this->assertNotContains('X-Amz-User-Agent', (string)$presigned->getUri()); - $this->assertNotContains('content-length', (string)$presigned->getUri()); - $this->assertNotContains('Content-Type', (string)$presigned->getUri()); + $this->assertStringNotContainsString('user-agent', (string)$presigned->getUri()); + $this->assertStringNotContainsString('X-Amz-User-Agent', (string)$presigned->getUri()); + $this->assertStringNotContainsString('content-length', (string)$presigned->getUri()); + $this->assertStringNotContainsString('Content-Type', (string)$presigned->getUri()); } - /** - * @expectedException \Aws\Exception\CouldNotCreateChecksumException - */ public function testEnsuresContentSha256CanBeCalculated() { + $this->expectException(\Aws\Exception\CouldNotCreateChecksumException::class); list($request, $credentials, $signature) = $this->getFixtures(); $request = $request->withBody(new NoSeekStream(Psr7\Utils::streamFor('foo'))); $signature->signRequest($request, $credentials); } - /** - * @expectedException \Aws\Exception\CouldNotCreateChecksumException - */ public function testEnsuresContentSha256CanBeCalculatedWhenSeekFails() { + $this->expectException(\Aws\Exception\CouldNotCreateChecksumException::class); list($request, $credentials, $signature) = $this->getFixtures(); $stream = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [ 'seek' => function () { @@ -334,6 +336,7 @@ public function testEnsuresContentSha256CanBeCalculatedWhenSeekFails() $signature->signRequest($request, $credentials); } + /** @doesNotPerformAssertions */ public function testUnsignedPayloadProvider() { return [ @@ -411,6 +414,7 @@ public function testSignRequestUnsignedPayload($req, $sreq, $creq) $this->assertSame($sreq, Psr7\Message::toString($signature->signRequest($request, $credentials))); } + /** @doesNotPerformAssertions */ public function testProvider() { return [ diff --git a/tests/Sqs/SqsClientTest.php b/tests/Sqs/SqsClientTest.php index ca62b2f3f8..a3ba034678 100644 --- a/tests/Sqs/SqsClientTest.php +++ b/tests/Sqs/SqsClientTest.php @@ -4,6 +4,7 @@ use Aws\Middleware; use Aws\Result; use Aws\Sqs\SqsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; @@ -12,6 +13,7 @@ */ class SqsClientTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; public function testGetQueueArn() @@ -36,12 +38,10 @@ public function testFifoQueueArn() $this->assertSame($arn, $sqs->getQueueArn($url)); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage MD5 mismatch. Expected foo, found ddc35f88fa71b6ef142ae61f35364653 - */ public function testValidatesMd5OfBody() { + $this->expectExceptionMessage("MD5 mismatch. Expected foo, found ddc35f88fa71b6ef142ae61f35364653"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -52,12 +52,10 @@ public function testValidatesMd5OfBody() $client->receiveMessage(['QueueUrl' => 'http://foo.com']); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage Attribute MD5 mismatch. Expected foo, found ee5a4b60facbcc4723c1b5b8baca2593 - */ public function testValidatesMd5OfMessageAttributes() { + $this->expectExceptionMessage("Attribute MD5 mismatch. Expected foo, found ee5a4b60facbcc4723c1b5b8baca2593"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -110,12 +108,10 @@ public function testValidatesMd5OfMessageAttributes() ]); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage No Attribute MD5 found. Expected 0408bb33aa149494a6a4683d58a7133f - */ public function testValidatesMd5OfMessageAttributesExists() { + $this->expectExceptionMessage("No Attribute MD5 found. Expected 0408bb33aa149494a6a4683d58a7133f"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -139,12 +135,10 @@ public function testValidatesMd5OfMessageAttributesExists() ]); } - /** - * @expectedException \Aws\Sqs\Exception\SqsException - * @expectedExceptionMessage Attribute MD5 mismatch. Expected foo, found No Attributes - */ public function testValidatesMessageAttributesExistWithMd5() { + $this->expectExceptionMessage("Attribute MD5 mismatch. Expected foo, found No Attributes"); + $this->expectException(\Aws\Sqs\Exception\SqsException::class); $client = new SqsClient([ 'region' => 'us-west-2', 'version' => 'latest' @@ -163,6 +157,7 @@ public function testValidatesMessageAttributesExistWithMd5() ]); } + /** @doesNotPerformAssertions */ public function testSkipsCommandsThatAreNotReceiveMessage() { $client = new SqsClient([ diff --git a/tests/StreamRequestPayloadMiddlewareTest.php b/tests/StreamRequestPayloadMiddlewareTest.php index a3bde2ccc3..dd98140f96 100644 --- a/tests/StreamRequestPayloadMiddlewareTest.php +++ b/tests/StreamRequestPayloadMiddlewareTest.php @@ -9,6 +9,7 @@ use Aws\Middleware; use Aws\Result; use Aws\StreamRequestPayloadMiddleware; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; @@ -19,6 +20,7 @@ */ class StreamRequestPayloadMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; /** * @dataProvider generateTestCases @@ -112,12 +114,10 @@ public function generateTestCases() ]; } - /** - * @expectedException \Aws\Exception\IncalculablePayloadException - * @expectedExceptionMessage Payload content length is required and can not be calculated. - */ public function testThrowsExceptionOnIncalculableSize() { + $this->expectExceptionMessage("Payload content length is required and can not be calculated."); + $this->expectException(\Aws\Exception\IncalculablePayloadException::class); $service = $this->generateTestService(); $client = $this->generateTestClient($service); $command = $client->getCommand( diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index d35f39d8b6..024b94949a 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\Sts\RegionalEndpoints\ConfigurationInterface; use Aws\Sts\RegionalEndpoints\ConfigurationProvider; use Aws\Sts\RegionalEndpoints\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', @@ -54,7 +57,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '=' . self::$originalEnv['endpoints_type']); @@ -168,21 +171,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -196,12 +195,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectExceptionMessage("'foo' not found in"); + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -214,12 +211,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Sts\RegionalEndpoints\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectExceptionMessage("Invalid config file:"); + $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -288,11 +283,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -402,12 +395,10 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Not a valid STS regional endpoints configuration argument. - */ public function testInvalidConfigurationUnwrap() { + $this->expectExceptionMessage("Not a valid STS regional endpoints configuration argument."); + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::unwrap([]); } } diff --git a/tests/Sts/RegionalEndpoints/ConfigurationTest.php b/tests/Sts/RegionalEndpoints/ConfigurationTest.php index 5828d04ac2..f7767a5b53 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\Sts\RegionalEndpoints; use Aws\Sts\RegionalEndpoints\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('regional'); @@ -25,12 +28,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new Configuration('invalid_type'); } } diff --git a/tests/Sts/StsClientTest.php b/tests/Sts/StsClientTest.php index df4523bccb..e7a0f63732 100644 --- a/tests/Sts/StsClientTest.php +++ b/tests/Sts/StsClientTest.php @@ -8,6 +8,7 @@ use Aws\Result; use Aws\Sts\RegionalEndpoints\Configuration; use Aws\Sts\StsClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Uri; use PHPUnit\Framework\TestCase; @@ -16,6 +17,8 @@ */ class StsClientTest extends TestCase { + use PHPUnitCompatTrait; + public function testCanCreateCredentialsObjectFromStsResult() { $result = new Result([ @@ -36,26 +39,22 @@ public function testCanCreateCredentialsObjectFromStsResult() $this->assertSame('foo', $credentials->getAccessKeyId()); $this->assertSame('bar', $credentials->getSecretKey()); $this->assertSame('baz', $credentials->getSecurityToken()); - $this->assertInternalType('int', $credentials->getExpiration()); + $this->assertIsInt($credentials->getExpiration()); $this->assertFalse($credentials->isExpired()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Result contains no credentials - */ public function testThrowsExceptionWhenCreatingCredentialsFromInvalidInput() { + $this->expectExceptionMessage("Result contains no credentials"); + $this->expectException(\InvalidArgumentException::class); $client = new StsClient(['region' => 'us-east-1', 'version' => 'latest']); $client->createCredentials(new Result()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Configuration parameter must either be 'legacy' or 'regional'. - */ public function testAddsStsRegionalEndpointsArgument() { + $this->expectExceptionMessage("Configuration parameter must either be 'legacy' or 'regional'."); + $this->expectException(\InvalidArgumentException::class); new StsClient([ 'region' => 'us-east-1', 'version' => 'latest', diff --git a/tests/TraceMiddlewareTest.php b/tests/TraceMiddlewareTest.php index 3a228c4140..4fb528d2c7 100644 --- a/tests/TraceMiddlewareTest.php +++ b/tests/TraceMiddlewareTest.php @@ -7,6 +7,7 @@ use Aws\Exception\AwsException; use Aws\HandlerList; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\TraceMiddleware; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; @@ -19,6 +20,8 @@ */ class TraceMiddlewareTest extends TestCase { + use PHPUnitCompatTrait; + public function testEmitsDebugInfo() { $str = ''; @@ -48,15 +51,15 @@ public function testEmitsDebugInfo() $request = new Request('GET', 'http://foo.com'); $handler($command, $request); Promise\queue()->run(); - $this->assertContains("-> Entering step init, name ''", $str); - $this->assertContains('command was set to array', $str); - $this->assertContains('request was set to array', $str); - $this->assertContains("<- Leaving step init, name ''", $str); - $this->assertContains('result was set to array', $str); - $this->assertContains('Inclusive step time: ', $str); - $this->assertContains('command.params.b was unset', $str); - $this->assertContains('no changes', $str); - $this->assertContains("<- Leaving step validate, name ''", $str); + $this->assertStringContainsString("-> Entering step init, name ''", $str); + $this->assertStringContainsString('command was set to array', $str); + $this->assertStringContainsString('request was set to array', $str); + $this->assertStringContainsString("<- Leaving step init, name ''", $str); + $this->assertStringContainsString('result was set to array', $str); + $this->assertStringContainsString('Inclusive step time: ', $str); + $this->assertStringContainsString('command.params.b was unset', $str); + $this->assertStringContainsString('no changes', $str); + $this->assertStringContainsString("<- Leaving step validate, name ''", $str); } public function testTracksExceptions() @@ -84,11 +87,11 @@ public function testTracksExceptions() $request = new Request('GET', 'http://foo.com'); $handler($command, $request); Promise\queue()->run(); - $this->assertContains('error was set to array', $str); - $this->assertContains('trace', $str); - $this->assertContains('class', $str); - $this->assertContains('message', $str); - $this->assertContains('string(6) "Oh no!"', $str); + $this->assertStringContainsString('error was set to array', $str); + $this->assertStringContainsString('trace', $str); + $this->assertStringContainsString('class', $str); + $this->assertStringContainsString('message', $str); + $this->assertStringContainsString('string(6) "Oh no!"', $str); } public function testTracksAwsSpecificExceptions() @@ -119,11 +122,11 @@ public function testTracksAwsSpecificExceptions() $request = new Request('GET', 'http://foo.com'); $handler($command, $request); Promise\queue()->run(); - $this->assertContains('error was set to array', $str); - $this->assertContains('trace', $str); - $this->assertContains('class', $str); - $this->assertContains('message', $str); - $this->assertContains('string(5) "error"', $str); + $this->assertStringContainsString('error was set to array', $str); + $this->assertStringContainsString('trace', $str); + $this->assertStringContainsString('class', $str); + $this->assertStringContainsString('message', $str); + $this->assertStringContainsString('string(5) "error"', $str); } /** @@ -160,11 +163,11 @@ public function testScrubsAuthStrings($key, $signature, array $headers) ); $handler($command, $request); - $this->assertNotContains($key, $str); - $this->assertNotContains($signature, $str); + $this->assertStringNotContainsString($key, $str); + $this->assertStringNotContainsString($signature, $str); foreach ($headers as $header) { - $this->assertNotContains($header['raw'], $str); - $this->assertContains($header['scrubbed'], $str); + $this->assertStringNotContainsString($header['raw'], $str); + $this->assertStringContainsString($header['scrubbed'], $str); } } @@ -206,14 +209,14 @@ public function testRedactsSensitiveTraits() $request = new Request('post', "/"); $handler($command, $request); - $this->assertContains("NestedParams also not redacted", $str); - $this->assertContains("PublicParameter not redacted", $str); - $this->assertContains("[SensitiveParameter]", $str); - $this->assertNotContains("SensitiveParameter was redacted", $str); - $this->assertContains("[NestedSensitiveParameter]", $str); - $this->assertNotContains("NestedSensitiveParameter was also redacted", $str); - $this->assertContains("[SensitiveArray]", $str); - $this->assertNotContains("SensitiveArray contents also redacted", $str); + $this->assertStringContainsString("NestedParams also not redacted", $str); + $this->assertStringContainsString("PublicParameter not redacted", $str); + $this->assertStringContainsString("[SensitiveParameter]", $str); + $this->assertStringNotContainsString("SensitiveParameter was redacted", $str); + $this->assertStringContainsString("[NestedSensitiveParameter]", $str); + $this->assertStringNotContainsString("NestedSensitiveParameter was also redacted", $str); + $this->assertStringContainsString("[SensitiveArray]", $str); + $this->assertStringNotContainsString("SensitiveArray contents also redacted", $str); } public function authStringProvider() @@ -273,9 +276,9 @@ public function testCanScrubOnArbitraryPatterns() ); $handler($command, $request); - $this->assertNotContains($toScrub, $str); + $this->assertStringNotContainsString($toScrub, $str); foreach (array_values($scrubPatterns) as $scrubbed) { - $this->assertContains($scrubbed, $str); + $this->assertStringContainsString($scrubbed, $str); } } diff --git a/tests/WaiterTest.php b/tests/WaiterTest.php index c6467f5cff..2387f0d534 100644 --- a/tests/WaiterTest.php +++ b/tests/WaiterTest.php @@ -6,6 +6,7 @@ use Aws\DynamoDb\DynamoDbClient; use Aws\Exception\AwsException; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; @@ -21,13 +22,12 @@ */ class WaiterTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; - /** - * @expectedException \InvalidArgumentException - */ public function testErrorOnBadConfig() { + $this->expectException(\InvalidArgumentException::class); $provider = ApiProvider::defaultProvider(); $client = new DynamoDbClient([ 'region' => 'foo', @@ -44,11 +44,9 @@ public function testErrorOnBadConfig() ); } - /** - * @expectedException \InvalidArgumentException - */ public function testErrorOnBadBeforeCallback() { + $this->expectException(\InvalidArgumentException::class); $client = $this->getTestClient('DynamoDb'); $client->waitUntil( 'TableExists', @@ -59,6 +57,7 @@ public function testErrorOnBadBeforeCallback() ); } + /** @doesNotPerformAssertions */ public function testContinueWaitingOnHandlerError() { $retries = 10; @@ -91,6 +90,7 @@ public function testContinueWaitingOnHandlerError() ]); } + /** @doesNotPerformAssertions */ public function testCanCancel() { $client = $this->getTestClient('DynamoDb'); diff --git a/tests/WrappedHttpHandlerTest.php b/tests/WrappedHttpHandlerTest.php index d8c1a0df57..5ee622d8cc 100644 --- a/tests/WrappedHttpHandlerTest.php +++ b/tests/WrappedHttpHandlerTest.php @@ -10,6 +10,7 @@ use Aws\CommandInterface; use Aws\Exception\AwsException; use Aws\Result; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\WrappedHttpHandler; use GuzzleHttp\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; @@ -23,6 +24,7 @@ */ class WrappedHttpHandlerTest extends TestCase { + use PHPUnitCompatTrait; use TestServiceTrait; public function testParsesResponses() @@ -59,12 +61,10 @@ public function testParsesResponses() ], $result['@metadata']); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage The HTTP handler was rejected without an "exception" key value pair. - */ public function testEnsuresErrorHasExceptionKey() { + $this->expectExceptionMessage("The HTTP handler was rejected without an \"exception\" key value pair."); + $this->expectException(\RuntimeException::class); $cmd = new Command('foo'); $req = new Request('GET', 'http://foo.com'); $handler = function () { return new RejectedPromise([]); }; @@ -373,7 +373,7 @@ public function testPassesOnTransferStatsCallbackToHandlerWhenRequested() { $handler = function ($request, array $options) { $this->assertArrayHasKey('http_stats_receiver', $options); - $this->assertInternalType('callable', $options['http_stats_receiver']); + $this->assertIsCallable($options['http_stats_receiver']); return new Response; }; diff --git a/tests/bootstrap.php b/tests/bootstrap.php index b8f8d6c0b2..c4cde91a15 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,17 +3,21 @@ date_default_timezone_set('UTC'); // Include the composer autoloader -$loader = require __DIR__ . '/../vendor/autoload.php'; +$loader = require __DIR__.'/../vendor/autoload.php'; -if (!class_exists('\PHPUnit\Framework\Constraint\RegularExpression')) { +if ( ! defined('PHPUNIT_COMPOSER_INSTALL')) { + 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\Constraint\Callback')) { + class_alias('\PHPUnit_Framework_Constraint_Callback', '\PHPUnit\Framework\Constraint\Callback'); } -if (!class_exists('\PHPUnit\Framework\Error\Warning')) { +if ( ! class_exists('\PHPUnit\Framework\Error\Warning')) { class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warning'); } @@ -22,10 +26,13 @@ class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warnin // Patch PHPUnit class for PHP 7.4+ and PHPUnit 5.x to avoid deprecation warning // Necessary because older versions of PHPUnit are no longer supported -$version = PHPUnit_Runner_Version::id(); +$version = class_exists('PHPUnit_Runner_Version') ? PHPUnit_Runner_Version::id() : PHPUnit\Runner\Version::id(); $versionData = explode('.', $version); + +include_once(sprintf("%s/Polyfill/PHPUnit%s/PHPUnitCompatTrait.php", __DIR__, $versionData[0])); + if (PHP_VERSION_ID >= 70400 && $versionData[0] == 5) { - $vendorGeneratorPath = __DIR__ . '/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; - $patchGeneratorPath = __DIR__ . '/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; + $vendorGeneratorPath = __DIR__.'/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; + $patchGeneratorPath = __DIR__.'/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; file_put_contents($vendorGeneratorPath, file_get_contents($patchGeneratorPath)); } From 1c4109ddf0fc0e83496e1090ad4a1294e368061a Mon Sep 17 00:00:00 2001 From: Zombaya Date: Tue, 17 May 2022 09:49:46 +0200 Subject: [PATCH 13/31] Replace key-fixture in CloudFront-tests with generated keys --- tests/CloudFront/CloudFrontClientTest.php | 4 ++-- tests/CloudFront/CookieSignerTest.php | 3 +-- tests/CloudFront/SignerTest.php | 1 - tests/CloudFront/UrlSignerTest.php | 4 ++-- tests/CloudFront/fixtures/test2.pem | 27 ----------------------- 5 files changed, 5 insertions(+), 34 deletions(-) delete mode 100644 tests/CloudFront/fixtures/test2.pem diff --git a/tests/CloudFront/CloudFrontClientTest.php b/tests/CloudFront/CloudFrontClientTest.php index 4ab56beea1..64e67425fd 100644 --- a/tests/CloudFront/CloudFrontClientTest.php +++ b/tests/CloudFront/CloudFrontClientTest.php @@ -7,7 +7,7 @@ use PHPUnit\Framework\TestCase; /** - * @covers Aws\CloudFront\CloudFrontClient + * @covers CloudFrontClient */ class CloudFrontClientTest extends TestCase { @@ -18,7 +18,7 @@ class CloudFrontClientTest extends TestCase public function _setUp() { - $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; } diff --git a/tests/CloudFront/CookieSignerTest.php b/tests/CloudFront/CookieSignerTest.php index 791fcfffa4..5d8742b44f 100644 --- a/tests/CloudFront/CookieSignerTest.php +++ b/tests/CloudFront/CookieSignerTest.php @@ -2,7 +2,6 @@ namespace Aws\Test\CloudFront; use Aws\CloudFront\CookieSigner; -use Aws\CloudFront\Policy; use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; @@ -15,7 +14,7 @@ class CookieSignerTest extends TestCase public function _setUp() { - $this->key = realpath(__DIR__.'/fixtures/test2.pem'); + openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; } diff --git a/tests/CloudFront/SignerTest.php b/tests/CloudFront/SignerTest.php index 7d992a1156..43800fc73c 100644 --- a/tests/CloudFront/SignerTest.php +++ b/tests/CloudFront/SignerTest.php @@ -1,7 +1,6 @@ key = realpath(__DIR__.'/fixtures/test2.pem'); + openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; } diff --git a/tests/CloudFront/fixtures/test2.pem b/tests/CloudFront/fixtures/test2.pem deleted file mode 100644 index 0bfb6e4a57..0000000000 --- a/tests/CloudFront/fixtures/test2.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEAxTbyKHzrPyxD91YYgq5R87tt66oX+OjJrMQI9MGp74t/N7+V -4uCGyPc5pXDgMtPO5JNAaEfkxJUosn3/g+0i/xnl7INOLrLRTLbOSBMAZVusLhlR -2l+iXPeFNrxwPxRSoROx5T9r2/rBvSwhUsDUJREPBz2IyUdbq+893QUytIm7DYSJ -NkgJFL7bIXxzQISZmfZ6ocJ1qpKuOsiAZdUu6Eaox8jdalvSqrgKhPhQ85T3HG6L -nlnEwMJAQHauwhVBaTzOybyycfvKVQNlT+JN1JnKQvdbt9lQxYVtLhZ9CEKcY41Q -3Yqyb+1MBl49C4kppYoZ5ZllIRa8sbHGk3gxgQIDAQABAoIBAQCPrwyXOwwaJqIO -HggVjfPfY/sd6/szOkdVPC5aRI8PG89ASrFlbrhEyvqQ8sAlx/PAzRfr4hVmtFXG -Vc5HzAnnWnMN8kyP8XBUOAvqrw1my3eSzpe4Rl0A5sWDr58IFkJtYPAHWkG3L+bf -cLuGkz79EoSkfcye+QJtLg0gbp0WsspfgnRxF0xKQu7H2MWkzppXzWOehxWc6YtJ -LIlBicnAQGOIbX0tghpguYNe/HsOyM5Mh1Q7AzTj6fhISxX8l/zjE5k/d9qPjk2S -hTYKYGTY11FCF6mhnRSt5hCop/N4lS+jR1ld3rbuKUzDMsuJFGKpM+8Vdn82gP7S -SzFBExzBAoGBAOyjSfKlCjojRtQ9G7D7oc11UnwP0tF73IonVoRrYyPub153/Nlc -DMB5YLCHl8u51TtPLpLH9tK+aQKaCpLoKkGxU1IK/pCGIL9JSJzyAkhajNtg/hmh -kWUdTQ9wckb5a+0VBjDPCgx4xk3sKC9fdWcrmETDs/hpJS8qz3v91N9NAoGBANVZ -4fPREN8rYIRABM/r8sd5+bIHrmFxWTb0iumx/B2Uf1z3HNDDOwUNe/WOSbZiMlsz -wK+3OoUygDT+yGvYpF6ZpjWtpPcuyKLxYQzICnISgjsohpwWt33LjGCqDtxuvcNx -JaDrLj+vZJzMr76PD6+z4KydErcAePoMDWZrfqkFAoGAO/elZbgtP05xRJe3zMH3 -3vk8TfQ0mKGq4dfWNPiBxzlFP8toaCzLjnsz5Yh3D0mon78RLmE+S2m1ctNWmqP7 -EWq+kqv2lulmoxMPM7agnXVU/MM3oYcwMU+bl64HR7UthIcvam8NPNveZSDTji3C -ssJ5c/OkR+9dXPacXe+VYoECgYEAuqxAVVKxznJnqo9RJpOuAvcokKrD2yKQCtOA -z+UZUNBjd/YHUmnftBYORdZPjLLymHX5vEU3gN+k6bmbpzEQ8GzDzue2FUjr6BYG -8mX9Lb4gEJ7u2JfPyNNWaiWhhyGmC+FuKRRdjP9rqv41LyiBcxySErYEb/aL40y0 -VM7tLfkCgYEArKYfLKzkJmicUQ7xzRIEM66DEynUEwH5VeTzHBO3Eszgj5w9C7rj -e+dGdUEJ6ie5J6QVLfT7oUCCuKF7Mrhvho8NLeObtzt2URRxQmQQfWH1TSzaarc0 -GQi4IIkGDLJeTow+7N2RB29zNDW6edh7vkoEJwvqIuC4bj4/wsEdfCI= ------END RSA PRIVATE KEY----- From 7dd0db1e10852bd3b3cb042d390b318e4edf1fa6 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Wed, 16 Mar 2022 09:57:21 +0100 Subject: [PATCH 14/31] Additional changes to unittest for phpunit9-compatibility --- tests/Api/ServiceTest.php | 7 +- tests/ClientResolverTest.php | 6 +- .../InstanceProfileProviderTest.php | 8 +- .../ConfigurationProviderTest.php | 37 +++--- tests/DefaultsMode/ConfigurationTest.php | 9 +- tests/DynamoDb/DynamoDbClientTest.php | 4 +- tests/Endpoint/PartitionTest.php | 4 +- .../ConfigurationProviderTest.php | 31 ++---- .../ConfigurationTest.php | 16 +-- .../ConfigurationProviderTest.php | 31 ++---- .../UseFipsEndpoint/ConfigurationTest.php | 9 +- .../EventBridgeEndpointMiddlewareTest.php | 5 +- tests/S3/StreamWrapperTest.php | 5 +- tests/S3/StreamWrapperV2ExistenceTest.php | 105 ++++++++---------- .../ConfigurationProviderTest.php | 2 +- 15 files changed, 121 insertions(+), 158 deletions(-) diff --git a/tests/Api/ServiceTest.php b/tests/Api/ServiceTest.php index 3458e535ce..6313559285 100644 --- a/tests/Api/ServiceTest.php +++ b/tests/Api/ServiceTest.php @@ -178,7 +178,6 @@ public function serializerDataProvider() /** * @dataProvider serializerDataProvider - * @doesNotPerformAssertions */ public function testCreatesSerializer($type, $cl) { @@ -203,7 +202,6 @@ public function parserDataProvider() /** * @dataProvider parserDataProvider - * @doesNotPerformAssertions */ public function testCreatesParsers($type, $cl) { @@ -215,8 +213,9 @@ function () { return []; } $this->assertInstanceOf($cl, $parser); if ($parser instanceof QueryParser) { - $this->assertAttributeInstanceOf( - 'Aws\Api\Parser\XmlParser', 'parser', $parser + $this->assertInstanceOf( + 'Aws\Api\Parser\XmlParser', + $this->readAttribute($parser, 'parser') ); } } diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index 7d96eda0b6..8da3967fb1 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -612,12 +612,10 @@ public function testDualstackEndpointInIsoPartition() ); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Dual-stack is not supported in ISO regions - */ public function testDualstackEndpointFailureOnDualstackNotSupported() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Dual-stack is not supported in ISO regions"); $data = json_decode( file_get_contents(__DIR__ . '/Endpoint/fixtures/dualstack_endpoints.json'), true diff --git a/tests/Credentials/InstanceProfileProviderTest.php b/tests/Credentials/InstanceProfileProviderTest.php index 27f7fed545..4c87a66973 100644 --- a/tests/Credentials/InstanceProfileProviderTest.php +++ b/tests/Credentials/InstanceProfileProviderTest.php @@ -986,7 +986,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsYieldsExpiredCreds($cl $creds = $provider()->wait(); $message = stream_get_contents($capture); - $this->assertRegExp('/Attempting credential expiration extension/', $message); + $this->assertMatchesRegularExpression('/Attempting credential expiration extension/', $message); $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('baz', $creds->getSecretKey()); $this->assertFalse($creds->isExpired()); @@ -1008,7 +1008,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsYieldsExpiredCreds($cl $result = $s3Client->listBuckets(); $this->assertEquals('Request sent', $result['message']); - $this->assertAttributeLessThanOrEqual(3, 'attempts', $provider); + $this->assertLessThanOrEqual(3,$this->readAttribute($provider,'attempts')); } public function returnsExpiredCredsProvider() @@ -1072,7 +1072,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsUnavailable($client) $creds = $provider($expiredCreds)->wait(); $message = stream_get_contents($capture); - $this->assertRegExp('/Attempting credential expiration extension/', $message); + $this->assertMatchesRegularExpression('/Attempting credential expiration extension/', $message); $this->assertSame('foo', $creds->getAccessKeyId()); $this->assertSame('baz', $creds->getSecretKey()); $this->assertFalse($expiredCreds->isExpired()); @@ -1094,7 +1094,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsUnavailable($client) $result = $s3Client->listBuckets(); $this->assertEquals('Request sent', $result['message']); - $this->assertAttributeLessThanOrEqual(3, 'attempts', $provider); + $this->assertLessThanOrEqual(3,$this->readAttribute($provider,'attempts')); } public function imdsUnavailableProvider() diff --git a/tests/DefaultsMode/ConfigurationProviderTest.php b/tests/DefaultsMode/ConfigurationProviderTest.php index e66a0b6404..eca5da78d4 100644 --- a/tests/DefaultsMode/ConfigurationProviderTest.php +++ b/tests/DefaultsMode/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\DefaultsMode\ConfigurationInterface; use Aws\DefaultsMode\ConfigurationProvider; use Aws\DefaultsMode\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_MODE) ?: '', @@ -53,7 +56,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_MODE . '=' . self::$originalEnv['mode']); @@ -167,21 +170,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -195,12 +194,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'foo' not found in"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -213,12 +210,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\DefaultsMode\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectException(\Aws\DefaultsMode\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Invalid config file:"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -285,11 +280,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } @@ -406,12 +399,10 @@ public function testCreatesLegacy() self::assertNull($config->getStsRegionalEndpoints()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage is not a valid mode. The mode has to be 'legacy', 'standard', 'cross-region', 'in-region', 'mobile', or 'auto'. - */ public function testThrowsForInvalidUnwrapArgument() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage("is not a valid mode. The mode has to be 'legacy', 'standard', 'cross-region', 'in-region', 'mobile', or 'auto'."); ConfigurationProvider::unwrap('some_string'); } } diff --git a/tests/DefaultsMode/ConfigurationTest.php b/tests/DefaultsMode/ConfigurationTest.php index d71547d4db..e3eb1d2fde 100644 --- a/tests/DefaultsMode/ConfigurationTest.php +++ b/tests/DefaultsMode/ConfigurationTest.php @@ -3,6 +3,7 @@ namespace Aws\Test\DefaultsMode; use Aws\DefaultsMode\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -10,6 +11,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + public function testGetsCorrectValues() { $config = new Configuration('standard'); @@ -42,12 +45,10 @@ public function testToArrayWithLegacy() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage 'foo' is not a valid mode - */ public function testHandlesInvalidMode() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage("'foo' is not a valid mode"); new Configuration('foo'); } } diff --git a/tests/DynamoDb/DynamoDbClientTest.php b/tests/DynamoDb/DynamoDbClientTest.php index 1a24aa489c..841f6d910e 100644 --- a/tests/DynamoDb/DynamoDbClientTest.php +++ b/tests/DynamoDb/DynamoDbClientTest.php @@ -26,9 +26,9 @@ public function testRegisterSessionHandlerReturnsHandler() { $client = $this->getTestSdk()->createDynamoDb(); @$sh = $client->registerSessionHandler(['locking' => true]); - $this->assertAttributeInstanceOf( + $this->assertInstanceOf( 'Aws\DynamoDb\LockingSessionConnection', - 'connection', $sh + $this->readAttribute($sh, 'connection') ); } diff --git a/tests/Endpoint/PartitionTest.php b/tests/Endpoint/PartitionTest.php index 09bb87cd52..6b85d6a73f 100644 --- a/tests/Endpoint/PartitionTest.php +++ b/tests/Endpoint/PartitionTest.php @@ -691,7 +691,7 @@ public function testGetVariantIgnoresVariantTagOrder( ] ]); - self::assertContains('testsuffix.com', $resolved['endpoint']); + $this->assertStringContainsString('testsuffix.com', $resolved['endpoint']); } public function variantTagProvider() @@ -841,7 +841,7 @@ public function testGetVariantNoVariantSelectedIfTagsAreEmpty( ] ]); - self::assertNotContains('testsuffix.com', $resolved['endpoint']); + $this->assertStringNotContainsString('testsuffix.com', $resolved['endpoint']); } public function variantTagEmptyProvider() diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php index 6f6fdd09eb..16de56b55e 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php @@ -7,6 +7,7 @@ use Aws\Endpoint\UseDualstackEndpoint\Configuration; use Aws\Endpoint\UseDualstackEndpoint\ConfigurationInterface; use Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -15,6 +16,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT) ?: '', @@ -54,7 +57,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT . '=' . self::$originalEnv['use_dualstack_endpoint']); @@ -169,21 +172,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini('us-east-1'))->wait(); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -197,12 +196,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'foo' not found in"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -215,12 +212,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Invalid config file:"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -290,11 +285,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php index fcedcdd5e4..e6931bba76 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Endpoint\UseDualstackEndpoint; use Aws\Endpoint\UseDualstackEndpoint\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider correctValueCases * @@ -44,20 +47,17 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'use_dual_stack_endpoint' config option must be a boolean value - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'use_dual_stack_endpoint' config option must be a boolean value"); new Configuration('not a boolean', 'us-east-1'); } - /** - * @expectedException \Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Dual-stack is not supported in ISO regions - */ + public function testThrowsOnInvalidRegion() { + $this->expectException(\Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Dual-stack is not supported in ISO regions"); new Configuration(true, 'something-iso-something'); } } diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php index 311c178a17..7ea27d0d18 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php @@ -6,6 +6,7 @@ use Aws\Endpoint\UseFipsEndpoint\Configuration; use Aws\Endpoint\UseFipsEndpoint\ConfigurationInterface; use Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; @@ -14,6 +15,8 @@ */ class ConfigurationProviderTest extends TestCase { + use PHPUnitCompatTrait; + private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT) ?: '', @@ -53,7 +56,7 @@ private function clearEnv() return $dir; } - public static function tearDownAfterClass() + public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT . '=' . self::$originalEnv['use_fips_endpoint']); @@ -177,21 +180,17 @@ public function testCreatesFromIniFileWithSpecifiedProfile() unlink($dir . '/config'); } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - */ public function testEnsuresIniFileExists() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); $this->clearEnv(); putenv('HOME=/does/not/exist'); call_user_func(ConfigurationProvider::ini())->wait(); } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - */ public function testEnsuresProfileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); $dir = $this->clearEnv(); $ini = "[custom]"; file_put_contents($dir . '/config', $ini); @@ -205,12 +204,10 @@ public function testEnsuresProfileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'foo' not found in - */ public function testEnsuresFileIsNotEmpty() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'foo' not found in"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', ''); putenv('HOME=' . dirname($dir)); @@ -223,12 +220,10 @@ public function testEnsuresFileIsNotEmpty() } } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage Invalid config file: - */ public function testEnsuresIniFileIsValid() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("Invalid config file:"); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); @@ -297,11 +292,9 @@ public function testChainsConfiguration() unlink($dir . '/config'); } - /** - * @expectedException \InvalidArgumentException - */ public function testChainThrowsExceptionOnEmptyArgs() { + $this->expectException(\InvalidArgumentException::class); ConfigurationProvider::chain(); } diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php index 1f915fcdcd..f603f737a4 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Endpoint\UseFipsEndpoint; use Aws\Endpoint\UseFipsEndpoint\Configuration; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; /** @@ -9,6 +10,8 @@ */ class ConfigurationTest extends TestCase { + use PHPUnitCompatTrait; + /** * @dataProvider correctValueCases * @@ -44,12 +47,10 @@ public function testToArray() $this->assertEquals($expected, $config->toArray()); } - /** - * @expectedException \Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException - * @expectedExceptionMessage 'use_fips_endpoint' config option must be a boolean value. - */ public function testThrowsOnInvalidEndpointsType() { + $this->expectException(\Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException::class); + $this->expectExceptionMessage("'use_fips_endpoint' config option must be a boolean value."); new Configuration('not a boolean'); } } diff --git a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php index 6f6d99a1a6..67d0ad5ac8 100644 --- a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php +++ b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php @@ -4,6 +4,7 @@ use Aws\CommandInterface; use Aws\Result; use Aws\EventBridge\EventBridgeClient; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; @@ -11,7 +12,7 @@ class EventBridgeEndpointMiddlewareTest extends TestCase { use UsesServiceTrait; - + use PHPUnitCompatTrait; public function putEventsEndpointSuccessProvider() { @@ -199,7 +200,7 @@ public function testPutEventsEndpointFailureCases( self::fail("this test should have thrown an exception"); } catch (\Exception $exception) { self::assertSame("InvalidArgumentException", get_class($exception)); - self::assertContains($expectedException, $exception->getMessage()); + self::assertStringContainsString($expectedException, $exception->getMessage()); } } diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index 3cbc902d51..1041cc832a 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -1010,12 +1010,13 @@ public function contentProvider() } /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Unable to determine stream size. Did you forget to close or flush the stream? * @dataProvider contentProvider */ public function testTriggersErrorOnNoFlushOrClose($content) { + $this->expectException(\PHPUnit\Framework\Error\Warning::class); + $this->expectExceptionMessage("Unable to determine stream size. Did you forget to close or flush the stream?"); + $stream = $this->getMockBuilder(Psr7\Stream::class) ->disableOriginalConstructor() ->getMock(); diff --git a/tests/S3/StreamWrapperV2ExistenceTest.php b/tests/S3/StreamWrapperV2ExistenceTest.php index 176fdfc32d..59c885b058 100644 --- a/tests/S3/StreamWrapperV2ExistenceTest.php +++ b/tests/S3/StreamWrapperV2ExistenceTest.php @@ -9,6 +9,7 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Response; @@ -20,6 +21,7 @@ */ class StreamWrapperV2ExistenceTest extends TestCase { + use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -28,7 +30,7 @@ class StreamWrapperV2ExistenceTest extends TestCase /** @var LruArrayCache */ private $cache; - public function setUp() + public function _setUp() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -37,12 +39,15 @@ public function setUp() $this->client->registerStreamWrapperV2(); } - public function tearDown() + public function _tearDown() { stream_wrapper_unregister('s3'); $this->client = null; } + /** + * @doesNotPerformAssertions + */ public function testSuccessfulXMode() { $this->addMockResults( @@ -234,12 +239,10 @@ public function testCanWriteEmptyFileToStream() $this->assertSame('', (string) $cmd['Body']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { + $this->expectError(); + $this->expectErrorMessage('403 Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } ]); @@ -305,12 +308,10 @@ public function testCanUnlinkFiles() $this->assertSame('bucket.s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testThrowsErrorsWhenUnlinkFails() { + $this->expectError(); + $this->expectErrorMessage('403 Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -322,22 +323,18 @@ public function testCreatingBucketWithNoBucketReturnsFalse() $this->assertFalse(mkdir('s3://')); } - /** - * @expectedExceptionMessage Bucket already exists: s3://already-existing-bucket - * @expectedException \PHPUnit\Framework\Error\Warning - */ 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'); } - /** - * @expectedExceptionMessage Subfolder already exists: s3://already-existing-bucket/key - * @expectedException \PHPUnit\Framework\Error\Warning - */ 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'); } @@ -407,24 +404,20 @@ function ($cmd, $r) { return new S3Exception( $entries = $history->toArray(); $this->assertSame('HEAD', $entries[0]['request']->getMethod()); $this->assertSame('PUT', $entries[1]['request']->getMethod()); - $this->assertContains('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); + $this->assertStringContainsString('public-read', $entries[1]['request']->getHeaderLine('x-amz-acl')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage specify a bucket - */ public function testCannotDeleteS3() { + $this->expectError(); + $this->expectErrorMessage('specify a bucket'); rmdir('s3://'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage 403 Forbidden - */ public function testRmDirWithExceptionTriggersError() { + $this->expectError(); + $this->expectErrorMessage('403 Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -464,7 +457,7 @@ public function testCanDeleteObjectWithRmDir($path) $this->assertCount(1, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=object%2F', $entries[0]['request']->getUri()->getQuery()); } public function testCanDeleteNestedFolderWithRmDir() @@ -484,37 +477,31 @@ public function testCanDeleteNestedFolderWithRmDir() $this->assertCount(2, $history); $entries = $history->toArray(); $this->assertSame('GET', $entries[0]['request']->getMethod()); - $this->assertContains('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); + $this->assertStringContainsString('prefix=bar%2F', $entries[0]['request']->getUri()->getQuery()); $this->assertSame('DELETE', $entries[1]['request']->getMethod()); $this->assertSame('/bar/', $entries[1]['request']->getUri()->getPath()); - $this->assertContains('foo', $entries[1]['request']->getUri()->getHost()); + $this->assertStringContainsString('foo', $entries[1]['request']->getUri()->getHost()); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage rename(): Cannot rename a file across wrapper types - */ 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'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage The Amazon S3 stream wrapper only supports copying objects - */ public function testRenameEnsuresKeyIsSet() { + $this->expectError(); + $this->expectErrorMessage('The Amazon S3 stream wrapper only supports copying objects'); rename('s3://foo/bar', 's3://baz'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ public function testRenameWithExceptionThrowsError() { + $this->expectError(); + $this->expectErrorMessage('Forbidden'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -612,12 +599,10 @@ public function testCanPullStatDataFromCache() $this->assertSame(123, filesize('s3://foo/bar')); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage Forbidden - */ 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); }, @@ -627,12 +612,10 @@ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } stat('s3://bucket/key'); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket - */ public function testBucketNotFoundTriggersError() { + $this->expectError(); + $this->expectErrorMessage('File or directory not found: s3://bucket'); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception( @@ -684,12 +667,10 @@ function ($cmd, $r) { return new S3Exception( $this->assertSame(0040777, $stat['mode']); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage File or directory not found: s3://bucket/prefix - */ 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', @@ -769,12 +750,16 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) $this->assertCount(count($queue), $history); } - /** - * @expectedException \PHPUnit\Framework\Error\Warning - * @expectedExceptionMessage cannot represent a stream of type user-space - */ 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->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) ]); @@ -805,7 +790,7 @@ function ($cmd, $r) { return new S3Exception( ['response' => new Response(404)] );}, ]); - $this->assertFileNotExists('s3://bucket/key'); + $this->assertFileDoesNotExist('s3://bucket/key'); } public function testProvidesDirectoriesForS3() @@ -872,7 +857,7 @@ public function testProvidesDirectoriesForS3() $dir = 's3://bucket/key/'; $r = opendir($dir); - $this->assertInternalType('resource', $r); + $this->assertIsResource($r); $files = []; while (($file = readdir($r)) !== false) { diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index 024b94949a..ae60071270 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -12,7 +12,7 @@ use PHPUnit\Framework\TestCase; /** - * @covers \Aws\Sts\RegionalEndpoints\ConfigurationProvider + * git\Sts\RegionalEndpoints\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { From a1299909892102289547f3edadf1f0840d9c1c60 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Fri, 18 Mar 2022 02:10:57 +0100 Subject: [PATCH 15/31] Fix problems with non-fully-reset environment-variables after test --- tests/ClientSideMonitoring/ConfigurationProviderTest.php | 3 +++ tests/DefaultsMode/ConfigurationProviderTest.php | 4 ++++ .../UseDualstackEndpoint/ConfigurationProviderTest.php | 6 +++++- .../UseFipsEndpoint/ConfigurationProviderTest.php | 8 ++++++-- tests/EndpointDiscovery/ConfigurationProviderTest.php | 4 ++++ tests/Retry/ConfigurationProviderTest.php | 4 ++++ tests/S3/RegionalEndpoint/ConfigurationProviderTest.php | 4 ++++ tests/S3/UseArnRegion/ConfigurationProviderTest.php | 4 ++++ tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php | 4 ++++ 9 files changed, 38 insertions(+), 3 deletions(-) diff --git a/tests/ClientSideMonitoring/ConfigurationProviderTest.php b/tests/ClientSideMonitoring/ConfigurationProviderTest.php index 73f37683bb..04b6a1a2a7 100644 --- a/tests/ClientSideMonitoring/ConfigurationProviderTest.php +++ b/tests/ClientSideMonitoring/ConfigurationProviderTest.php @@ -57,6 +57,7 @@ public static function _setUpBeforeClass() 'port' => getenv(ConfigurationProvider::ENV_PORT) ?: '', 'client_id' => getenv(ConfigurationProvider::ENV_CLIENT_ID) ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -90,6 +91,8 @@ public static function _tearDownAfterClass() self::$originalEnv['client_id']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); } public function testCreatesFromEnvironmentVariables() diff --git a/tests/DefaultsMode/ConfigurationProviderTest.php b/tests/DefaultsMode/ConfigurationProviderTest.php index eca5da78d4..e49c557e71 100644 --- a/tests/DefaultsMode/ConfigurationProviderTest.php +++ b/tests/DefaultsMode/ConfigurationProviderTest.php @@ -39,6 +39,7 @@ public static function _setUpBeforeClass() 'mode' => getenv(ConfigurationProvider::ENV_MODE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -46,6 +47,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_MODE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -62,6 +64,8 @@ public static function _tearDownAfterClass() self::$originalEnv['mode']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php index 16de56b55e..c94f206d06 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php @@ -1,5 +1,5 @@ getenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -47,6 +48,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -63,6 +65,8 @@ public static function _tearDownAfterClass() self::$originalEnv['use_dualstack_endpoint']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php index 7ea27d0d18..d290fc8f69 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php @@ -1,5 +1,5 @@ getenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } private function clearEnv() { putenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -60,9 +62,11 @@ public static function _tearDownAfterClass() { putenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT . '=' . self::$originalEnv['use_fips_endpoint']); + putenv('HOME=' . self::$originalEnv['home']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); - putenv('HOME=' . self::$originalEnv['home']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); } public function testCreatesFromEnvironmentVariables() diff --git a/tests/EndpointDiscovery/ConfigurationProviderTest.php b/tests/EndpointDiscovery/ConfigurationProviderTest.php index ef98cdbc45..f63d7d07da 100644 --- a/tests/EndpointDiscovery/ConfigurationProviderTest.php +++ b/tests/EndpointDiscovery/ConfigurationProviderTest.php @@ -44,6 +44,7 @@ public static function _setUpBeforeClass() 'enabled_alt' => getenv(ConfigurationProvider::ENV_ENABLED_ALT) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -52,6 +53,7 @@ private function clearEnv() putenv(ConfigurationProvider::ENV_ENABLED . '='); putenv(ConfigurationProvider::ENV_ENABLED_ALT . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -70,6 +72,8 @@ public static function _tearDownAfterClass() self::$originalEnv['enabled_alt']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Retry/ConfigurationProviderTest.php b/tests/Retry/ConfigurationProviderTest.php index 5e4a134b30..f9e9e531f1 100644 --- a/tests/Retry/ConfigurationProviderTest.php +++ b/tests/Retry/ConfigurationProviderTest.php @@ -44,6 +44,7 @@ public static function _setUpBeforeClass() 'mode' => getenv(ConfigurationProvider::ENV_MODE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -52,6 +53,7 @@ private function clearEnv() putenv(ConfigurationProvider::ENV_MODE . '='); putenv(ConfigurationProvider::ENV_MAX_ATTEMPTS . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -70,6 +72,8 @@ public static function _tearDownAfterClass() self::$originalEnv['mode']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php index f6d6845496..d04396a643 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php @@ -42,6 +42,7 @@ public static function _setUpBeforeClass() 'endpoints_type' => getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -49,6 +50,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -65,6 +67,8 @@ public static function _tearDownAfterClass() self::$originalEnv['endpoints_type']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/S3/UseArnRegion/ConfigurationProviderTest.php b/tests/S3/UseArnRegion/ConfigurationProviderTest.php index b61a9c27d1..6f1b378426 100644 --- a/tests/S3/UseArnRegion/ConfigurationProviderTest.php +++ b/tests/S3/UseArnRegion/ConfigurationProviderTest.php @@ -39,6 +39,7 @@ public static function _setUpBeforeClass() 'use_arn_region' => getenv(ConfigurationProvider::ENV_USE_ARN_REGION) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -46,6 +47,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_USE_ARN_REGION . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -62,6 +64,8 @@ public static function _tearDownAfterClass() self::$originalEnv['use_arn_region']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index ae60071270..2b720b1582 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -40,6 +40,7 @@ public static function _setUpBeforeClass() 'endpoints_type' => getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', 'home' => getenv('HOME') ?: '', 'profile' => getenv(ConfigurationProvider::ENV_PROFILE) ?: '', + 'config_file' => getenv(ConfigurationProvider::ENV_CONFIG_FILE) ?: '', ]; } @@ -47,6 +48,7 @@ private function clearEnv() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '='); putenv(ConfigurationProvider::ENV_CONFIG_FILE . '='); + putenv(ConfigurationProvider::ENV_PROFILE . '='); $dir = sys_get_temp_dir() . '/.aws'; @@ -63,6 +65,8 @@ public static function _tearDownAfterClass() self::$originalEnv['endpoints_type']); putenv(ConfigurationProvider::ENV_PROFILE . '=' . self::$originalEnv['profile']); + putenv(ConfigurationProvider::ENV_CONFIG_FILE . '=' . + self::$originalEnv['config_file']); putenv('HOME=' . self::$originalEnv['home']); } From 22374fc8e9945f097cccfcaba37644a6fc766c4a Mon Sep 17 00:00:00 2001 From: Zombaya Date: Fri, 18 Mar 2022 11:55:20 +0100 Subject: [PATCH 16/31] Add changelog document --- .changes/nextrelease/php8 | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .changes/nextrelease/php8 diff --git a/.changes/nextrelease/php8 b/.changes/nextrelease/php8 new file mode 100644 index 0000000000..3aac71a472 --- /dev/null +++ b/.changes/nextrelease/php8 @@ -0,0 +1,7 @@ +[ + { + "type": "enhancement", + "category": "", + "description": "Add support for php 8.0 and 8.1" + } +] \ No newline at end of file From 991312f6c4082bbc9486f9a01a4911fa4ce0f842 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Wed, 11 May 2022 16:48:53 +0200 Subject: [PATCH 17/31] Small rewrites of unittests because of deprecation-warnings in phpunit 9.x --- tests/ClientResolverTest.php | 52 ++++++++++++++++++---------------- tests/S3/StreamWrapperTest.php | 4 +-- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index 8da3967fb1..962401ba17 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -825,33 +825,37 @@ public function testUserAgentAlwaysStartsWithSdkAgentString() ->disableOriginalConstructor() ->getMock(); - $request->expects($this->at(0)) + $request->expects($this->exactly(2)) ->method('getHeader') - ->with('X-Amz-User-Agent') - ->willReturn(["MockBuilder"]); - - $request->expects($this->at(1)) - ->method('withHeader') - ->with( - 'X-Amz-User-Agent', - new \PHPUnit\Framework\Constraint\RegularExpression( - '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' - ) - )->willReturn($request); - - $request->expects($this->at(2)) - ->method('getHeader') - ->with('User-Agent') - ->willReturn(['MockBuilder']); + ->withConsecutive( + ['X-Amz-User-Agent'], + ['User-Agent'] + ) + ->willReturnOnConsecutiveCalls( + ["MockBuilder"], + ['MockBuilder'] + ); - $request->expects($this->at(3)) + $request->expects($this->exactly(2)) ->method('withHeader') - ->with( - 'User-Agent', - new \PHPUnit\Framework\Constraint\RegularExpression( - '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' - ) - )->willReturn($request); + ->withConsecutive( + [ + 'X-Amz-User-Agent', + new \PHPUnit\Framework\Constraint\RegularExpression( + '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' + ) + ], + [ + 'User-Agent', + new \PHPUnit\Framework\Constraint\RegularExpression( + '/aws-sdk-php\/' . Sdk::VERSION . '.* MockBuilder/' + ) + ] + ) + ->willReturnOnConsecutiveCalls( + $request, + $request + ); $args = []; $list = new HandlerList(function () {}); diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index 1041cc832a..abf7b99b3d 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -1014,8 +1014,8 @@ public function contentProvider() */ public function testTriggersErrorOnNoFlushOrClose($content) { - $this->expectException(\PHPUnit\Framework\Error\Warning::class); - $this->expectExceptionMessage("Unable to determine stream size. Did you forget to close or flush the stream?"); + $this->expectWarning(); + $this->expectWarning("Unable to determine stream size. Did you forget to close or flush the stream?"); $stream = $this->getMockBuilder(Psr7\Stream::class) ->disableOriginalConstructor() From a57b51f860cd9079e195d220f88864a6d79882c9 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Wed, 11 May 2022 17:10:37 +0200 Subject: [PATCH 18/31] Remove warnings from usage of arguments of wrong type in php 8.1 --- src/Api/Parser/AbstractRestParser.php | 2 +- src/Api/Serializer/JsonBody.php | 2 +- src/Arn/ArnParser.php | 2 +- src/S3/S3Client.php | 2 +- tests/Integ/S3Context.php | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Api/Parser/AbstractRestParser.php b/src/Api/Parser/AbstractRestParser.php index de346b6513..c977588bd9 100644 --- a/src/Api/Parser/AbstractRestParser.php +++ b/src/Api/Parser/AbstractRestParser.php @@ -160,7 +160,7 @@ private function extractHeaders( // Check if the headers are prefixed by a location name $result[$name] = []; $prefix = $shape['locationName']; - $prefixLen = strlen($prefix); + $prefixLen = $prefix !== null ? strlen($prefix) : 0; foreach ($response->getHeaders() as $k => $values) { if (!$prefixLen) { diff --git a/src/Api/Serializer/JsonBody.php b/src/Api/Serializer/JsonBody.php index 4a4fe7f9bb..40e6387d6d 100644 --- a/src/Api/Serializer/JsonBody.php +++ b/src/Api/Serializer/JsonBody.php @@ -29,7 +29,7 @@ public function __construct(Service $api) public static function getContentType(Service $service) { return 'application/x-amz-json-' - . number_format($service->getMetadata('jsonVersion'), 1); + . number_format(($version = $service->getMetadata('jsonVersion')) !== null ? $version : 0.0, 1); } /** diff --git a/src/Arn/ArnParser.php b/src/Arn/ArnParser.php index ae57b26be4..331c507d5c 100644 --- a/src/Arn/ArnParser.php +++ b/src/Arn/ArnParser.php @@ -23,7 +23,7 @@ class ArnParser */ public static function isArn($string) { - return strpos($string, 'arn:') === 0; + return $string !== null && strpos($string, 'arn:') === 0; } /** diff --git a/src/S3/S3Client.php b/src/S3/S3Client.php index 899375ec2d..3ea7a9731b 100644 --- a/src/S3/S3Client.php +++ b/src/S3/S3Client.php @@ -429,7 +429,7 @@ public function __construct(array $args) */ public static function isBucketDnsCompatible($bucket) { - $bucketLen = strlen($bucket); + $bucketLen = $bucket !== null ? strlen($bucket) : 0; return ($bucketLen >= 3 && $bucketLen <= 63) && // Cannot look like an IP address diff --git a/tests/Integ/S3Context.php b/tests/Integ/S3Context.php index 04194f9a74..b08e5571f2 100644 --- a/tests/Integ/S3Context.php +++ b/tests/Integ/S3Context.php @@ -411,7 +411,7 @@ private static function executeWithRetries( throw $e; } $attempts++; - sleep(pow(1.2, $attempts)); + sleep((int) pow(1.2, $attempts)); } } } From f07ec2649297f013e8cef909991eac9e06bbd87f Mon Sep 17 00:00:00 2001 From: Zombaya Date: Tue, 7 Jun 2022 23:00:00 +0200 Subject: [PATCH 19/31] Solve failing unittest CloudFront\SignerTest::testBadPrivateKeyPath() There were remaining error-messages in the openssl-error-stack, resulting in an unexpected result in the unittest. This was solved by outputting all error-messages in Aws\CloudFront\Signer::__construct(). Another option would be to clear all error-messages in Aws\Test\CloudFront\SignerTest::_tearDown(), so tests would no longer interfer with eachother. The first solution was chosen since it would output all openssl-error-messages to the user, not only the first one, making it more complete. --- src/CloudFront/Signer.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/CloudFront/Signer.php b/src/CloudFront/Signer.php index 156570d595..22e55c2a44 100644 --- a/src/CloudFront/Signer.php +++ b/src/CloudFront/Signer.php @@ -34,11 +34,15 @@ public function __construct($keyPairId, $privateKey, $passphrase = "") if (!$this->pkHandle = openssl_pkey_get_private($privateKey, $passphrase)) { if (!file_exists($privateKey)) { throw new \InvalidArgumentException("PK file not found: $privateKey"); - } else { - $this->pkHandle = openssl_pkey_get_private("file://$privateKey", $passphrase); - if (!$this->pkHandle) { - throw new \InvalidArgumentException(openssl_error_string()); + } + + $this->pkHandle = openssl_pkey_get_private("file://$privateKey", $passphrase); + if (!$this->pkHandle) { + $errorMessages = []; + while(($newMessage = openssl_error_string()) !== false){ + $errorMessages[] = $newMessage; } + throw new \InvalidArgumentException(implode("\n",$errorMessages)); } } } From d6474a885e6e877dc9e3fbf714a564555ac7e686 Mon Sep 17 00:00:00 2001 From: Sean O'Brien <60306702+stobrien89@users.noreply.github.com> Date: Thu, 9 Jun 2022 12:27:42 -0500 Subject: [PATCH 20/31] switch to double pipe --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 97aa94391e..2622cbe2aa 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "ext-dom": "*", "ext-pcntl": "*", "ext-sockets": "*", - "phpunit/phpunit": "^4.8.35 || ^5.6.3|^9.5", + "phpunit/phpunit": "^4.8.35 || ^5.6.3 || ^9.5", "behat/behat": "~3.0", "doctrine/cache": "~1.4", "aws/aws-php-sns-message-validator": "~1.0", @@ -41,7 +41,7 @@ "psr/cache": "^1.0", "psr/simple-cache": "^1.0", "paragonie/random_compat": ">= 2", - "sebastian/comparator": "^1.2.3|^4.0" + "sebastian/comparator": "^1.2.3 || ^4.0" }, "suggest": { "ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages", From c2def676807d9d1a6100359b6f27f9409ebc8e01 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Mon, 13 Jun 2022 23:45:26 +0200 Subject: [PATCH 21/31] Formatting fixes --- src/Api/Serializer/JsonBody.php | 7 ++++++- src/S3/S3Client.php | 4 ++++ tests/CloudFront/UrlSignerTest.php | 2 +- tests/EndpointParameterMiddlewareTest.php | 2 +- tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php | 6 +++--- tests/S3/S3ClientTest.php | 9 ++++++++- tests/bootstrap.php | 18 +++++++++--------- 7 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/Api/Serializer/JsonBody.php b/src/Api/Serializer/JsonBody.php index 40e6387d6d..9470c9bbf2 100644 --- a/src/Api/Serializer/JsonBody.php +++ b/src/Api/Serializer/JsonBody.php @@ -29,7 +29,12 @@ public function __construct(Service $api) public static function getContentType(Service $service) { return 'application/x-amz-json-' - . number_format(($version = $service->getMetadata('jsonVersion')) !== null ? $version : 0.0, 1); + . number_format( + ($version = $service->getMetadata('jsonVersion')) !== null + ? $version + : 0.0, + 1 + ); } /** diff --git a/src/S3/S3Client.php b/src/S3/S3Client.php index 3ea7a9731b..51a7401761 100644 --- a/src/S3/S3Client.php +++ b/src/S3/S3Client.php @@ -429,6 +429,10 @@ public function __construct(array $args) */ public static function isBucketDnsCompatible($bucket) { + if (!is_string($bucket)) { + return false; + } + $bucketLen = $bucket !== null ? strlen($bucket) : 0; return ($bucketLen >= 3 && $bucketLen <= 63) && diff --git a/tests/CloudFront/UrlSignerTest.php b/tests/CloudFront/UrlSignerTest.php index 1c9caaeab2..3818887290 100644 --- a/tests/CloudFront/UrlSignerTest.php +++ b/tests/CloudFront/UrlSignerTest.php @@ -46,7 +46,7 @@ public function testCreatesUrlSignersForHttp() $url ); $urlObject = new Uri($url); - $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); + $query = \GuzzleHttp\Psr7\Query::parse($urlObject->getQuery()); $signature = $query['Signature']; $this->assertStringNotContainsString('?', $signature); $this->assertStringNotContainsString('=', $signature); diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 0e8a1c1c7a..62ad7674ba 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -90,7 +90,7 @@ public function testCorrectlyOutputsHost( }); $handler = $list->resolve(); - $handler($command, new Request('POST', $endpoint))->wait(false); + $handler($command, new Request('POST', $endpoint)); } public function getTestCases() diff --git a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php index f10106183e..8ecdd7f639 100644 --- a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php +++ b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php @@ -73,7 +73,7 @@ public function readAttribute($object, $attributeName) } if (isset($attribute)) { - if ( ! $attribute || $attribute->isPublic()) { + if (!$attribute || $attribute->isPublic()) { return $object->$attributeName; } $attribute->setAccessible(true); @@ -109,14 +109,14 @@ public static function invalidArgumentHelper($argument, $type, $value = null) public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = '') { - if ( ! (\is_array($subset) || $subset instanceof ArrayAccess)) { + if (!(\is_array($subset) || $subset instanceof ArrayAccess)) { throw self::invalidArgumentHelper( 1, 'array or ArrayAccess' ); } - if ( ! (\is_array($array) || $array instanceof ArrayAccess)) { + if (!(\is_array($array) || $array instanceof ArrayAccess)) { throw self::invalidArgumentHelper( 2, 'array or ArrayAccess' diff --git a/tests/S3/S3ClientTest.php b/tests/S3/S3ClientTest.php index 5c00ac551b..21363b3522 100644 --- a/tests/S3/S3ClientTest.php +++ b/tests/S3/S3ClientTest.php @@ -69,7 +69,14 @@ public function bucketNameProvider() ['my.bucket.com', true], ['test-fooCaps', false], ['w-w', true], - ['w------', false] + ['w------', false], + ['', false], + [null,false], + [false,false], + [true,false], + [1,false], + [[],false], + [new \stdClass(),false] ]; } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index c4cde91a15..b331f5e341 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -3,21 +3,21 @@ date_default_timezone_set('UTC'); // Include the composer autoloader -$loader = require __DIR__.'/../vendor/autoload.php'; +$loader = require __DIR__ . '/../vendor/autoload.php'; -if ( ! defined('PHPUNIT_COMPOSER_INSTALL')) { - define('PHPUNIT_COMPOSER_INSTALL', __DIR__.'/../vendor/autoload.php'); +if (!defined('PHPUNIT_COMPOSER_INSTALL')) { + define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/../vendor/autoload.php'); } -if ( ! class_exists('\PHPUnit\Framework\Constraint\RegularExpression')) { +if (!class_exists('\PHPUnit\Framework\Constraint\RegularExpression')) { class_alias('\PHPUnit_Framework_Constraint_PCREMatch', '\PHPUnit\Framework\Constraint\RegularExpression'); } -if ( ! class_exists('\PHPUnit\Framework\Constraint\Callback')) { +if (!class_exists('\PHPUnit\Framework\Constraint\Callback')) { class_alias('\PHPUnit_Framework_Constraint_Callback', '\PHPUnit\Framework\Constraint\Callback'); } -if ( ! class_exists('\PHPUnit\Framework\Error\Warning')) { +if (!class_exists('\PHPUnit\Framework\Error\Warning')) { class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warning'); } @@ -26,13 +26,13 @@ class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warnin // Patch PHPUnit class for PHP 7.4+ and PHPUnit 5.x to avoid deprecation warning // Necessary because older versions of PHPUnit are no longer supported -$version = class_exists('PHPUnit_Runner_Version') ? PHPUnit_Runner_Version::id() : PHPUnit\Runner\Version::id(); +$version = class_exists('PHPUnit_Runner_Version') ? PHPUnit_Runner_Version::id() : PHPUnit\Runner\Version::id(); $versionData = explode('.', $version); include_once(sprintf("%s/Polyfill/PHPUnit%s/PHPUnitCompatTrait.php", __DIR__, $versionData[0])); if (PHP_VERSION_ID >= 70400 && $versionData[0] == 5) { - $vendorGeneratorPath = __DIR__.'/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; - $patchGeneratorPath = __DIR__.'/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; + $vendorGeneratorPath = __DIR__ . '/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; + $patchGeneratorPath = __DIR__ . '/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; file_put_contents($vendorGeneratorPath, file_get_contents($patchGeneratorPath)); } From c6f3be2bbf2c7ef1bf9e2a459d57c04c22e0e90e Mon Sep 17 00:00:00 2001 From: Zombaya Date: Mon, 27 Jun 2022 17:53:11 +0200 Subject: [PATCH 22/31] Additional methods added to PHPUnitCompatibilitityTraits --- tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php | 10 ++++++++++ tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php | 12 ++++++++++++ 2 files changed, 22 insertions(+) diff --git a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php index 9af1c4707f..19dd3eab1d 100644 --- a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php +++ b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php @@ -63,6 +63,16 @@ public function expectWarning() $this->expectException(\PHPUnit_Framework_Error_Warning::class); } + public function expectError() + { + $this->expectException(\PHPUnit_Framework_Error::class); + } + + public function expectErrorMessage($message) + { + $this->expectExceptionMessage($message); + } + public function expectExceptionMessageMatches($regularExpression) { $this->expectExceptionMessageRegExp($regularExpression); diff --git a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php index 35eb03eccc..d7218e462a 100644 --- a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php +++ b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php @@ -2,6 +2,8 @@ namespace Aws\Test\Polyfill\PHPUnit; +use PHPUnit\Framework\Error\Error; + trait PHPUnitCompatTrait { private $exceptionCode = null; @@ -51,6 +53,16 @@ public function expectWarning() $this->expectException(\PHPUnit_Framework_Error_Warning::class); } + public function expectError() + { + $this->expectException(\PHPUnit_Framework_Error::class); + } + + public function expectErrorMessage($message) + { + $this->expectExceptionMessage($message); + } + public function expectExceptionMessageMatches($regularExpression) { $this->expectExceptionMessageRegExp($regularExpression); From 71f3ec55880e58b64d0225f7e70c59e618859b30 Mon Sep 17 00:00:00 2001 From: Sean O'Brien Date: Tue, 19 Jul 2022 13:33:07 -0400 Subject: [PATCH 23/31] fix conflicts/warnings --- tests/CloudFront/CloudFrontClientTest.php | 2 +- tests/CloudFront/UrlSignerTest.php | 2 +- tests/EndpointParameterMiddlewareTest.php | 3 +++ tests/S3/S3ClientTest.php | 6 ++--- tests/S3/StreamWrapperV2ExistenceTest.php | 1 + tests/Script/ComposerTest.php | 29 ++++++++++------------- 6 files changed, 22 insertions(+), 21 deletions(-) diff --git a/tests/CloudFront/CloudFrontClientTest.php b/tests/CloudFront/CloudFrontClientTest.php index 64e67425fd..f25450db59 100644 --- a/tests/CloudFront/CloudFrontClientTest.php +++ b/tests/CloudFront/CloudFrontClientTest.php @@ -7,7 +7,7 @@ use PHPUnit\Framework\TestCase; /** - * @covers CloudFrontClient + * @covers Aws\CloudFront\CloudFrontClient */ class CloudFrontClientTest extends TestCase { diff --git a/tests/CloudFront/UrlSignerTest.php b/tests/CloudFront/UrlSignerTest.php index 3818887290..5a10b5162d 100644 --- a/tests/CloudFront/UrlSignerTest.php +++ b/tests/CloudFront/UrlSignerTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; /** - * @covers UrlSigner + * @covers Aws\CloudFront\UrlSigner */ class UrlSignerTest extends TestCase { diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 62ad7674ba..980b11caeb 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -78,6 +78,9 @@ public function testCorrectlyOutputsHost( $endpoint, $expectedHost ) { + if ($cmdName === 'NoEndpointOp') { + $this->expectNotToPerformAssertions(); + } $client = $this->generateTestClient($service, $clientArgs); $command = $client->getCommand($cmdName, $params); diff --git a/tests/S3/S3ClientTest.php b/tests/S3/S3ClientTest.php index 21363b3522..4d008da374 100644 --- a/tests/S3/S3ClientTest.php +++ b/tests/S3/S3ClientTest.php @@ -248,9 +248,9 @@ public function testCreatesPresignedRequestsForObjectLambdaService() ); $url = (string) $client->createPresignedRequest($command, 1342138769)->getUri(); $this->assertStringStartsWith('https://lambda-access-point-123456789012.s3-object-lambda.us-east-1.amazonaws.com/bar?', $url); - $this->assertContains('X-Amz-Expires=', $url); - $this->assertContains('X-Amz-Credential=', $url); - $this->assertContains('X-Amz-Signature=', $url); + $this->assertStringContainsString('X-Amz-Expires=', $url); + $this->assertStringContainsString('X-Amz-Credential=', $url); + $this->assertStringContainsString('X-Amz-Signature=', $url); } public function testRegistersStreamWrapper() diff --git a/tests/S3/StreamWrapperV2ExistenceTest.php b/tests/S3/StreamWrapperV2ExistenceTest.php index 59c885b058..7f0879ca25 100644 --- a/tests/S3/StreamWrapperV2ExistenceTest.php +++ b/tests/S3/StreamWrapperV2ExistenceTest.php @@ -877,6 +877,7 @@ public function testProvidesDirectoriesForS3() public function testCanSetDelimiterStreamContext() { + $this->expectNotToPerformAssertions(); $this->addMockResults($this->client, [ [ 'IsTruncated' => false, diff --git a/tests/Script/ComposerTest.php b/tests/Script/ComposerTest.php index 168b9e0fbd..1f2baa609a 100644 --- a/tests/Script/ComposerTest.php +++ b/tests/Script/ComposerTest.php @@ -3,11 +3,14 @@ use Aws; use Aws\Script\Composer\Composer; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use PHPUnit\Framework\TestCase; use Symfony\Component\Filesystem\Filesystem; class ComposerTest extends TestCase { + use PHPUnitCompatTrait; + public function invalidServiceNameProvider() { return [ @@ -26,27 +29,21 @@ public function invalidServiceNameProvider() */ public function testListInvalidServiceName($serviceList, $invalidService) { - if (method_exists($this, 'expectException')) { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage( - "'$invalidService' is not a valid AWS service namespace. Please check spelling and casing." - ); - } else { - $this->setExpectedException(\InvalidArgumentException::class); - } + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + "'$invalidService' is not a valid AWS service namespace. Please check spelling and casing." + ); + Composer::removeUnusedServices($this->getMockEvent($serviceList)); } public function testNoListedServices() { - if (method_exists($this, 'expectException')) { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage( - "There are no services listed. Did you intend to use this script?" - ); - } else { - $this->setExpectedException(\InvalidArgumentException::class); - } + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage( + "There are no services listed. Did you intend to use this script?" + ); + Composer::removeUnusedServices($this->getMockEvent([])); } From f49a0ef9f75fc43cbf8d8dad127767d40d1c4d66 Mon Sep 17 00:00:00 2001 From: Sean O'Brien Date: Thu, 21 Jul 2022 19:17:21 -0400 Subject: [PATCH 24/31] refactor jsonbody getcontenttype --- src/Api/Serializer/JsonBody.php | 9 +++++++-- tests/Api/Parser/ParserTestServiceTrait.php | 13 +++++++++---- tests/Api/ServiceTest.php | 6 +++++- tests/Api/test_cases/protocols/input/json.json | 3 ++- tests/EndpointParameterMiddlewareTest.php | 3 ++- tests/InputValidationMiddlewareTest.php | 3 ++- tests/TestServiceTrait.php | 13 +++++++++---- tests/TraceMiddlewareTest.php | 3 ++- tests/WaiterTest.php | 1 + 9 files changed, 39 insertions(+), 15 deletions(-) diff --git a/src/Api/Serializer/JsonBody.php b/src/Api/Serializer/JsonBody.php index ba8b2c5298..39838b64b4 100644 --- a/src/Api/Serializer/JsonBody.php +++ b/src/Api/Serializer/JsonBody.php @@ -32,8 +32,13 @@ public static function getContentType(Service $service) return 'application/json'; } - return 'application/x-amz-json-' - . @number_format($service->getMetadata('jsonVersion'), 1); + $jsonVersion = $service->getMetadata('jsonVersion'); + if (empty($jsonVersion)) { + throw new \InvalidArgumentException('invalid json'); + }else { + return 'application/x-amz-json-' + . @number_format($service->getMetadata('jsonVersion'), 1); + } } /** diff --git a/tests/Api/Parser/ParserTestServiceTrait.php b/tests/Api/Parser/ParserTestServiceTrait.php index a991e4ac92..3bbb2a9012 100644 --- a/tests/Api/Parser/ParserTestServiceTrait.php +++ b/tests/Api/Parser/ParserTestServiceTrait.php @@ -48,12 +48,17 @@ private function generateTestClient(Service $service, $content) */ private function generateTestService($protocol) { + $metadata = [ + "protocol" => "{$protocol}", + "apiVersion" => "2014-01-01" + ]; + if ($protocol === 'json') { + $metadata['jsonVersion'] = "1.1"; + } + return new Service( [ - 'metadata' => [ - "protocol" => "{$protocol}", - "apiVersion" => "2014-01-01" - ], + 'metadata' => $metadata, 'shapes' => [ "ParseIso8601Response" => [ "type" => "structure", diff --git a/tests/Api/ServiceTest.php b/tests/Api/ServiceTest.php index 6313559285..8f23587a5f 100644 --- a/tests/Api/ServiceTest.php +++ b/tests/Api/ServiceTest.php @@ -181,8 +181,12 @@ public function serializerDataProvider() */ public function testCreatesSerializer($type, $cl) { + $data = ['metadata' => ['protocol' => $type]]; + if ($type === 'json') { + $data['metadata']['jsonVersion'] = '1.1'; + } $service = new Service( - ['metadata' => ['protocol' => $type]], + $data, function () { return []; } ); $serializer = Service::createSerializer($service, $type); diff --git a/tests/Api/test_cases/protocols/input/json.json b/tests/Api/test_cases/protocols/input/json.json index 4f017d67f2..38fb14ee60 100644 --- a/tests/Api/test_cases/protocols/input/json.json +++ b/tests/Api/test_cases/protocols/input/json.json @@ -495,7 +495,8 @@ "description": "Idempotency token auto fill", "metadata": { "protocol": "json", - "apiVersion": "2014-01-01" + "apiVersion": "2014-01-01", + "jsonVersion": "1.1" }, "shapes": { "InputShape": { diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 980b11caeb..650b2203e6 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -185,7 +185,8 @@ private function generateTestService() [ 'metadata' => [ "protocol" => "json", - "apiVersion" => "2014-01-01" + "apiVersion" => "2014-01-01", + 'jsonVersion' => "1.1" ], 'shapes' => [ "StaticInputShape" => [ diff --git a/tests/InputValidationMiddlewareTest.php b/tests/InputValidationMiddlewareTest.php index fcac7834e6..3dd52a3b55 100644 --- a/tests/InputValidationMiddlewareTest.php +++ b/tests/InputValidationMiddlewareTest.php @@ -152,7 +152,8 @@ private function generateTestService() [ 'metadata' => [ "protocol" => "json", - "apiVersion" => "2014-01-01" + "apiVersion" => "2014-01-01", + "jsonVersion" => "1.1" ], 'shapes' => [ "InputShape" => [ diff --git a/tests/TestServiceTrait.php b/tests/TestServiceTrait.php index 0845197e46..19707d4573 100644 --- a/tests/TestServiceTrait.php +++ b/tests/TestServiceTrait.php @@ -39,12 +39,17 @@ private function generateTestClient(Service $service, $args = []) */ private function generateTestService($protocol) { + $metadata = [ + "protocol" => $protocol, + "apiVersion" => "2019-05-01" + ]; + if ($protocol === 'json') { + $metadata['jsonVersion'] = "1.1"; + } + return new Service( [ - 'metadata' => [ - "protocol" => $protocol, - "apiVersion" => "2019-05-01" - ], + 'metadata' => $metadata, 'shapes' => [ "HeaderMap"=> [ "type"=> "map", diff --git a/tests/TraceMiddlewareTest.php b/tests/TraceMiddlewareTest.php index 4fb528d2c7..b5fca3fcf5 100644 --- a/tests/TraceMiddlewareTest.php +++ b/tests/TraceMiddlewareTest.php @@ -305,7 +305,8 @@ private function generateTestService() [ 'metadata' => [ "protocol" => "json", - "apiVersion" => "2014-01-01" + "apiVersion" => "2014-01-01", + "jsonVersion" => "1.1" ], 'shapes' => [ "InputShape" => [ diff --git a/tests/WaiterTest.php b/tests/WaiterTest.php index 2387f0d534..7b22116918 100644 --- a/tests/WaiterTest.php +++ b/tests/WaiterTest.php @@ -221,6 +221,7 @@ private function getApiProvider() 'metadata' => [ 'endpointPrefix' => 'foo', 'protocol' => 'json', + 'jsonVersion' => '1.1', 'signatureVersion' => 'v4' ], ]; From ceb60ccdf4e08f8e5e50be4705e2f94c313ced9f Mon Sep 17 00:00:00 2001 From: Sean O'Brien Date: Thu, 4 Aug 2022 14:37:16 -0400 Subject: [PATCH 25/31] add compattrait to endpointparametermiddlewaretest --- tests/EndpointParameterMiddlewareTest.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 650b2203e6..c4f4553aa2 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -5,6 +5,7 @@ use Aws\EndpointParameterMiddleware; use Aws\HandlerList; use Aws\Api\Service; +use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; @@ -13,6 +14,7 @@ */ class EndpointParameterMiddlewareTest extends TestCase { + use PHPUnitCompatTrait public function testThrowsExceptionForMissingParameter() { From 7ce24b426920bb6369e5c09037622ba68ff30657 Mon Sep 17 00:00:00 2001 From: Sean O'Brien Date: Thu, 4 Aug 2022 14:44:18 -0400 Subject: [PATCH 26/31] add compattrait to endpointparametermiddlewaretest --- tests/EndpointParameterMiddlewareTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index c4f4553aa2..66ef283c6b 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -14,7 +14,7 @@ */ class EndpointParameterMiddlewareTest extends TestCase { - use PHPUnitCompatTrait + use PHPUnitCompatTrait; public function testThrowsExceptionForMissingParameter() { From 6d1e8aa319e45320479076d1d02bcfcf66292d26 Mon Sep 17 00:00:00 2001 From: Sean O'Brien Date: Thu, 4 Aug 2022 16:11:04 -0400 Subject: [PATCH 27/31] add update to instanceprofileprovider --- src/Credentials/InstanceProfileProvider.php | 2 +- .../InstanceProfileProviderTest.php | 44 ++++++++++++++++--- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/src/Credentials/InstanceProfileProvider.php b/src/Credentials/InstanceProfileProvider.php index effa857849..0f1fcb126d 100644 --- a/src/Credentials/InstanceProfileProvider.php +++ b/src/Credentials/InstanceProfileProvider.php @@ -56,7 +56,6 @@ public function __construct(array $config = []) $this->timeout = (float) getenv(self::ENV_TIMEOUT) ?: (isset($config['timeout']) ? $config['timeout'] : 1.0); $this->profile = isset($config['profile']) ? $config['profile'] : null; $this->retries = (int) getenv(self::ENV_RETRIES) ?: (isset($config['retries']) ? $config['retries'] : 3); - $this->attempts = 0; $this->client = isset($config['client']) ? $config['client'] // internal use only : \Aws\default_http_handler(); @@ -69,6 +68,7 @@ public function __construct(array $config = []) */ public function __invoke($previousCredentials = null) { + $this->attempts = 0; return Promise\Coroutine::of(function () use ($previousCredentials) { // Retrieve token or switch out of secure mode diff --git a/tests/Credentials/InstanceProfileProviderTest.php b/tests/Credentials/InstanceProfileProviderTest.php index 4c87a66973..ea6059fd5c 100644 --- a/tests/Credentials/InstanceProfileProviderTest.php +++ b/tests/Credentials/InstanceProfileProviderTest.php @@ -303,7 +303,8 @@ private function getInsecureTestClient( */ public function testHandlesSuccessScenarios( callable $client, - CredentialsInterface $expected + CredentialsInterface $expected, + $expectedAttempts = null ) { $provider = new InstanceProfileProvider([ 'client' => $client, @@ -328,6 +329,9 @@ public function testHandlesSuccessScenarios( $expected->getExpiration(), $credentials->getExpiration() ); + if ($expectedAttempts) { + $this->assertEquals($expectedAttempts, $this->readAttribute($provider, 'attempts')); + } } public function successTestCases() @@ -412,7 +416,8 @@ public function successTestCases() 'MockProfile', $creds ), - $credsObject + $credsObject, + 6 ], // Insecure data flow, with retries for request exception @@ -431,7 +436,8 @@ public function successTestCases() 'MockProfile', $creds ), - $credsObject + $credsObject, + 5 ], // Secure data flow, with retries for json exception @@ -446,7 +452,8 @@ public function successTestCases() 'MockProfile', $creds ), - $credsObject + $credsObject, + 4 ], // Insecure data flow, with retries for json exception @@ -461,7 +468,8 @@ public function successTestCases() 'MockProfile', $creds ), - $credsObject + $credsObject, + 4 ], // Secure data flow, with retries for ConnectException (Guzzle 7) @@ -489,7 +497,8 @@ public function successTestCases() $creds, true ), - $credsObject + $credsObject, + 6 ], // Insecure data flow, with retries for ConnectException (Guzzle 7) @@ -509,7 +518,8 @@ public function successTestCases() $creds, true ), - $credsObject + $credsObject, + 5 ], ]; } @@ -1178,4 +1188,24 @@ public function imdsUnavailableProvider() ] ]; } + + public function testResetsAttempts() + { + $now = time() + 10000; + $creds = ['foo', 'baz', null, "@{$now}"]; + + $client = $this->getSecureTestClient( + [], + 'MockProfile', + $creds + ); + + $provider = new InstanceProfileProvider([ + 'client' => $client + ]); + + $provider()->wait(); + $provider()->wait(); + $this->assertLessThanOrEqual(3, $this->readAttribute($provider, 'attempts')); + } } From 9634dfac82736788a35715b42bfbe849e1e54c6b Mon Sep 17 00:00:00 2001 From: Zombaya Date: Thu, 11 Aug 2022 20:57:12 +0200 Subject: [PATCH 28/31] Replace PHPUnitCompatTrait with packages yoast/phpunit-polyfills and dms/phpunit-arraysubset-asserts --- composer.json | 4 +- tests/AbstractConfigurationProviderTest.php | 5 +- tests/Api/ApiProviderTest.php | 7 +- tests/Api/ErrorParser/XmlErrorParserTest.php | 6 +- tests/Api/ListShapeTest.php | 5 +- tests/Api/MapShapeTest.php | 5 +- tests/Api/OperationTest.php | 5 +- .../Api/Parser/Crc32ValidatingParserTest.php | 5 +- .../DecodingEventStreamIteratorTest.php | 5 +- tests/Api/Parser/EventParsingIteratorTest.php | 7 +- tests/Api/Parser/JsonParserTest.php | 4 +- tests/Api/Parser/XmlParserTest.php | 6 +- .../Api/Serializer/RestJsonSerializerTest.php | 4 +- .../Api/Serializer/RestXmlSerializerTest.php | 4 +- tests/Api/ServiceTest.php | 6 +- tests/Api/ShapeMapTest.php | 5 +- tests/Api/ShapeTest.php | 5 +- tests/Api/StructureShapeTest.php | 5 +- tests/Api/TimestampShapeTest.php | 5 +- tests/Api/ValidatorTest.php | 5 +- tests/AwsClientTest.php | 6 +- .../Build/Changelog/ChangelogBuilderTest.php | 5 +- tests/ClientResolverTest.php | 6 +- .../ConfigurationProviderTest.php | 8 +- .../ConfigurationTest.php | 5 +- .../MonitoringMiddlewareTestingTrait.php | 6 +- tests/CloudFront/CloudFrontClientTest.php | 7 +- tests/CloudFront/CookieSignerTest.php | 7 +- tests/CloudFront/SignerTest.php | 7 +- tests/CloudFront/UrlSignerTest.php | 6 +- .../CloudSearchDomainTest.php | 5 +- tests/CloudTrail/LogFileIteratorTest.php | 4 +- .../CognitoIdentityProviderTest.php | 7 +- tests/CognitoSync/CognitoSyncClientTest.php | 4 +- tests/CommandPoolTest.php | 4 +- .../AssumeRoleCredentialProviderTest.php | 4 +- ...eWithWebIdentityCredentialProviderTest.php | 4 +- tests/Credentials/CredentialProviderTest.php | 8 +- .../Credentials/EcsCredentialProviderTest.php | 9 +- .../InstanceProfileProviderTest.php | 17 +-- tests/Crypto/AesDecryptingStreamTest.php | 4 +- tests/Crypto/AesEncryptingStreamTest.php | 4 +- tests/Crypto/AesGcmDecryptingStreamTest.php | 4 +- tests/Crypto/AesGcmEncryptingStreamTest.php | 8 +- tests/Crypto/Cipher/CbcTest.php | 5 +- tests/Crypto/KmsMaterialsProviderV2Test.php | 4 +- tests/Crypto/MetadataEnvelopeTest.php | 4 +- tests/Crypto/Polyfill/KeyTest.php | 5 +- .../ConfigurationProviderTest.php | 9 +- tests/DefaultsMode/ConfigurationTest.php | 5 +- tests/DocDb/DocDbClientTest.php | 9 +- tests/DynamoDb/DynamoDbClientTest.php | 6 +- tests/DynamoDb/MarshalerTest.php | 5 +- tests/DynamoDb/SessionHandlerTest.php | 8 +- .../StandardSessionConnectionTest.php | 4 +- tests/DynamoDb/WriteRequestBatchTest.php | 20 ++- tests/Endpoint/EndpointProviderTest.php | 5 +- tests/Endpoint/PartitionTest.php | 5 +- .../ConfigurationProviderTest.php | 9 +- .../ConfigurationTest.php | 5 +- .../ConfigurationProviderTest.php | 9 +- .../UseFipsEndpoint/ConfigurationTest.php | 5 +- .../ConfigurationProviderTest.php | 9 +- tests/EndpointDiscovery/ConfigurationTest.php | 5 +- .../EndpointDiscoveryMiddlewareTest.php | 4 +- tests/EndpointParameterMiddlewareTest.php | 5 +- .../EventBridgeEndpointMiddlewareTest.php | 4 +- tests/FunctionsTest.php | 5 +- tests/Glacier/GlacierClientTest.php | 4 +- tests/Glacier/TreeHashTest.php | 5 +- tests/Handler/GuzzleV5/HandlerTest.php | 7 +- tests/Handler/GuzzleV5/StreamTest.php | 7 +- tests/Handler/GuzzleV6/HandlerTest.php | 7 +- tests/HandlerListTest.php | 5 +- tests/HistoryTest.php | 4 +- tests/IdempotencyTokenMiddlewareTest.php | 5 +- tests/Integ/GuzzleV5HandlerTest.php | 7 +- tests/Integ/GuzzleV6StreamHandlerTest.php | 6 +- tests/JsonCompilerTest.php | 7 +- tests/Lambda/LambdaClientTest.php | 6 +- tests/MiddlewareTest.php | 7 +- tests/MockHandlerTest.php | 5 +- tests/MultiRegionClientTest.php | 7 +- tests/Multipart/AbstractUploaderTest.php | 6 +- tests/Neptune/NeptuneClientTest.php | 9 +- tests/Polly/PollyClientTest.php | 5 +- .../Polyfill/PHPUnit4/PHPUnitCompatTrait.php | 141 ------------------ .../Polyfill/PHPUnit5/PHPUnitCompatTrait.php | 131 ---------------- tests/Polyfill/PHPUnit9/ArraySubset.php | 133 ----------------- .../Polyfill/PHPUnit9/PHPUnitCompatTrait.php | 130 ---------------- tests/PresignUrlMiddlewareTest.php | 4 +- tests/Psr16CacheAdapterTest.php | 7 +- tests/PsrCacheAdapterTest.php | 6 +- tests/Rds/AuthTokenGeneratorTest.php | 5 +- tests/Rds/RdsClientTest.php | 9 +- tests/ResultPaginatorTest.php | 10 +- tests/ResultTest.php | 5 +- tests/Retry/ConfigurationProviderTest.php | 9 +- tests/Retry/ConfigurationTest.php | 5 +- tests/RetryMiddlewareTest.php | 5 +- tests/RetryMiddlewareV2Test.php | 4 +- tests/Route53/RouteClient53Test.php | 5 +- tests/S3/AmbiguousSuccessParserTest.php | 7 +- tests/S3/BatchDeleteTest.php | 4 +- tests/S3/BucketEndpointArnMiddlewareTest.php | 4 +- tests/S3/Crypto/S3EncryptionClientTest.php | 4 +- tests/S3/Crypto/S3EncryptionClientV2Test.php | 4 +- .../S3EncryptionMultipartUploaderTest.php | 5 +- .../S3EncryptionMultipartUploaderV2Test.php | 5 +- .../DeleteMultipleObjectsExceptionTest.php | 5 +- tests/S3/MultipartUploaderTest.php | 6 +- tests/S3/PermanentRedirectMiddlewareTest.php | 4 +- tests/S3/PostObjectTest.php | 6 +- tests/S3/PostObjectV4Test.php | 10 +- .../ConfigurationProviderTest.php | 9 +- .../S3/RegionalEndpoint/ConfigurationTest.php | 5 +- .../RetryableMalformedResponseParserTest.php | 5 +- tests/S3/S3ClientTest.php | 4 +- tests/S3/S3EndpointMiddlewareTest.php | 4 +- tests/S3/S3MultiRegionClientTest.php | 10 +- tests/S3/S3UriParserTest.php | 5 +- tests/S3/SSECMiddlewareTest.php | 4 +- tests/S3/StreamWrapperPathStyleTest.php | 8 +- tests/S3/StreamWrapperTest.php | 8 +- tests/S3/StreamWrapperV2ExistenceTest.php | 8 +- tests/S3/TransferTest.php | 4 +- .../ConfigurationProviderTest.php | 9 +- tests/S3/UseArnRegion/ConfigurationTest.php | 5 +- tests/S3Control/EndpointArnMiddlewareTest.php | 4 +- tests/Script/ComposerTest.php | 5 +- tests/SdkTest.php | 4 +- tests/Signature/S3SignatureV4Test.php | 10 +- tests/Signature/SignatureProviderTest.php | 5 +- tests/Signature/SignatureV4Test.php | 23 ++- tests/Sqs/SqsClientTest.php | 4 +- tests/StreamRequestPayloadMiddlewareTest.php | 6 +- .../ConfigurationProviderTest.php | 9 +- .../RegionalEndpoints/ConfigurationTest.php | 5 +- tests/Sts/StsClientTest.php | 5 +- tests/TraceMiddlewareTest.php | 5 +- tests/WaiterTest.php | 4 +- tests/WrappedHttpHandlerTest.php | 4 +- tests/bootstrap.php | 2 - 143 files changed, 248 insertions(+), 1123 deletions(-) delete mode 100644 tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php delete mode 100644 tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php delete mode 100644 tests/Polyfill/PHPUnit9/ArraySubset.php delete mode 100644 tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php diff --git a/composer.json b/composer.json index 2622cbe2aa..d481a12a99 100644 --- a/composer.json +++ b/composer.json @@ -41,7 +41,9 @@ "psr/cache": "^1.0", "psr/simple-cache": "^1.0", "paragonie/random_compat": ">= 2", - "sebastian/comparator": "^1.2.3 || ^4.0" + "sebastian/comparator": "^1.2.3 || ^4.0", + "yoast/phpunit-polyfills": "^1.0", + "dms/phpunit-arraysubset-asserts": "^0.4.0" }, "suggest": { "ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages", diff --git a/tests/AbstractConfigurationProviderTest.php b/tests/AbstractConfigurationProviderTest.php index 8ed3a04275..af369f504e 100644 --- a/tests/AbstractConfigurationProviderTest.php +++ b/tests/AbstractConfigurationProviderTest.php @@ -5,17 +5,14 @@ use Aws\LruArrayCache; use Aws\Result; use Aws\ResultInterface; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\AbstractConfigurationProvider */ class AbstractConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - /** @var \PHPUnit_Framework_MockObject_MockObject */ private $provider; diff --git a/tests/Api/ApiProviderTest.php b/tests/Api/ApiProviderTest.php index 16e98537d4..350daa7f6c 100644 --- a/tests/Api/ApiProviderTest.php +++ b/tests/Api/ApiProviderTest.php @@ -3,16 +3,13 @@ use Aws\Api\ApiProvider; use Aws\Exception\UnresolvedApiException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Api\ApiProvider */ class ApiProviderTest extends TestCase { - use PHPUnitCompatTrait; - /** * @return ApiProvider; */ @@ -56,7 +53,7 @@ public function testCanGetServiceVersions() public function testCanGetDefaultProvider() { $p = ApiProvider::defaultProvider(); - $this->assertArrayHasKey('s3', $this->readAttribute($p, 'manifest')); + $this->assertArrayHasKey('s3', $this->getPropertyValue($p, 'manifest')); } public function testManifestProviderReturnsNullForMissingService() diff --git a/tests/Api/ErrorParser/XmlErrorParserTest.php b/tests/Api/ErrorParser/XmlErrorParserTest.php index 6a87c23703..3bc73e5f19 100644 --- a/tests/Api/ErrorParser/XmlErrorParserTest.php +++ b/tests/Api/ErrorParser/XmlErrorParserTest.php @@ -2,17 +2,17 @@ namespace Aws\Test\Api\ErrorParser; use Aws\Api\ErrorParser\XmlErrorParser; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\TestServiceTrait; +use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Api\ErrorParser\XmlErrorParser */ class XmlErrorParserTest extends TestCase { - use PHPUnitCompatTrait; + use ArraySubsetAsserts; use TestServiceTrait; /** diff --git a/tests/Api/ListShapeTest.php b/tests/Api/ListShapeTest.php index a14f702998..a6f5f3a456 100644 --- a/tests/Api/ListShapeTest.php +++ b/tests/Api/ListShapeTest.php @@ -3,16 +3,13 @@ use Aws\Api\ShapeMap; use Aws\Api\ListShape; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\ListShape */ class ListShapeTest extends TestCase { - use PHPUnitCompatTrait; - public function testReturnsMember() { $s = new ListShape( diff --git a/tests/Api/MapShapeTest.php b/tests/Api/MapShapeTest.php index c1c14633fe..9e5248994a 100644 --- a/tests/Api/MapShapeTest.php +++ b/tests/Api/MapShapeTest.php @@ -3,16 +3,13 @@ use Aws\Api\ShapeMap; use Aws\Api\MapShape; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\MapShape */ class MapShapeTest extends TestCase { - use PHPUnitCompatTrait; - public function testReturnsValue() { $s = new MapShape(['value' => ['type' => 'string']], new ShapeMap([])); diff --git a/tests/Api/OperationTest.php b/tests/Api/OperationTest.php index 2a0e9f2614..319793e034 100644 --- a/tests/Api/OperationTest.php +++ b/tests/Api/OperationTest.php @@ -3,16 +3,13 @@ use Aws\Api\ShapeMap; use Aws\Api\Operation; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\Operation */ class OperationTest extends TestCase { - use PHPUnitCompatTrait; - public function testCreatesDefaultMethodAndUri() { $o = new Operation([], new ShapeMap([])); diff --git a/tests/Api/Parser/Crc32ValidatingParserTest.php b/tests/Api/Parser/Crc32ValidatingParserTest.php index 7fbc169176..128c536abe 100644 --- a/tests/Api/Parser/Crc32ValidatingParserTest.php +++ b/tests/Api/Parser/Crc32ValidatingParserTest.php @@ -7,17 +7,14 @@ use Aws\Api\Service; use Aws\Command; use Aws\Exception\AwsException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Response; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Api\Parser\Crc32ValidatingParser */ class Crc32ValidatingParserTest extends TestCase { - use PHPUnitCompatTrait; - private function getWrapped() { $provider = ApiProvider::defaultProvider(); diff --git a/tests/Api/Parser/DecodingEventStreamIteratorTest.php b/tests/Api/Parser/DecodingEventStreamIteratorTest.php index 201881458c..5937a3c8d7 100644 --- a/tests/Api/Parser/DecodingEventStreamIteratorTest.php +++ b/tests/Api/Parser/DecodingEventStreamIteratorTest.php @@ -4,18 +4,15 @@ use Aws\Api\Parser\DecodingEventStreamIterator; use Aws\Api\Parser\Exception\ParserException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Stream; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Api\Parser\DecodingEventStreamIterator */ class DecodingEventStreamIteratorTest extends TestCase { - use PHPUnitCompatTrait; - public function complianceTests() { $cases = []; diff --git a/tests/Api/Parser/EventParsingIteratorTest.php b/tests/Api/Parser/EventParsingIteratorTest.php index e73a9b35c4..be55616f82 100644 --- a/tests/Api/Parser/EventParsingIteratorTest.php +++ b/tests/Api/Parser/EventParsingIteratorTest.php @@ -9,18 +9,15 @@ use Aws\Api\ShapeMap; use Aws\Api\StructureShape; use Aws\Exception\EventStreamDataException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Api\Parser\EventParsingIterator */ class EventParsingIteratorTest extends TestCase { - use PHPUnitCompatTrait; - /** @var array */ private static $successEventNames = [ 'end_event', @@ -32,7 +29,7 @@ class EventParsingIteratorTest extends TestCase /** @var StructureShape */ private $eventstreamShape; - public function _setUp() + public function set_up() { $shape = json_decode( file_get_contents( diff --git a/tests/Api/Parser/JsonParserTest.php b/tests/Api/Parser/JsonParserTest.php index 4368c8b948..0c8f3c51d0 100644 --- a/tests/Api/Parser/JsonParserTest.php +++ b/tests/Api/Parser/JsonParserTest.php @@ -2,8 +2,7 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * This class tests the custom functionality of the JsonParser; @@ -13,7 +12,6 @@ */ class JsonParserTest extends TestCase { - use PHPUnitCompatTrait; use ParserTestServiceTrait; public function timeStampModelProvider() diff --git a/tests/Api/Parser/XmlParserTest.php b/tests/Api/Parser/XmlParserTest.php index ed831ceb70..50190e379f 100644 --- a/tests/Api/Parser/XmlParserTest.php +++ b/tests/Api/Parser/XmlParserTest.php @@ -2,10 +2,7 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; - -; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * This class tests the custom functionality of the XmlParser; @@ -15,7 +12,6 @@ */ class XmlParserTest extends TestCase { - use PHPUnitCompatTrait; use ParserTestServiceTrait; public function timeStampModelProvider() diff --git a/tests/Api/Serializer/RestJsonSerializerTest.php b/tests/Api/Serializer/RestJsonSerializerTest.php index 89320c7f33..21706f0112 100644 --- a/tests/Api/Serializer/RestJsonSerializerTest.php +++ b/tests/Api/Serializer/RestJsonSerializerTest.php @@ -4,16 +4,14 @@ use Aws\Api\Service; use Aws\Command; use Aws\Api\Serializer\RestJsonSerializer; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Api\Serializer\RestJsonSerializer */ class RestJsonSerializerTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; private function getTestService() diff --git a/tests/Api/Serializer/RestXmlSerializerTest.php b/tests/Api/Serializer/RestXmlSerializerTest.php index 5db0a6e040..6269284a6d 100644 --- a/tests/Api/Serializer/RestXmlSerializerTest.php +++ b/tests/Api/Serializer/RestXmlSerializerTest.php @@ -2,16 +2,14 @@ namespace Aws\Test\Api\Serializer; use Aws\Api\Serializer\RestXmlSerializer; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Api\Serializer\RestXmlSerializer */ class RestXmlSerializerTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; private function getRequest($commandName, $input) diff --git a/tests/Api/ServiceTest.php b/tests/Api/ServiceTest.php index 8f23587a5f..2fa69d0fde 100644 --- a/tests/Api/ServiceTest.php +++ b/tests/Api/ServiceTest.php @@ -4,17 +4,15 @@ use Aws\Api\Parser\QueryParser; use Aws\Api\Service; use Aws\Api\StructureShape; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\TestServiceTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\Service */ class ServiceTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; use TestServiceTrait; @@ -219,7 +217,7 @@ function () { return []; } if ($parser instanceof QueryParser) { $this->assertInstanceOf( 'Aws\Api\Parser\XmlParser', - $this->readAttribute($parser, 'parser') + $this->getPropertyValue($parser, 'parser') ); } } diff --git a/tests/Api/ShapeMapTest.php b/tests/Api/ShapeMapTest.php index 4bc2ca3e60..2a22f425df 100644 --- a/tests/Api/ShapeMapTest.php +++ b/tests/Api/ShapeMapTest.php @@ -2,16 +2,13 @@ namespace Aws\Test\Api; use Aws\Api\ShapeMap; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\ShapeMap */ class ShapeMapTest extends TestCase { - use PHPUnitCompatTrait; - public function testReturnsShapeName() { $sm = new ShapeMap(['foo' => [], 'baz' => []]); diff --git a/tests/Api/ShapeTest.php b/tests/Api/ShapeTest.php index b72125d918..10bff1909a 100644 --- a/tests/Api/ShapeTest.php +++ b/tests/Api/ShapeTest.php @@ -3,8 +3,7 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\Shape @@ -12,8 +11,6 @@ */ class ShapeTest extends TestCase { - use PHPUnitCompatTrait; - public function testImplementsArray() { $s = new Shape(['metadata' => ['foo' => 'bar']], new ShapeMap([])); diff --git a/tests/Api/StructureShapeTest.php b/tests/Api/StructureShapeTest.php index c92f6f7c32..43ee121a2f 100644 --- a/tests/Api/StructureShapeTest.php +++ b/tests/Api/StructureShapeTest.php @@ -3,16 +3,13 @@ use Aws\Api\ShapeMap; use Aws\Api\StructureShape; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\StructureShape */ class StructureShapeTest extends TestCase { - use PHPUnitCompatTrait; - public function testReturnsWhenMembersAreEmpty() { $s = new StructureShape([], new ShapeMap([])); diff --git a/tests/Api/TimestampShapeTest.php b/tests/Api/TimestampShapeTest.php index ef4fe70c83..230c60de77 100644 --- a/tests/Api/TimestampShapeTest.php +++ b/tests/Api/TimestampShapeTest.php @@ -3,16 +3,13 @@ use Aws\Api\TimestampShape; use Aws\Api\ShapeMap; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Api\TimestampShape */ class TimestampShapeTest extends TestCase { - use PHPUnitCompatTrait; - public function formatProvider() { $t = strtotime('january 5, 1999'); diff --git a/tests/Api/ValidatorTest.php b/tests/Api/ValidatorTest.php index caa6fec8a2..719d499197 100644 --- a/tests/Api/ValidatorTest.php +++ b/tests/Api/ValidatorTest.php @@ -4,17 +4,14 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Aws\Api\Validator; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; /** * @covers Aws\Api\Validator */ class ValidatorTest extends TestCase { - use PHPUnitCompatTrait; - public function validationProvider() { return [ diff --git a/tests/AwsClientTest.php b/tests/AwsClientTest.php index 510ef8d2a7..49216ff456 100644 --- a/tests/AwsClientTest.php +++ b/tests/AwsClientTest.php @@ -15,18 +15,16 @@ use Aws\S3\S3Client; use Aws\Signature\SignatureV4; use Aws\Sts\StsClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\WrappedHttpHandler; use GuzzleHttp\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\AwsClient */ class AwsClientTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; private function getApiProvider() @@ -57,7 +55,7 @@ public function testHasGetters() ]; $client = new AwsClient($config); - $this->assertSame($config['handler'], $this->readAttribute($client->getHandlerList(), 'handler')); + $this->assertSame($config['handler'], $this->getPropertyValue($client->getHandlerList(), 'handler')); $this->assertSame($config['credentials'], $client->getCredentials()->wait()); $this->assertSame($config['region'], $client->getRegion()); $this->assertSame('foo', $client->getApi()->getEndpointPrefix()); diff --git a/tests/Build/Changelog/ChangelogBuilderTest.php b/tests/Build/Changelog/ChangelogBuilderTest.php index 3ddf1936d8..a6ffcdb5b4 100644 --- a/tests/Build/Changelog/ChangelogBuilderTest.php +++ b/tests/Build/Changelog/ChangelogBuilderTest.php @@ -2,16 +2,13 @@ namespace Aws\Test\Build\Changelog; use Aws\Build\Changelog\ChangelogBuilder; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Build\Changelog\ChangelogBuilder */ class ChangelogBuilderTest extends TestCase { - use PHPUnitCompatTrait; - private $RESOURCE_DIR = "tests/Build/Changelog/resources/"; public function testBuildChangelogNoDirectory() diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index 962401ba17..0580817cc8 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -16,16 +16,14 @@ use Aws\HandlerList; use Aws\Sdk; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\ClientResolver */ class ClientResolverTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testEnsuresRequiredArgumentsAreProvided() @@ -795,7 +793,7 @@ public function testAddsTraceMiddleware() 'version' => 'latest', 'debug' => ['logfn' => function ($value) use (&$str) { $str .= $value; }] ], $list); - $value = $this->readAttribute($list, 'interposeFn'); + $value = $this->getPropertyValue($list, 'interposeFn'); $this->assertIsCallable($value); } diff --git a/tests/ClientSideMonitoring/ConfigurationProviderTest.php b/tests/ClientSideMonitoring/ConfigurationProviderTest.php index 04b6a1a2a7..bc50ca0b0f 100644 --- a/tests/ClientSideMonitoring/ConfigurationProviderTest.php +++ b/tests/ClientSideMonitoring/ConfigurationProviderTest.php @@ -7,9 +7,8 @@ use Aws\ClientSideMonitoring\ConfigurationProvider; use Aws\ClientSideMonitoring\Exception\ConfigurationException; use Aws\LruArrayCache; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** @@ -17,7 +16,6 @@ */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; private static $originalEnv; @@ -49,7 +47,7 @@ class ConfigurationProviderTest extends TestCase csm_client_id = CustomAltIniApp EOT; - public static function _setUpBeforeClass() + public static function set_up_before_class() { self::$originalEnv = [ 'enabled' => getenv(ConfigurationProvider::ENV_ENABLED) ?: '', @@ -79,7 +77,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_ENABLED . '=' . self::$originalEnv['enabled']); diff --git a/tests/ClientSideMonitoring/ConfigurationTest.php b/tests/ClientSideMonitoring/ConfigurationTest.php index c2db64036a..6add824ee4 100644 --- a/tests/ClientSideMonitoring/ConfigurationTest.php +++ b/tests/ClientSideMonitoring/ConfigurationTest.php @@ -3,8 +3,7 @@ namespace Aws\Test\ClientSideMonitoring; use Aws\ClientSideMonitoring\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Log\InvalidArgumentException; @@ -13,8 +12,6 @@ */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - public function testGetsCorrectValues() { $config = new Configuration(true, 'FooHost', 888, 'FooApp'); diff --git a/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php b/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php index 1739d4c2b5..bcfe9ed206 100644 --- a/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php +++ b/tests/ClientSideMonitoring/MonitoringMiddlewareTestingTrait.php @@ -5,12 +5,14 @@ use Aws\HandlerList; use Aws\MonitoringEventsInterface; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; +use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts; use GuzzleHttp\Promise; +use Yoast\PHPUnitPolyfills\Polyfills\AssertIsType; trait MonitoringMiddlewareTestingTrait { - use PHPUnitCompatTrait; + use AssertIsType; + use ArraySubsetAsserts; /** * @dataProvider getMonitoringDataTests diff --git a/tests/CloudFront/CloudFrontClientTest.php b/tests/CloudFront/CloudFrontClientTest.php index f25450db59..04d2cd12c7 100644 --- a/tests/CloudFront/CloudFrontClientTest.php +++ b/tests/CloudFront/CloudFrontClientTest.php @@ -3,20 +3,17 @@ namespace Aws\Test\CloudFront; use Aws\CloudFront\CloudFrontClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\CloudFront\CloudFrontClient */ class CloudFrontClientTest extends TestCase { - use PHPUnitCompatTrait; - protected $key; protected $kp; - public function _setUp() + public function set_up() { openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; diff --git a/tests/CloudFront/CookieSignerTest.php b/tests/CloudFront/CookieSignerTest.php index 5d8742b44f..54856629db 100644 --- a/tests/CloudFront/CookieSignerTest.php +++ b/tests/CloudFront/CookieSignerTest.php @@ -2,17 +2,14 @@ namespace Aws\Test\CloudFront; use Aws\CloudFront\CookieSigner; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class CookieSignerTest extends TestCase { - use PHPUnitCompatTrait; - protected $key; protected $kp; - public function _setUp() + public function set_up() { openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; diff --git a/tests/CloudFront/SignerTest.php b/tests/CloudFront/SignerTest.php index 43800fc73c..a8d03f4398 100644 --- a/tests/CloudFront/SignerTest.php +++ b/tests/CloudFront/SignerTest.php @@ -2,20 +2,17 @@ namespace Aws\Test\CloudFront; use Aws\CloudFront\Signer; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class SignerTest extends TestCase { - use PHPUnitCompatTrait; - /** @var Signer */ private $instance; private $testKeyFile; const PASSPHRASE = "1234"; - public function _setUp() + public function set_up() { $this->testKeyFile =__DIR__ . '/fixtures/test.pem'; $this->instance = new Signer( diff --git a/tests/CloudFront/UrlSignerTest.php b/tests/CloudFront/UrlSignerTest.php index 23d6b3c237..585a356d04 100644 --- a/tests/CloudFront/UrlSignerTest.php +++ b/tests/CloudFront/UrlSignerTest.php @@ -4,21 +4,19 @@ use Aws\CloudFront\CloudFrontClient; use Aws\CloudFront\UrlSigner; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Uri; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\CloudFront\UrlSigner */ class UrlSignerTest extends TestCase { - use PHPUnitCompatTrait; protected $key; protected $kp; - public function _setUp() + public function set_up() { openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; diff --git a/tests/CloudSearchDomain/CloudSearchDomainTest.php b/tests/CloudSearchDomain/CloudSearchDomainTest.php index 91beb6b851..6ba8816612 100644 --- a/tests/CloudSearchDomain/CloudSearchDomainTest.php +++ b/tests/CloudSearchDomain/CloudSearchDomainTest.php @@ -2,17 +2,14 @@ namespace Aws\Test\CloudSearchDomain; use Aws\CloudSearchDomain\CloudSearchDomainClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\CloudSearchDomain\CloudSearchDomainClient */ class CloudSearchDomainTest extends TestCase { - use PHPUnitCompatTrait; - public function testRequiresEndpoint() { $this->expectException(\InvalidArgumentException::class); diff --git a/tests/CloudTrail/LogFileIteratorTest.php b/tests/CloudTrail/LogFileIteratorTest.php index 6941e85062..b331d4c232 100644 --- a/tests/CloudTrail/LogFileIteratorTest.php +++ b/tests/CloudTrail/LogFileIteratorTest.php @@ -6,17 +6,15 @@ use Aws\CloudTrail\LogFileIterator; use Aws\Result; use Aws\S3\S3Client; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Response; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\CloudTrail\LogFileIterator */ class LogFileIteratorTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testFactoryCanCreateForTrail() diff --git a/tests/CognitoIdentity/CognitoIdentityProviderTest.php b/tests/CognitoIdentity/CognitoIdentityProviderTest.php index 7f1125c328..6098430316 100644 --- a/tests/CognitoIdentity/CognitoIdentityProviderTest.php +++ b/tests/CognitoIdentity/CognitoIdentityProviderTest.php @@ -5,13 +5,10 @@ use Aws\CognitoIdentity\CognitoIdentityProvider; use Aws\MockHandler; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class CognitoIdentityProviderTest extends TestCase { - use PHPUnitCompatTrait; - public function testCreatesFromCognitoIdentity() { $options = [ @@ -53,7 +50,7 @@ public function testAccessTokensCanBeRefreshed() $provider->updateLogin('www.amazon.com', 'access-token-new'); $this->assertSame( 'access-token-new', - $this->readAttribute($provider, 'logins')['www.amazon.com'] + $this->getPropertyValue($provider, 'logins')['www.amazon.com'] ); } } diff --git a/tests/CognitoSync/CognitoSyncClientTest.php b/tests/CognitoSync/CognitoSyncClientTest.php index 94a2c6d421..1884163f68 100644 --- a/tests/CognitoSync/CognitoSyncClientTest.php +++ b/tests/CognitoSync/CognitoSyncClientTest.php @@ -1,16 +1,14 @@ home = getenv('HOME'); $this->homedrive = getenv('HOMEDRIVE'); @@ -77,7 +75,7 @@ public function _setUp() $this->profile = getenv(CredentialProvider::ENV_PROFILE); } - public function _tearDown() + public function tear_down() { putenv('HOME=' . $this->home); putenv('HOMEDRIVE=' . $this->homedrive); diff --git a/tests/Credentials/EcsCredentialProviderTest.php b/tests/Credentials/EcsCredentialProviderTest.php index 56d9df6390..1987f9175b 100644 --- a/tests/Credentials/EcsCredentialProviderTest.php +++ b/tests/Credentials/EcsCredentialProviderTest.php @@ -2,22 +2,19 @@ namespace Aws\Test\Credentials; use Aws\Credentials\EcsCredentialProvider; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\ClientInterface; use GuzzleHttp\Client; use GuzzleHttp\Promise; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Ring\Future\CompletedFutureArray; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Credentials\EcsCredentialProvider */ class EcsCredentialProviderTest extends TestCase { - use PHPUnitCompatTrait; - private $uripath; private function clearEnv() @@ -32,14 +29,14 @@ private function clearEnv() unset($_SERVER[EcsCredentialProvider::ENV_AUTH_TOKEN]); } - public function _setUp() + public function set_up() { $this->uripath = getenv(EcsCredentialProvider::ENV_URI); $this->fulluripath = getenv(EcsCredentialProvider::ENV_FULL_URI); $this->authtokenpath = getenv(EcsCredentialProvider::ENV_AUTH_TOKEN); } - public function _tearDown() + public function tear_down() { $this->uripath = getenv(EcsCredentialProvider::ENV_URI); $this->fulluripath = getenv(EcsCredentialProvider::ENV_FULL_URI); diff --git a/tests/Credentials/InstanceProfileProviderTest.php b/tests/Credentials/InstanceProfileProviderTest.php index ea6059fd5c..b95f23deaf 100644 --- a/tests/Credentials/InstanceProfileProviderTest.php +++ b/tests/Credentials/InstanceProfileProviderTest.php @@ -9,13 +9,12 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\Sdk; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Promise; use GuzzleHttp\Psr7; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\Response; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; /** @@ -23,17 +22,15 @@ */ class InstanceProfileProviderTest extends TestCase { - use PHPUnitCompatTrait; - static $originalFlag; - public static function _setUpBeforeClass() + public static function set_up_before_class() { self::$originalFlag = getenv(InstanceProfileProvider::ENV_DISABLE) ?: ''; putenv(InstanceProfileProvider::ENV_DISABLE. '=false'); } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(InstanceProfileProvider::ENV_DISABLE. '=' . self::$originalFlag); } @@ -330,7 +327,7 @@ public function testHandlesSuccessScenarios( $credentials->getExpiration() ); if ($expectedAttempts) { - $this->assertEquals($expectedAttempts, $this->readAttribute($provider, 'attempts')); + $this->assertEquals($expectedAttempts, $this->getPropertyValue($provider, 'attempts')); } } @@ -1018,7 +1015,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsYieldsExpiredCreds($cl $result = $s3Client->listBuckets(); $this->assertEquals('Request sent', $result['message']); - $this->assertLessThanOrEqual(3,$this->readAttribute($provider,'attempts')); + $this->assertLessThanOrEqual(3,$this->getPropertyValue($provider,'attempts')); } public function returnsExpiredCredsProvider() @@ -1104,7 +1101,7 @@ public function testExtendsExpirationAndSendsRequestIfImdsUnavailable($client) $result = $s3Client->listBuckets(); $this->assertEquals('Request sent', $result['message']); - $this->assertLessThanOrEqual(3,$this->readAttribute($provider,'attempts')); + $this->assertLessThanOrEqual(3,$this->getPropertyValue($provider,'attempts')); } public function imdsUnavailableProvider() @@ -1206,6 +1203,6 @@ public function testResetsAttempts() $provider()->wait(); $provider()->wait(); - $this->assertLessThanOrEqual(3, $this->readAttribute($provider, 'attempts')); + $this->assertLessThanOrEqual(3, $this->getPropertyValue($provider, 'attempts')); } } diff --git a/tests/Crypto/AesDecryptingStreamTest.php b/tests/Crypto/AesDecryptingStreamTest.php index b713c2488b..da2d03cf22 100644 --- a/tests/Crypto/AesDecryptingStreamTest.php +++ b/tests/Crypto/AesDecryptingStreamTest.php @@ -4,17 +4,15 @@ use Aws\Crypto\AesDecryptingStream; use Aws\Crypto\Cipher\Cbc; use Aws\Crypto\Cipher\CipherMethod; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class AesDecryptingStreamTest extends TestCase { const KB = 1024; const MB = 1048576; - use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** diff --git a/tests/Crypto/AesEncryptingStreamTest.php b/tests/Crypto/AesEncryptingStreamTest.php index ecf406c745..086e52c146 100644 --- a/tests/Crypto/AesEncryptingStreamTest.php +++ b/tests/Crypto/AesEncryptingStreamTest.php @@ -5,17 +5,15 @@ use Aws\Crypto\AesEncryptingStream; use Aws\Crypto\Cipher\Cbc; use Aws\Crypto\Cipher\CipherMethod; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class AesEncryptingStreamTest extends TestCase { const KB = 1024; const MB = 1048576; - use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** diff --git a/tests/Crypto/AesGcmDecryptingStreamTest.php b/tests/Crypto/AesGcmDecryptingStreamTest.php index 11b1bbdead..4f35be9e28 100644 --- a/tests/Crypto/AesGcmDecryptingStreamTest.php +++ b/tests/Crypto/AesGcmDecryptingStreamTest.php @@ -2,14 +2,12 @@ namespace Aws\Test\Crypto; use Aws\Crypto\AesGcmDecryptingStream; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class AesGcmDecryptingStreamTest extends TestCase { - use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; /** diff --git a/tests/Crypto/AesGcmEncryptingStreamTest.php b/tests/Crypto/AesGcmEncryptingStreamTest.php index 0a03fa1ecd..37738cbb61 100644 --- a/tests/Crypto/AesGcmEncryptingStreamTest.php +++ b/tests/Crypto/AesGcmEncryptingStreamTest.php @@ -2,24 +2,22 @@ namespace Aws\Test\Crypto; use Aws\Crypto\AesGcmEncryptingStream; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class AesGcmEncryptingStreamTest extends TestCase { - use PHPUnitCompatTrait; use AesEncryptionStreamTestTrait; - protected function _setUp() + protected function set_up() { if (version_compare(PHP_VERSION, '7.1', '<')) { $this->markTestSkipped( 'AES-GCM decryption is only supported in PHP 7.1 or greater' ); } - parent::setUp(); + parent::set_up(); } /** diff --git a/tests/Crypto/Cipher/CbcTest.php b/tests/Crypto/Cipher/CbcTest.php index 79d252c763..ee4b6cca0d 100644 --- a/tests/Crypto/Cipher/CbcTest.php +++ b/tests/Crypto/Cipher/CbcTest.php @@ -2,13 +2,10 @@ namespace Aws\Test\Crypto\Cipher; use Aws\Crypto\Cipher\Cbc; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class CbcTest extends TestCase { - use PHPUnitCompatTrait; - public function testShouldReportCipherMethodOfCBC() { $ivString = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); diff --git a/tests/Crypto/KmsMaterialsProviderV2Test.php b/tests/Crypto/KmsMaterialsProviderV2Test.php index 4c8c90bf60..007278f83b 100644 --- a/tests/Crypto/KmsMaterialsProviderV2Test.php +++ b/tests/Crypto/KmsMaterialsProviderV2Test.php @@ -5,16 +5,14 @@ use Aws\Kms\KmsClient; use Aws\Middleware; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Crypto\KmsMaterialsProviderV2 */ class KmsMaterialsProviderV2Test extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testProviderBasics() diff --git a/tests/Crypto/MetadataEnvelopeTest.php b/tests/Crypto/MetadataEnvelopeTest.php index 95d1c5127d..11fd1121cc 100644 --- a/tests/Crypto/MetadataEnvelopeTest.php +++ b/tests/Crypto/MetadataEnvelopeTest.php @@ -2,15 +2,13 @@ namespace Aws\Test\Crypto; use Aws\Crypto\MetadataEnvelope; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Crypto\MetadataEnvelope */ class MetadataEnvelopeTest extends TestCase { - use PHPUnitCompatTrait; use UsesMetadataEnvelopeTrait; /** diff --git a/tests/Crypto/Polyfill/KeyTest.php b/tests/Crypto/Polyfill/KeyTest.php index b05424804c..8ee4d3426f 100644 --- a/tests/Crypto/Polyfill/KeyTest.php +++ b/tests/Crypto/Polyfill/KeyTest.php @@ -2,8 +2,7 @@ namespace Aws\Test\Crypto\Polyfill; use Aws\Crypto\Polyfill\Key; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * Class KeyTest @@ -11,8 +10,6 @@ */ class KeyTest extends TestCase { - use PHPUnitCompatTrait; - public function testConstructor() { $this->assertInstanceOf(Key::class, new Key('test')); diff --git a/tests/DefaultsMode/ConfigurationProviderTest.php b/tests/DefaultsMode/ConfigurationProviderTest.php index e49c557e71..c4e12744e4 100644 --- a/tests/DefaultsMode/ConfigurationProviderTest.php +++ b/tests/DefaultsMode/ConfigurationProviderTest.php @@ -6,17 +6,14 @@ use Aws\DefaultsMode\ConfigurationInterface; use Aws\DefaultsMode\ConfigurationProvider; use Aws\DefaultsMode\Exception\ConfigurationException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\DefaultsMode\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_MODE) ?: '', @@ -58,7 +55,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_MODE . '=' . self::$originalEnv['mode']); diff --git a/tests/DefaultsMode/ConfigurationTest.php b/tests/DefaultsMode/ConfigurationTest.php index e3eb1d2fde..3460ee8fe9 100644 --- a/tests/DefaultsMode/ConfigurationTest.php +++ b/tests/DefaultsMode/ConfigurationTest.php @@ -3,16 +3,13 @@ namespace Aws\Test\DefaultsMode; use Aws\DefaultsMode\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\DefaultsMode\Configuration */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - public function testGetsCorrectValues() { $config = new Configuration('standard'); diff --git a/tests/DocDb/DocDbClientTest.php b/tests/DocDb/DocDbClientTest.php index cb43941b43..800c7b8bc0 100644 --- a/tests/DocDb/DocDbClientTest.php +++ b/tests/DocDb/DocDbClientTest.php @@ -5,8 +5,7 @@ use Aws\Credentials\Credentials; use Aws\DocDB\DocDBClient; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -15,15 +14,13 @@ */ class DocDbClientTestClientTest extends TestCase { - use PHPUnitCompatTrait; - - public static function _setUpBeforeClass() + public static function set_up_before_class() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; diff --git a/tests/DynamoDb/DynamoDbClientTest.php b/tests/DynamoDb/DynamoDbClientTest.php index 841f6d910e..10d7350474 100644 --- a/tests/DynamoDb/DynamoDbClientTest.php +++ b/tests/DynamoDb/DynamoDbClientTest.php @@ -7,19 +7,17 @@ use Aws\Exception\AwsException; use Aws\MockHandler; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Stream; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\DynamoDb\DynamoDbClient */ class DynamoDbClientTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testRegisterSessionHandlerReturnsHandler() @@ -28,7 +26,7 @@ public function testRegisterSessionHandlerReturnsHandler() @$sh = $client->registerSessionHandler(['locking' => true]); $this->assertInstanceOf( 'Aws\DynamoDb\LockingSessionConnection', - $this->readAttribute($sh, 'connection') + $this->getPropertyValue($sh, 'connection') ); } diff --git a/tests/DynamoDb/MarshalerTest.php b/tests/DynamoDb/MarshalerTest.php index 8dcf6ac3a9..48c9f404e6 100644 --- a/tests/DynamoDb/MarshalerTest.php +++ b/tests/DynamoDb/MarshalerTest.php @@ -5,17 +5,14 @@ use Aws\DynamoDb\BinaryValue; use Aws\DynamoDb\NumberValue; use Aws\DynamoDb\SetValue; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\DynamoDb\Marshaler */ class MarshalerTest extends TestCase { - use PHPUnitCompatTrait; - const ERROR = 'ERROR'; /** diff --git a/tests/DynamoDb/SessionHandlerTest.php b/tests/DynamoDb/SessionHandlerTest.php index 0041a0d806..ea8c114397 100644 --- a/tests/DynamoDb/SessionHandlerTest.php +++ b/tests/DynamoDb/SessionHandlerTest.php @@ -2,16 +2,14 @@ namespace Aws\Test\DynamoDb; use Aws\DynamoDb\SessionHandler; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\DynamoDb\SessionHandler */ class SessionHandlerTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testCanCreateSessionHandler() @@ -22,11 +20,11 @@ public function testCanCreateSessionHandler() $this->assertInstanceOf( 'Aws\DynamoDb\StandardSessionConnection', - $this->readAttribute($sh1, 'connection') + $this->getPropertyValue($sh1, 'connection') ); $this->assertInstanceOf( 'Aws\DynamoDb\LockingSessionConnection', - $this->readAttribute($sh2, 'connection') + $this->getPropertyValue($sh2, 'connection') ); } diff --git a/tests/DynamoDb/StandardSessionConnectionTest.php b/tests/DynamoDb/StandardSessionConnectionTest.php index 9d2b659408..27260fda5e 100644 --- a/tests/DynamoDb/StandardSessionConnectionTest.php +++ b/tests/DynamoDb/StandardSessionConnectionTest.php @@ -5,16 +5,14 @@ use Aws\DynamoDb\StandardSessionConnection; use Aws\Middleware; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\DynamoDb\StandardSessionConnection */ class StandardSessionConnectionTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testStandardConfig() diff --git a/tests/DynamoDb/WriteRequestBatchTest.php b/tests/DynamoDb/WriteRequestBatchTest.php index 7d4db5c6d9..2be84a22e3 100644 --- a/tests/DynamoDb/WriteRequestBatchTest.php +++ b/tests/DynamoDb/WriteRequestBatchTest.php @@ -6,23 +6,21 @@ use Aws\MockHandler; use Aws\Result; use Aws\DynamoDb\WriteRequestBatch; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\DynamoDb\WriteRequestBatch */ class WriteRequestBatchTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testInstantiateWriteRequestBatch() { // Ensure threshold is correctly calculated $batch = new WriteRequestBatch($this->getTestClient('DynamoDb'), ['pool_size' => 2]); - $this->assertSame(50, $this->readAttribute($batch, 'config')['threshold']); + $this->assertSame(50, $this->getPropertyValue($batch, 'config')['threshold']); } /** @@ -63,7 +61,7 @@ public function testAddItems() 'data' => ['DeleteRequest' => ['Key' => ['c' => 'd']]], ] ], - $this->readAttribute($batch, 'queue') + $this->getPropertyValue($batch, 'queue') ); } @@ -108,7 +106,7 @@ function (CommandInterface $command) use (&$commandCount) { // Ensure that 2 commands and 1 flush happened, with 1 left in queue. $this->assertEquals([1, 1], $commandCount); - $this->assertCount(1, $this->readAttribute($batch, 'queue')); + $this->assertCount(1, $this->getPropertyValue($batch, 'queue')); } public function testUnprocessedItemsAreRequeued() @@ -142,11 +140,11 @@ public function testUnprocessedItemsAreRequeued() 'data' => ['DeleteRequest' => ['Key' => ['id' => ['S' => 'c']]]], ] ], - $this->readAttribute($batch, 'queue') + $this->getPropertyValue($batch, 'queue') ); $batch->flush(); - $this->assertCount(0, $this->readAttribute($batch, 'queue')); + $this->assertCount(0, $this->getPropertyValue($batch, 'queue')); } public function testErrorsAreHandled() @@ -189,13 +187,13 @@ function ($command, $request) { $batch->put(['id' => ['S' => 'b']]); // There should be two items in the queue before we flush. - $this->assertCount(2, $this->readAttribute($batch, 'queue')); + $this->assertCount(2, $this->getPropertyValue($batch, 'queue')); $batch->flush(false); // The 1st response should be a ProvisionedThroughputExceededException, // which means the items should be re-queued, keeping the count at 2. - $this->assertCount(2, $this->readAttribute($batch, 'queue')); + $this->assertCount(2, $this->getPropertyValue($batch, 'queue')); $batch->flush(); $batch->put(['id' => ['S' => 'c']]); @@ -203,7 +201,7 @@ function ($command, $request) { // After 2 complete flushes, the queue should be empty, and there should // been 2 unhandled errors that would have triggered the callback. - $this->assertCount(0, $this->readAttribute($batch, 'queue')); + $this->assertCount(0, $this->getPropertyValue($batch, 'queue')); $this->assertSame(2, $unhandledErrors); } } diff --git a/tests/Endpoint/EndpointProviderTest.php b/tests/Endpoint/EndpointProviderTest.php index 78e72aa979..d9199cd1a4 100644 --- a/tests/Endpoint/EndpointProviderTest.php +++ b/tests/Endpoint/EndpointProviderTest.php @@ -3,16 +3,13 @@ use Aws\Endpoint\EndpointProvider; use Aws\Endpoint\PartitionEndpointProvider; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Endpoint\EndpointProvider */ class EndpointProviderTest extends TestCase { - use PHPUnitCompatTrait; - public function testThrowsWhenUnresolved() { $this->expectException(\Aws\Exception\UnresolvedEndpointException::class); diff --git a/tests/Endpoint/PartitionTest.php b/tests/Endpoint/PartitionTest.php index 6b85d6a73f..e8210b64d2 100644 --- a/tests/Endpoint/PartitionTest.php +++ b/tests/Endpoint/PartitionTest.php @@ -5,16 +5,13 @@ use Aws\Endpoint\PartitionInterface; use Aws\Endpoint\UseDualstackEndpoint; use Aws\Endpoint\UseFipsEndpoint; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Endpoint\Partition */ class PartitionTest extends TestCase { - use PHPUnitCompatTrait; - /** * @dataProvider partitionDefinitionProvider * diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php index c94f206d06..c6c4cfea2c 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php @@ -7,17 +7,14 @@ use Aws\Endpoint\UseDualstackEndpoint\Configuration; use Aws\Endpoint\UseDualstackEndpoint\ConfigurationInterface; use Aws\Endpoint\UseDualstackEndpoint\Exception\ConfigurationException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Endpoint\UseDualstackEndpoint\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT) ?: '', @@ -59,7 +56,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_USE_DUAL_STACK_ENDPOINT . '=' . self::$originalEnv['use_dualstack_endpoint']); diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php index e6931bba76..621146e6d6 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php @@ -2,16 +2,13 @@ namespace Aws\Test\Endpoint\UseDualstackEndpoint; use Aws\Endpoint\UseDualstackEndpoint\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Endpoint\UseDualstackEndpoint\Configuration */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - /** * @dataProvider correctValueCases * diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php index d290fc8f69..b9c3a255a7 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php @@ -6,17 +6,14 @@ use Aws\Endpoint\UseFipsEndpoint\Configuration; use Aws\Endpoint\UseFipsEndpoint\ConfigurationInterface; use Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Endpoint\UseFipsEndpoint\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT) ?: '', @@ -58,7 +55,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_USE_FIPS_ENDPOINT . '=' . self::$originalEnv['use_fips_endpoint']); diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php index f603f737a4..b77a7a030c 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php @@ -2,16 +2,13 @@ namespace Aws\Test\Endpoint\UseFipsEndpoint; use Aws\Endpoint\UseFipsEndpoint\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Endpoint\UseFipsEndpoint\Configuration */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - /** * @dataProvider correctValueCases * diff --git a/tests/EndpointDiscovery/ConfigurationProviderTest.php b/tests/EndpointDiscovery/ConfigurationProviderTest.php index f63d7d07da..4e031e726a 100644 --- a/tests/EndpointDiscovery/ConfigurationProviderTest.php +++ b/tests/EndpointDiscovery/ConfigurationProviderTest.php @@ -8,17 +8,14 @@ use Aws\EndpointDiscovery\ConfigurationProvider; use Aws\EndpointDiscovery\Exception\ConfigurationException; use Aws\LruArrayCache; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\EndpointDiscovery\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENABLED) ?: '', @@ -64,7 +61,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_ENABLED . '=' . self::$originalEnv['enabled']); diff --git a/tests/EndpointDiscovery/ConfigurationTest.php b/tests/EndpointDiscovery/ConfigurationTest.php index 309a651f8e..1d2588eaf9 100644 --- a/tests/EndpointDiscovery/ConfigurationTest.php +++ b/tests/EndpointDiscovery/ConfigurationTest.php @@ -3,8 +3,7 @@ namespace Aws\Test\EndpointDiscovery; use Aws\EndpointDiscovery\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Log\InvalidArgumentException; /** @@ -12,8 +11,6 @@ */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - public function testGetsCorrectValues() { $config = new Configuration(true, 2000); diff --git a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php index 1791fcc1b9..ea8ae88039 100644 --- a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php +++ b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php @@ -13,12 +13,11 @@ use Aws\Result; use Aws\ResultInterface; use Aws\Sdk; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Uri; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; /** @@ -26,7 +25,6 @@ */ class EndpointDiscoveryMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; /** * @backupStaticAttributes enabled diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 66ef283c6b..d59f32169a 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -5,17 +5,14 @@ use Aws\EndpointParameterMiddleware; use Aws\HandlerList; use Aws\Api\Service; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\EndpointParameterMiddleware */ class EndpointParameterMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; - public function testThrowsExceptionForMissingParameter() { $service = $this->generateTestService(); diff --git a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php index 67d0ad5ac8..a852e4869b 100644 --- a/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php +++ b/tests/EventBridge/EventBridgeEndpointMiddlewareTest.php @@ -4,15 +4,13 @@ use Aws\CommandInterface; use Aws\Result; use Aws\EventBridge\EventBridgeClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class EventBridgeEndpointMiddlewareTest extends TestCase { use UsesServiceTrait; - use PHPUnitCompatTrait; public function putEventsEndpointSuccessProvider() { diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index fd8f2b6110..1ccd7bda0a 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -5,13 +5,10 @@ use Aws\MockHandler; use Aws\Result; use Aws\S3\S3Client; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class FunctionsTest extends TestCase { - use PHPUnitCompatTrait; - /** * @covers Aws\recursive_dir_iterator() */ diff --git a/tests/Glacier/GlacierClientTest.php b/tests/Glacier/GlacierClientTest.php index b1bda13762..080b359d8e 100644 --- a/tests/Glacier/GlacierClientTest.php +++ b/tests/Glacier/GlacierClientTest.php @@ -3,18 +3,16 @@ use Aws\Exception\CouldNotCreateChecksumException; use Aws\Glacier\GlacierClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Glacier\GlacierClient */ class GlacierClientTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testAppliesAllMiddleware() diff --git a/tests/Glacier/TreeHashTest.php b/tests/Glacier/TreeHashTest.php index 2d68d17873..907faac89e 100644 --- a/tests/Glacier/TreeHashTest.php +++ b/tests/Glacier/TreeHashTest.php @@ -2,13 +2,10 @@ namespace Aws\Test\Glacier; use Aws\Glacier\TreeHash; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class TreeHashTest extends TestCase { - use PHPUnitCompatTrait; - /** * @covers Aws\Glacier\TreeHash::__construct * @covers Aws\Glacier\TreeHash::update diff --git a/tests/Handler/GuzzleV5/HandlerTest.php b/tests/Handler/GuzzleV5/HandlerTest.php index e58deabe08..b8750ba500 100644 --- a/tests/Handler/GuzzleV5/HandlerTest.php +++ b/tests/Handler/GuzzleV5/HandlerTest.php @@ -2,7 +2,6 @@ namespace Aws\Test\Handler\GuzzleV5; use Aws\Handler\GuzzleV5\GuzzleHandler; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; @@ -18,16 +17,14 @@ use GuzzleHttp\Ring\Client\MockHandler; use GuzzleHttp\Stream\Stream; use React\Promise\Deferred; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Handler\GuzzleV5\GuzzleHandler */ class HandlerTest extends TestCase { - use PHPUnitCompatTrait; - - public function _setUp() + public function set_up() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Handler/GuzzleV5/StreamTest.php b/tests/Handler/GuzzleV5/StreamTest.php index 11605024bb..de34540546 100644 --- a/tests/Handler/GuzzleV5/StreamTest.php +++ b/tests/Handler/GuzzleV5/StreamTest.php @@ -3,10 +3,9 @@ use Aws\Handler\GuzzleV5\GuzzleStream as GuzzleStreamAdapter; use Aws\Handler\GuzzleV5\PsrStream as PsrStreamAdapter; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Stream\Stream as GuzzleStream; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Handler\GuzzleV5\GuzzleStream @@ -14,9 +13,7 @@ */ class StreamTest extends TestCase { - use PHPUnitCompatTrait; - - public function _setUp() + public function set_up() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Handler/GuzzleV6/HandlerTest.php b/tests/Handler/GuzzleV6/HandlerTest.php index 636e714cee..73ac9500cd 100644 --- a/tests/Handler/GuzzleV6/HandlerTest.php +++ b/tests/Handler/GuzzleV6/HandlerTest.php @@ -2,7 +2,6 @@ namespace Aws\Test\Handler\GuzzleV6; use Aws\Handler\GuzzleV6\GuzzleHandler; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Handler\MockHandler; @@ -11,16 +10,14 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use GuzzleHttp\TransferStats; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Handler\GuzzleV6\GuzzleHandler */ class HandlerTest extends TestCase { - use PHPUnitCompatTrait; - - public function _setUp() + public function set_up() { if (!class_exists('GuzzleHttp\HandlerStack')) { $this->markTestSkipped(); diff --git a/tests/HandlerListTest.php b/tests/HandlerListTest.php index 745818a1ba..d9a7ac99a5 100644 --- a/tests/HandlerListTest.php +++ b/tests/HandlerListTest.php @@ -5,17 +5,14 @@ use Aws\CommandInterface; use Aws\HandlerList; use Aws\Middleware; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Request; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\HandlerList */ class HandlerListTest extends TestCase { - use PHPUnitCompatTrait; - public function testEnsuresHandlerIsSet() { $this->expectException(\LogicException::class); diff --git a/tests/HistoryTest.php b/tests/HistoryTest.php index 04c1d12d45..71e103dfc8 100644 --- a/tests/HistoryTest.php +++ b/tests/HistoryTest.php @@ -6,15 +6,13 @@ use Aws\History; use Aws\Exception\AwsException; use GuzzleHttp\Psr7\Request; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\History */ class HistoryTest extends TestCase { - use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; - public function testIsCountable() { $h = new History(); diff --git a/tests/IdempotencyTokenMiddlewareTest.php b/tests/IdempotencyTokenMiddlewareTest.php index 9d5c27fd9c..c26c66dde6 100644 --- a/tests/IdempotencyTokenMiddlewareTest.php +++ b/tests/IdempotencyTokenMiddlewareTest.php @@ -3,22 +3,19 @@ use Aws\IdempotencyTokenMiddleware; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Aws\HandlerList; use Aws\Api\ApiProvider; use Aws\Api\Service; use Aws\Command; use GuzzleHttp\Psr7\Request; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\IdempotencyTokenMiddleware */ class IdempotencyTokenMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; - public function testAutoFillsMemberWithIdempotencyTrait() { $list = new HandlerList(); diff --git a/tests/Integ/GuzzleV5HandlerTest.php b/tests/Integ/GuzzleV5HandlerTest.php index 041439cc24..ed3654619e 100644 --- a/tests/Integ/GuzzleV5HandlerTest.php +++ b/tests/Integ/GuzzleV5HandlerTest.php @@ -2,18 +2,15 @@ namespace Aws\Test\Integ; use Aws\Handler\GuzzleV5\GuzzleHandler; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise\RejectionException; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class GuzzleV5HandlerTest extends TestCase { - use PHPUnitCompatTrait; - - public function _setUp() + public function set_up() { if (!class_exists('GuzzleHttp\Ring\Core')) { $this->markTestSkipped(); diff --git a/tests/Integ/GuzzleV6StreamHandlerTest.php b/tests/Integ/GuzzleV6StreamHandlerTest.php index 924e68d0a9..1bf58a46c2 100644 --- a/tests/Integ/GuzzleV6StreamHandlerTest.php +++ b/tests/Integ/GuzzleV6StreamHandlerTest.php @@ -1,16 +1,14 @@ markTestSkipped(); diff --git a/tests/JsonCompilerTest.php b/tests/JsonCompilerTest.php index 993eb6c6a6..bca34d2c4f 100644 --- a/tests/JsonCompilerTest.php +++ b/tests/JsonCompilerTest.php @@ -2,19 +2,16 @@ namespace Aws\Test; use Aws\JsonCompiler; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\JsonCompiler */ class JsonCompilerTest extends TestCase { - use PHPUnitCompatTrait; - private $models; - public function _setUp() + public function set_up() { $this->models = realpath(__DIR__ . '/../src/data'); } diff --git a/tests/Lambda/LambdaClientTest.php b/tests/Lambda/LambdaClientTest.php index 850f34ce4d..f484a14da1 100644 --- a/tests/Lambda/LambdaClientTest.php +++ b/tests/Lambda/LambdaClientTest.php @@ -3,13 +3,13 @@ use Aws\Lambda\LambdaClient; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; +use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class LambdaClientTest extends TestCase { - use PHPUnitCompatTrait; + use ArraySubsetAsserts; function testsAddsDefaultCurlOptions() { diff --git a/tests/MiddlewareTest.php b/tests/MiddlewareTest.php index f920ad649c..ce87b6d8d1 100644 --- a/tests/MiddlewareTest.php +++ b/tests/MiddlewareTest.php @@ -15,21 +15,18 @@ use Aws\Result; use Aws\ResultInterface; use Aws\Signature\SignatureV4; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Middleware */ class MiddlewareTest extends TestCase { - use PHPUnitCompatTrait; - - public function _setUp() + public function set_up() { \GuzzleHttp\Promise\queue()->run(); } diff --git a/tests/MockHandlerTest.php b/tests/MockHandlerTest.php index e9706a8227..9d35ce60be 100644 --- a/tests/MockHandlerTest.php +++ b/tests/MockHandlerTest.php @@ -6,19 +6,16 @@ use Aws\Exception\AwsException; use Aws\MockHandler; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\MockHandler */ class MockHandlerTest extends TestCase { - use PHPUnitCompatTrait; - public function testValidatesEachResult() { $this->expectExceptionMessage("Expected an Aws\ResultInterface or Exception"); diff --git a/tests/MultiRegionClientTest.php b/tests/MultiRegionClientTest.php index 1ce01cc553..c8913ac9a5 100644 --- a/tests/MultiRegionClientTest.php +++ b/tests/MultiRegionClientTest.php @@ -10,22 +10,19 @@ use Aws\MockHandler; use Aws\MultiRegionClient; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class MultiRegionClientTest extends TestCase { - use PHPUnitCompatTrait; - /** @var MultiRegionClient */ private $instance; /** @var \PHPUnit_Framework_MockObject_MockObject */ private $mockRegionalClient; - public function _setUp() + public function set_up() { $this->mockRegionalClient = $this->getMockBuilder(AwsClient::class) ->disableOriginalConstructor() diff --git a/tests/Multipart/AbstractUploaderTest.php b/tests/Multipart/AbstractUploaderTest.php index c52d8f6be8..96d3dd9a95 100644 --- a/tests/Multipart/AbstractUploaderTest.php +++ b/tests/Multipart/AbstractUploaderTest.php @@ -6,17 +6,15 @@ use Aws\Exception\MultipartUploadException; use Aws\Multipart\UploadState; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Multipart\AbstractUploader */ class AbstractUploaderTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; private function getUploaderWithState($status, array $results = [], $source = null) @@ -170,7 +168,7 @@ public function testCanSetSourceFromFilenameIfExists() $uploader = $this->getTestUploader(__FILE__, $config); $this->assertInstanceOf( 'Psr\Http\Message\StreamInterface', - $this->readAttribute($uploader, 'source') + $this->getPropertyValue($uploader, 'source') ); // CASE 2: Filename does not exist. diff --git a/tests/Neptune/NeptuneClientTest.php b/tests/Neptune/NeptuneClientTest.php index b365d61b4f..9d7daac579 100644 --- a/tests/Neptune/NeptuneClientTest.php +++ b/tests/Neptune/NeptuneClientTest.php @@ -5,8 +5,7 @@ use Aws\Credentials\Credentials; use Aws\Neptune\NeptuneClient; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -15,15 +14,13 @@ */ class NeptuneClientTest extends TestCase { - use PHPUnitCompatTrait; - - public static function _setUpBeforeClass() + public static function set_up_before_class() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; diff --git a/tests/Polly/PollyClientTest.php b/tests/Polly/PollyClientTest.php index 62a821f859..24ee4883f4 100644 --- a/tests/Polly/PollyClientTest.php +++ b/tests/Polly/PollyClientTest.php @@ -3,16 +3,13 @@ use Aws\Credentials\Credentials; use Aws\Polly\PollyClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Polly\PollyClient */ class PollyClientTest extends TestCase { - use PHPUnitCompatTrait; - public function testCanGeneratePreSignedUrlForSynthesizeSpeech() { $polly = new PollyClient([ diff --git a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php deleted file mode 100644 index 19dd3eab1d..0000000000 --- a/tests/Polyfill/PHPUnit4/PHPUnitCompatTrait.php +++ /dev/null @@ -1,141 +0,0 @@ -setExpectedException( $exception, $this->exceptionMessage, $this->exceptionCode ); - } - - public function expectExceptionMessage( $message ) { - $this->exceptionMessage = $message; - - $exception = $this->getExpectedException(); - $this->setExpectedException( $exception, $message, $this->exceptionCode ); - } - - public function _setUp() - { - } - - public function setUp() - { - $this->_setUp(); - } - - public function _tearDown() - { - } - - public function tearDown() - { - $this->_tearDown(); - } - - public static function setUpBeforeClass() - { - self::_setUpBeforeClass(); - } - - public static function tearDownAfterClass() - { - self::_tearDownAfterClass(); - } - - public static function _tearDownAfterClass() - { - } - - public static function _setUpBeforeClass() - { - } - - public function expectNotToPerformAssertions() - { - } - - public function expectWarning() - { - $this->expectException(\PHPUnit_Framework_Error_Warning::class); - } - - public function expectError() - { - $this->expectException(\PHPUnit_Framework_Error::class); - } - - public function expectErrorMessage($message) - { - $this->expectExceptionMessage($message); - } - - public function expectExceptionMessageMatches($regularExpression) - { - $this->expectExceptionMessageRegExp($regularExpression); - } - - public function expectExceptionMessageRegExp($messageRegExp) - { - $exception = $this->getExpectedException(); - $this->setExpectedExceptionRegExp($exception, $messageRegExp, $this->exceptionCode); - } - - public function assertStringContainsString($expected, $actual, $message = '') - { - $this->assertContains($expected, $actual, $message); - } - - public function assertStringNotContainsString($expected, $actual, $message = '') - { - $this->assertNotContains($expected, $actual, $message); - } - - public function assertStringContainsStringIgnoringCase($expected, $actual, $message = '') - { - $this->assertContains($expected, $actual, $message, true); - } - - public function assertIsInt($actual, $message = '') - { - $this->assertInternalType('int', $actual, $message); - } - - public function assertIsArray($actual, $message = '') - { - $this->assertInternalType('array', $actual, $message); - } - - public function assertIsCallable($actual, $message = '') - { - $this->assertInternalType('callable', $actual, $message); - } - - public function assertIsString($actual, $message = '') - { - $this->assertInternalType('string', $actual, $message); - } - - public function assertIsResource($actual, $message = '') - { - $this->assertInternalType('resource', $actual, $message); - } - - public function assertMatchesRegularExpression($pattern, $string, $message = '') - { - $this->assertRegExp($pattern, $string, $message); - } - - public function assertDoesNotMatchRegularExpression($pattern, $string, $message = '') - { - $this->assertNotRegExp($pattern, $string, $message); - } - - public function assertFileDoesNotExist($file, $message = '') - { - $this->assertFileNotExists($file, $message); - } -} \ No newline at end of file diff --git a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php deleted file mode 100644 index d7218e462a..0000000000 --- a/tests/Polyfill/PHPUnit5/PHPUnitCompatTrait.php +++ /dev/null @@ -1,131 +0,0 @@ -_setUp(); - } - - public function _tearDown() - { - } - - public function tearDown() - { - $this->_tearDown(); - } - - public static function setUpBeforeClass() - { - self::_setUpBeforeClass(); - } - - public static function tearDownAfterClass() - { - self::_tearDownAfterClass(); - } - - public static function _tearDownAfterClass() - { - } - - public static function _setUpBeforeClass() - { - } - - public function expectNotToPerformAssertions() - { - } - - public function expectWarning() - { - $this->expectException(\PHPUnit_Framework_Error_Warning::class); - } - - public function expectError() - { - $this->expectException(\PHPUnit_Framework_Error::class); - } - - public function expectErrorMessage($message) - { - $this->expectExceptionMessage($message); - } - - public function expectExceptionMessageMatches($regularExpression) - { - $this->expectExceptionMessageRegExp($regularExpression); - } - - public function expectExceptionMessageRegExp($messageRegExp) - { - $exception = $this->getExpectedException(); - $this->setExpectedExceptionRegExp($exception, $messageRegExp, $this->exceptionCode); - } - - public function assertStringContainsString($expected, $actual, $message = '') - { - $this->assertContains($expected, $actual, $message); - } - - public function assertStringNotContainsString($expected, $actual, $message = '') - { - $this->assertNotContains($expected, $actual, $message); - } - - public function assertStringContainsStringIgnoringCase($expected, $actual, $message = '') - { - $this->assertContains($expected, $actual, $message, true); - } - - public function assertIsInt($actual, $message = '') - { - $this->assertInternalType('int', $actual, $message); - } - - public function assertIsArray($actual, $message = '') - { - $this->assertInternalType('array', $actual, $message); - } - - public function assertIsCallable($actual, $message = '') - { - $this->assertInternalType('callable', $actual, $message); - } - - public function assertIsString($actual, $message = '') - { - $this->assertInternalType('string', $actual, $message); - } - - public function assertIsResource($actual, $message = '') - { - $this->assertInternalType('resource', $actual, $message); - } - - public function assertMatchesRegularExpression($pattern, $string, $message = '') - { - $this->assertRegExp($pattern, $string, $message); - } - - public function assertDoesNotMatchRegularExpression($pattern, $string, $message = '') - { - $this->assertNotRegExp($pattern, $string, $message); - } - - public function assertFileDoesNotExist($file, $message = '') - { - $this->assertFileNotExists($file, $message); - } -} \ No newline at end of file diff --git a/tests/Polyfill/PHPUnit9/ArraySubset.php b/tests/Polyfill/PHPUnit9/ArraySubset.php deleted file mode 100644 index 308dfe9402..0000000000 --- a/tests/Polyfill/PHPUnit9/ArraySubset.php +++ /dev/null @@ -1,133 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ -namespace Aws\Test\Polyfill\PHPUnit9; - -use PHPUnit\Framework\Constraint\Constraint; -use PHPUnit\Framework\ExpectationFailedException; -use PHPUnit\Util\Exception; -use SebastianBergmann\Comparator\ComparisonFailure; - -/** - * Constraint that asserts that the array it is evaluated for has a specified subset. - * - * Uses array_replace_recursive() to check if a key value subset is part of the - * subject array. - */ -class ArraySubset extends Constraint -{ - /** - * @var iterable - */ - private $subset; - - /** - * @var bool - */ - private $strict; - - public function __construct(iterable $subset, bool $strict = false) - { - $this->strict = $strict; - $this->subset = $subset; - } - - /** - * Evaluates the constraint for parameter $other - * - * If $returnResult is set to false (the default), an exception is thrown - * in case of a failure. null is returned otherwise. - * - * If $returnResult is true, the result of the evaluation is returned as - * a boolean value instead: true in case of success, false in case of a - * failure. - * - * @param mixed $other value or object to evaluate - * @param string $description Additional information about the test - * @param bool $returnResult Whether to return a result or throw an exception - * - * @throws ExpectationFailedException - * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException - */ - public function evaluate($other, string $description = '', $returnResult = false): ?bool - { - //type cast $other & $this->subset as an array to allow - //support in standard array functions. - $other = $this->toArray($other); - $this->subset = $this->toArray($this->subset); - - $patched = \array_replace_recursive($other, $this->subset); - - if ($this->strict) { - $result = $other === $patched; - } else { - $result = $other == $patched; - } - - if ($returnResult) { - return $result; - } - - if (!$result) { - $f = new ComparisonFailure( - $patched, - $other, - \var_export($patched, true), - \var_export($other, true) - ); - - $this->fail($other, $description, $f); - } - - return null; - } - - /** - * Returns a string representation of the constraint. - * - * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException - */ - public function toString(): string - { - throw new Exception('Not implemented'); - } - - /** - * Returns the description of the failure - * - * The beginning of failure messages is "Failed asserting that" in most - * cases. This method should return the second part of that sentence. - * - * @param mixed $other evaluated value or object - * - * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException - */ - protected function failureDescription($other): string - { - return 'an array ' . $this->toString(); - } - - private function toArray($other) - { - if (\is_array($other)) { - return $other; - } - - if ($other instanceof \ArrayObject) { - return $other->getArrayCopy(); - } - - if ($other instanceof \Traversable) { - return \iterator_to_array($other); - } - - // Keep BC even if we know that array would not be the expected one - return (array) $other; - } -} diff --git a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php b/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php deleted file mode 100644 index 8ecdd7f639..0000000000 --- a/tests/Polyfill/PHPUnit9/PHPUnitCompatTrait.php +++ /dev/null @@ -1,130 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Aws\Test\Polyfill\PHPUnit; - -use ArrayAccess; -use Exception; -use ReflectionException; -use ReflectionObject; -use ReflectionProperty; -use Aws\Test\Polyfill\PHPUnit9\ArraySubset; - -trait PHPUnitCompatTrait -{ - public function _setUp() - { - } - - public function setUp(): void - { - $this->_setUp(); - } - - public function _tearDown() - { - } - - public function tearDown(): void - { - $this->_tearDown(); - } - - public static function setUpBeforeClass(): void - { - self::_setUpBeforeClass(); - } - - public static function tearDownAfterClass(): void - { - self::_tearDownAfterClass(); - } - - public static function _tearDownAfterClass() - { - } - - public static function _setUpBeforeClass() - { - } - - public function readAttribute($object, $attributeName) - { - try { - $attribute = new ReflectionProperty($object, $attributeName); - } catch (ReflectionException $e) { - $reflector = new ReflectionObject($object); - - while ($reflector = $reflector->getParentClass()) { - try { - $attribute = $reflector->getProperty($attributeName); - break; - } catch (ReflectionException $e) { - } - } - } - - if (isset($attribute)) { - if (!$attribute || $attribute->isPublic()) { - return $object->$attributeName; - } - $attribute->setAccessible(true); - $value = $attribute->getValue($object); - $attribute->setAccessible(false); - - return $value; - } - - throw new Exception( - sprintf( - 'Attribute "%s" not found in object.', - $attributeName - ) - ); - } - - public static function invalidArgumentHelper($argument, $type, $value = null) - { - $stack = debug_backtrace(false); - - return new \PHPUnit\Framework\Exception( - sprintf( - 'Argument #%d%sof %s::%s() must be a %s', - $argument, - $value !== null ? ' ('.$value.')' : ' ', - $stack[1]['class'], - $stack[1]['function'], - $type - ) - ); - } - - public function assertArraySubset($subset, $array, $checkForObjectIdentity = false, $message = '') - { - if (!(\is_array($subset) || $subset instanceof ArrayAccess)) { - throw self::invalidArgumentHelper( - 1, - 'array or ArrayAccess' - ); - } - - if (!(\is_array($array) || $array instanceof ArrayAccess)) { - throw self::invalidArgumentHelper( - 2, - 'array or ArrayAccess' - ); - } - - $constraint = new ArraySubset($subset, $checkForObjectIdentity); - - static::assertThat($array, $constraint, $message); - } -} \ No newline at end of file diff --git a/tests/PresignUrlMiddlewareTest.php b/tests/PresignUrlMiddlewareTest.php index 58b01d66c9..20912499cc 100644 --- a/tests/PresignUrlMiddlewareTest.php +++ b/tests/PresignUrlMiddlewareTest.php @@ -8,16 +8,14 @@ use Aws\Neptune\NeptuneClient; use Aws\Rds\RdsClient; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\PresignUrlMiddleware */ class PresignUrlMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testDoesNotAddPresignedUrlForNonRequiredOperations() diff --git a/tests/Psr16CacheAdapterTest.php b/tests/Psr16CacheAdapterTest.php index adf00ff7e9..337d5db31e 100644 --- a/tests/Psr16CacheAdapterTest.php +++ b/tests/Psr16CacheAdapterTest.php @@ -2,20 +2,17 @@ namespace Aws\Test; use Aws\Psr16CacheAdapter; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\SimpleCache\CacheInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class Psr16CacheAdapterTest extends TestCase { - use PHPUnitCompatTrait; - /** @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedCache */ private $wrapped; /** @var Psr16CacheAdapter */ private $instance; - public function _setUp() + public function set_up() { $this->wrapped = $this->getMockBuilder(CacheInterface::class)->getMock(); $this->instance = new Psr16CacheAdapter($this->wrapped); diff --git a/tests/PsrCacheAdapterTest.php b/tests/PsrCacheAdapterTest.php index ac7bde272d..9b1911c097 100644 --- a/tests/PsrCacheAdapterTest.php +++ b/tests/PsrCacheAdapterTest.php @@ -2,21 +2,19 @@ namespace Aws\Test; use Aws\PsrCacheAdapter; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class PsrCacheAdapterTest extends TestCase { - use PHPUnitCompatTrait; /** @var CacheItemPoolInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedCache */ private $wrapped; /** @var PsrCacheAdapter */ private $instance; - public function _setUp() + public function set_up() { $this->wrapped = $this->getMockBuilder(CacheItemPoolInterface::class)->getMock(); $this->instance = new PsrCacheAdapter($this->wrapped); diff --git a/tests/Rds/AuthTokenGeneratorTest.php b/tests/Rds/AuthTokenGeneratorTest.php index a1ced2279c..c3bfdef93c 100644 --- a/tests/Rds/AuthTokenGeneratorTest.php +++ b/tests/Rds/AuthTokenGeneratorTest.php @@ -3,17 +3,14 @@ use Aws\Credentials\Credentials; use Aws\Rds\AuthTokenGenerator; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Rds\AuthTokenGenerator */ class AuthTokenGeneratorTest extends TestCase { - use PHPUnitCompatTrait; - public function testCanCreateAuthTokenWthCredentialInstance() { $creds = new Credentials('foo', 'bar', 'baz'); diff --git a/tests/Rds/RdsClientTest.php b/tests/Rds/RdsClientTest.php index cfcc8176eb..ca862cc726 100644 --- a/tests/Rds/RdsClientTest.php +++ b/tests/Rds/RdsClientTest.php @@ -6,8 +6,7 @@ use Aws\Rds\RdsClient; use Aws\MockHandler; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; require_once __DIR__ . '/../Signature/sig_hack.php'; @@ -16,15 +15,13 @@ */ class RdsClientTest extends TestCase { - use PHPUnitCompatTrait; - - public static function _setUpBeforeClass() + public static function set_up_before_class() { $_SERVER['aws_time'] = 1598486400; $_SERVER['formatAwsTime'] = true; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; diff --git a/tests/ResultPaginatorTest.php b/tests/ResultPaginatorTest.php index ecefbbcea2..93280c42e8 100644 --- a/tests/ResultPaginatorTest.php +++ b/tests/ResultPaginatorTest.php @@ -5,17 +5,15 @@ use Aws\CommandInterface; use Aws\DynamoDb\DynamoDbClient; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\ResultPaginator */ class ResultPaginatorTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; private function getCustomClientProvider(array $config) @@ -107,13 +105,13 @@ public function testNonIterator() $this->addMockResults($client, $results); $paginator = $client->getPaginator('ListTables', [], $config); $this->assertEquals(['test1', 'test2'], $paginator->current()['TableNames']); - $this->assertEquals(['NextToken' => 'test2'], $this->readAttribute($paginator, 'nextToken'), '[1]'); + $this->assertEquals(['NextToken' => 'test2'], $this->getPropertyValue($paginator, 'nextToken'), '[1]'); $paginator->next(); $this->assertEquals([], $paginator->current()['TableNames']); - $this->assertEquals(['NextToken' => 'test2'], $this->readAttribute($paginator, 'nextToken'), '[2]'); + $this->assertEquals(['NextToken' => 'test2'], $this->getPropertyValue($paginator, 'nextToken'), '[2]'); $paginator->next(); $this->assertEquals(['test3'], $paginator->current()['TableNames']); - $this->assertEmpty($this->readAttribute($paginator, 'nextToken'), '[3]'); + $this->assertEmpty($this->getPropertyValue($paginator, 'nextToken'), '[3]'); } /** diff --git a/tests/ResultTest.php b/tests/ResultTest.php index 38cb5f01db..633009e40d 100644 --- a/tests/ResultTest.php +++ b/tests/ResultTest.php @@ -2,16 +2,13 @@ namespace Aws\Test; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Result */ class ResultTest extends TestCase { - use PHPUnitCompatTrait; - public function testHasData() { $c = new Result(['a' => 'b', 'c' => 'd']); diff --git a/tests/Retry/ConfigurationProviderTest.php b/tests/Retry/ConfigurationProviderTest.php index f9e9e531f1..f9c8feb194 100644 --- a/tests/Retry/ConfigurationProviderTest.php +++ b/tests/Retry/ConfigurationProviderTest.php @@ -6,17 +6,14 @@ use Aws\Retry\ConfigurationInterface; use Aws\Retry\ConfigurationProvider; use Aws\Retry\Exception\ConfigurationException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Retry\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_MAX_ATTEMPTS) ?: '', @@ -64,7 +61,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_MAX_ATTEMPTS . '=' . self::$originalEnv['max_attempts']); diff --git a/tests/Retry/ConfigurationTest.php b/tests/Retry/ConfigurationTest.php index 48c0df944e..312b1d47de 100644 --- a/tests/Retry/ConfigurationTest.php +++ b/tests/Retry/ConfigurationTest.php @@ -3,16 +3,13 @@ namespace Aws\Test\Retry; use Aws\Retry\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Retry\Configuration */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - public function testGetsCorrectValues() { $config = new Configuration('adaptive', 8); diff --git a/tests/RetryMiddlewareTest.php b/tests/RetryMiddlewareTest.php index c9a3b6b2ff..07a76ada34 100644 --- a/tests/RetryMiddlewareTest.php +++ b/tests/RetryMiddlewareTest.php @@ -7,22 +7,19 @@ use Aws\MockHandler; use Aws\Result; use Aws\RetryMiddleware; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\RetryMiddleware */ class RetryMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; - public function testAddRetryHeader() { $nextHandler = function (CommandInterface $command, RequestInterface $request) { diff --git a/tests/RetryMiddlewareV2Test.php b/tests/RetryMiddlewareV2Test.php index a3f5fd99f7..6d66a57090 100644 --- a/tests/RetryMiddlewareV2Test.php +++ b/tests/RetryMiddlewareV2Test.php @@ -12,20 +12,18 @@ use Aws\Retry\QuotaManager; use Aws\Retry\RateLimiter; use Aws\RetryMiddlewareV2; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\RetryMiddlewareV2 */ class RetryMiddlewareV2Test extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** diff --git a/tests/Route53/RouteClient53Test.php b/tests/Route53/RouteClient53Test.php index 9362e7a671..88dde9306c 100644 --- a/tests/Route53/RouteClient53Test.php +++ b/tests/Route53/RouteClient53Test.php @@ -2,16 +2,13 @@ namespace Aws\Test\Route53; use Aws\Route53\Route53Client; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Route53\Route53Client */ class RouteClient53Test extends TestCase { - use PHPUnitCompatTrait; - public function testCleansIds() { $client = new Route53Client([ diff --git a/tests/S3/AmbiguousSuccessParserTest.php b/tests/S3/AmbiguousSuccessParserTest.php index d9e0d20cbf..75d8f5ee1a 100644 --- a/tests/S3/AmbiguousSuccessParserTest.php +++ b/tests/S3/AmbiguousSuccessParserTest.php @@ -7,18 +7,15 @@ use Aws\CommandInterface; use Aws\S3\AmbiguousSuccessParser; use Aws\S3\Exception\S3Exception; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\ResponseInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class AmbiguousSuccessParserTest extends TestCase { - use PHPUnitCompatTrait; - private $instance; - public function _setUp() + public function set_up() { $parser = function () {}; $errorParser = function () { diff --git a/tests/S3/BatchDeleteTest.php b/tests/S3/BatchDeleteTest.php index 6a26d85ced..f6d6bbd561 100644 --- a/tests/S3/BatchDeleteTest.php +++ b/tests/S3/BatchDeleteTest.php @@ -6,16 +6,14 @@ use Aws\Result; use Aws\S3\BatchDelete; use Aws\S3\Exception\DeleteMultipleObjectsException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\S3\BatchDelete */ class BatchDeleteTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testValidatesBatchSizeIsGreatherThanZero() diff --git a/tests/S3/BucketEndpointArnMiddlewareTest.php b/tests/S3/BucketEndpointArnMiddlewareTest.php index 704179ff17..08dc347bc7 100644 --- a/tests/S3/BucketEndpointArnMiddlewareTest.php +++ b/tests/S3/BucketEndpointArnMiddlewareTest.php @@ -9,10 +9,9 @@ use Aws\Result; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; /** @@ -20,7 +19,6 @@ */ class BucketEndpointArnMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** diff --git a/tests/S3/Crypto/S3EncryptionClientTest.php b/tests/S3/Crypto/S3EncryptionClientTest.php index 28794aebc9..c7bc88ad56 100644 --- a/tests/S3/Crypto/S3EncryptionClientTest.php +++ b/tests/S3/Crypto/S3EncryptionClientTest.php @@ -15,18 +15,16 @@ use Aws\S3\Crypto\HeadersMetadataStrategy; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTrait; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class S3EncryptionClientTest extends TestCase { - use PHPUnitCompatTrait; use S3EncryptionClientTestingTrait; use UsesCryptoParamsTrait; use UsesMetadataEnvelopeTrait; diff --git a/tests/S3/Crypto/S3EncryptionClientV2Test.php b/tests/S3/Crypto/S3EncryptionClientV2Test.php index f9c7e14226..05e4ff0a40 100644 --- a/tests/S3/Crypto/S3EncryptionClientV2Test.php +++ b/tests/S3/Crypto/S3EncryptionClientV2Test.php @@ -12,18 +12,16 @@ use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\S3\Crypto\S3EncryptionClientV2; use Aws\Test\Crypto\UsesCryptoParamsTraitV2; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; class S3EncryptionClientV2Test extends TestCase { - use PHPUnitCompatTrait; use S3EncryptionClientTestingTrait; use UsesCryptoParamsTraitV2; use UsesMetadataEnvelopeTrait; diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php index f99ef4916a..328cf8b46c 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php @@ -7,15 +7,14 @@ use Aws\Crypto\KmsMaterialsProvider; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTrait; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class S3EncryptionMultipartUploaderTest extends TestCase { - use PHPUnitCompatTrait, UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTrait; + use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTrait; const MB = 1048576; const TEST_URL = 'http://foo.s3.amazonaws.com/bar'; diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php index c901f9c5b0..a38ea4621b 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php @@ -8,16 +8,15 @@ use Aws\Crypto\KmsMaterialsProviderV2; use Aws\S3\Crypto\InstructionFileMetadataStrategy; use Aws\Test\Crypto\UsesCryptoParamsTraitV2; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; class S3EncryptionMultipartUploaderV2Test extends TestCase { - use PHPUnitCompatTrait, UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTraitV2; + use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTraitV2; const MB = 1048576; const TEST_URL = 'http://foo.s3.amazonaws.com/bar'; diff --git a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php index ade2ce7f5d..97acc0c053 100644 --- a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php +++ b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php @@ -2,16 +2,13 @@ namespace Aws\Test\S3\Exception; use Aws\S3\Exception\DeleteMultipleObjectsException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\S3\Exception\DeleteMultipleObjectsException */ class DeleteMultipleObjectsExceptionTest extends TestCase { - use PHPUnitCompatTrait; - public function testReturnsData() { $del = [['Key' => 'foo']]; diff --git a/tests/S3/MultipartUploaderTest.php b/tests/S3/MultipartUploaderTest.php index 1fda627565..dd369e291b 100644 --- a/tests/S3/MultipartUploaderTest.php +++ b/tests/S3/MultipartUploaderTest.php @@ -4,25 +4,23 @@ use Aws\S3\MultipartUploader; use Aws\Result; use Aws\S3\S3Client; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\S3\MultipartUploader */ class MultipartUploaderTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; const MB = 1048576; const FILENAME = '_aws-sdk-php-s3-mup-test-dots.txt'; - public static function _tearDownAfterClass() + public static function tear_down_after_class() { @unlink(sys_get_temp_dir() . '/' . self::FILENAME); } diff --git a/tests/S3/PermanentRedirectMiddlewareTest.php b/tests/S3/PermanentRedirectMiddlewareTest.php index 4ffb7c9ccd..eda7f92424 100644 --- a/tests/S3/PermanentRedirectMiddlewareTest.php +++ b/tests/S3/PermanentRedirectMiddlewareTest.php @@ -1,16 +1,14 @@ client = $this->getTestClient( 's3', diff --git a/tests/S3/PostObjectV4Test.php b/tests/S3/PostObjectV4Test.php index bb20c011b4..b891b96847 100644 --- a/tests/S3/PostObjectV4Test.php +++ b/tests/S3/PostObjectV4Test.php @@ -4,24 +4,22 @@ use Aws\Credentials\Credentials; use Aws\S3\PostObjectV4; use Aws\S3\S3Client; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Aws\Test\UsesServiceTrait; require_once __DIR__ . '/sig_hack.php'; -use PHPUnit\Framework\TestCase; /** * @covers Aws\S3\PostObjectV4 */ class PostObjectV4Test extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ protected $client; - public function _setUp() + public function set_up() { $this->client = new S3Client([ 'version' => 'latest', @@ -33,9 +31,9 @@ public function _setUp() ]); } - public function _tearDown() + public function tear_down() { - parent::tearDown(); + parent::tear_down(); unset($_SERVER['aws_time']); } diff --git a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php index d04396a643..d16c0b13b6 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationProviderTest.php @@ -7,17 +7,14 @@ use Aws\S3\RegionalEndpoint\ConfigurationInterface; use Aws\S3\RegionalEndpoint\ConfigurationProvider; use Aws\S3\RegionalEndpoint\Exception\ConfigurationException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\S3\RegionalEndpoint\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', @@ -61,7 +58,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '=' . self::$originalEnv['endpoints_type']); diff --git a/tests/S3/RegionalEndpoint/ConfigurationTest.php b/tests/S3/RegionalEndpoint/ConfigurationTest.php index 585e87a3f0..a7fc2f16f7 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationTest.php @@ -3,16 +3,13 @@ namespace Aws\Test\S3\RegionalEndpoint; use Aws\Sts\RegionalEndpoints\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\S3\RegionalEndpoint\Configuration */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - public function testGetsCorrectValues() { $config = new Configuration('regional'); diff --git a/tests/S3/RetryableMalformedResponseParserTest.php b/tests/S3/RetryableMalformedResponseParserTest.php index 82997ee344..adc071b15f 100644 --- a/tests/S3/RetryableMalformedResponseParserTest.php +++ b/tests/S3/RetryableMalformedResponseParserTest.php @@ -6,14 +6,11 @@ use Aws\CommandInterface; use Aws\S3\Exception\S3Exception; use Aws\S3\RetryableMalformedResponseParser; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Psr\Http\Message\ResponseInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class RetryableMalformedResponseParserTest extends TestCase { - use PHPUnitCompatTrait; - public function testConvertsParserExceptionsToRetryableExceptions() { $this->expectExceptionMessage("Sorry!"); diff --git a/tests/S3/S3ClientTest.php b/tests/S3/S3ClientTest.php index 4d008da374..b2c64a595f 100644 --- a/tests/S3/S3ClientTest.php +++ b/tests/S3/S3ClientTest.php @@ -15,7 +15,6 @@ use Aws\S3\S3Client; use Aws\S3\UseArnRegion\Configuration as UseArnRegionConfiguration; use Aws\Signature\SignatureV4; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; @@ -27,7 +26,7 @@ use GuzzleHttp\Psr7\Uri; use http\Exception\InvalidArgumentException; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Aws\Exception\UnresolvedEndpointException; /** @@ -36,7 +35,6 @@ */ class S3ClientTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testCanUseBucketEndpoint() diff --git a/tests/S3/S3EndpointMiddlewareTest.php b/tests/S3/S3EndpointMiddlewareTest.php index 30ede0aa0b..8887bdd94d 100644 --- a/tests/S3/S3EndpointMiddlewareTest.php +++ b/tests/S3/S3EndpointMiddlewareTest.php @@ -6,17 +6,15 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\S3\S3EndpointMiddleware; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class S3EndpointMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** diff --git a/tests/S3/S3MultiRegionClientTest.php b/tests/S3/S3MultiRegionClientTest.php index a1fb4c24ca..fb71936612 100644 --- a/tests/S3/S3MultiRegionClientTest.php +++ b/tests/S3/S3MultiRegionClientTest.php @@ -8,7 +8,6 @@ use Aws\ResultInterface; use Aws\S3\S3ClientInterface; use Aws\S3\S3MultiRegionClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7; @@ -16,11 +15,10 @@ use GuzzleHttp\Promise; use GuzzleHttp\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; class S3MultiRegionClientTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testWillRecoverFromPermanentRedirect() @@ -286,7 +284,7 @@ public function testCachesBucketLocation() ]); $client->getObject(['Bucket' => 'foo', 'Key' => 'bar']); - $this->assertSame('us-west-2', $this->readAttribute($client, 'cache')->get('aws:s3:foo:location')); + $this->assertSame('us-west-2', $this->getPropertyValue($client, 'cache')->get('aws:s3:foo:location')); } public function testRethrowsAwsExceptionViaMiddleware() @@ -363,7 +361,7 @@ public function testCachesBucketLocationAfterLookupWithPathStyle() ]); $client->getObject(['Bucket' => 'foo', 'Key' => 'bar']); - $this->assertSame('us-west-2', $this->readAttribute($client, 'cache')->get('aws:s3:foo:location')); + $this->assertSame('us-west-2', $this->getPropertyValue($client, 'cache')->get('aws:s3:foo:location')); } public function testCachesBucketLocationWithPathStyle() @@ -385,7 +383,7 @@ public function testCachesBucketLocationWithPathStyle() ]); $client->getObject(['Bucket' => 'foo', 'Key' => 'bar']); - $this->assertSame('us-west-2', $this->readAttribute($client, 'cache')->get('aws:s3:foo:location')); + $this->assertSame('us-west-2', $this->getPropertyValue($client, 'cache')->get('aws:s3:foo:location')); } public function testReadsBucketLocationFromCache() diff --git a/tests/S3/S3UriParserTest.php b/tests/S3/S3UriParserTest.php index 73525d70ff..3d6eb4a910 100644 --- a/tests/S3/S3UriParserTest.php +++ b/tests/S3/S3UriParserTest.php @@ -3,16 +3,13 @@ use Aws\Arn\Exception\InvalidArnException; use Aws\S3\S3UriParser; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\S3\S3UriParser */ class S3UriParserTest extends TestCase { - use PHPUnitCompatTrait; - public function uriProvider() { return [ diff --git a/tests/S3/SSECMiddlewareTest.php b/tests/S3/SSECMiddlewareTest.php index a988d19109..21dfd1f83d 100644 --- a/tests/S3/SSECMiddlewareTest.php +++ b/tests/S3/SSECMiddlewareTest.php @@ -3,16 +3,14 @@ use Aws\Middleware; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\S3\SSECMiddleware */ class SSECMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** diff --git a/tests/S3/StreamWrapperPathStyleTest.php b/tests/S3/StreamWrapperPathStyleTest.php index 162070dfc7..68ce5bc3f8 100644 --- a/tests/S3/StreamWrapperPathStyleTest.php +++ b/tests/S3/StreamWrapperPathStyleTest.php @@ -9,17 +9,15 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\S3\StreamWrapper */ class StreamWrapperPathStyleTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -28,7 +26,7 @@ class StreamWrapperPathStyleTest extends TestCase /** @var LruArrayCache */ private $cache; - public function _setUp() + public function set_up() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -40,7 +38,7 @@ public function _setUp() $this->client->registerStreamWrapper(); } - public function _tearDown() + public function tear_down() { stream_wrapper_unregister('s3'); $this->client = null; diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index abf7b99b3d..ae858a46bf 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -9,10 +9,9 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; /** @@ -20,7 +19,6 @@ */ class StreamWrapperTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -29,7 +27,7 @@ class StreamWrapperTest extends TestCase /** @var LruArrayCache */ private $cache; - public function _setUp() + public function set_up() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -38,7 +36,7 @@ public function _setUp() $this->client->registerStreamWrapper(); } - public function _tearDown() + public function tear_down() { stream_wrapper_unregister('s3'); $this->client = null; diff --git a/tests/S3/StreamWrapperV2ExistenceTest.php b/tests/S3/StreamWrapperV2ExistenceTest.php index 7f0879ca25..a9746080ff 100644 --- a/tests/S3/StreamWrapperV2ExistenceTest.php +++ b/tests/S3/StreamWrapperV2ExistenceTest.php @@ -9,11 +9,10 @@ use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\S3\StreamWrapper; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Response; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; /** @@ -21,7 +20,6 @@ */ class StreamWrapperV2ExistenceTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; /** @var S3Client */ @@ -30,7 +28,7 @@ class StreamWrapperV2ExistenceTest extends TestCase /** @var LruArrayCache */ private $cache; - public function _setUp() + public function set_up() { // use a fresh LRU cache for each test. $this->cache = new LruArrayCache(); @@ -39,7 +37,7 @@ public function _setUp() $this->client->registerStreamWrapperV2(); } - public function _tearDown() + public function tear_down() { stream_wrapper_unregister('s3'); $this->client = null; diff --git a/tests/S3/TransferTest.php b/tests/S3/TransferTest.php index 99f74c5740..680a7c5e9f 100644 --- a/tests/S3/TransferTest.php +++ b/tests/S3/TransferTest.php @@ -6,11 +6,10 @@ use Aws\Result; use Aws\S3\S3Client; use Aws\S3\Transfer; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use SplFileInfo; /** @@ -18,7 +17,6 @@ */ class TransferTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testEnsuresBaseDirIsAvailable() diff --git a/tests/S3/UseArnRegion/ConfigurationProviderTest.php b/tests/S3/UseArnRegion/ConfigurationProviderTest.php index 6f1b378426..ba3eda9993 100644 --- a/tests/S3/UseArnRegion/ConfigurationProviderTest.php +++ b/tests/S3/UseArnRegion/ConfigurationProviderTest.php @@ -6,17 +6,14 @@ use Aws\S3\UseArnRegion\ConfigurationInterface; use Aws\S3\UseArnRegion\ConfigurationProvider; use Aws\S3\UseArnRegion\Exception\ConfigurationException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\S3\UseArnRegion\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_USE_ARN_REGION) ?: '', @@ -58,7 +55,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_USE_ARN_REGION . '=' . self::$originalEnv['use_arn_region']); diff --git a/tests/S3/UseArnRegion/ConfigurationTest.php b/tests/S3/UseArnRegion/ConfigurationTest.php index d7d69bbf4a..9f05028cee 100644 --- a/tests/S3/UseArnRegion/ConfigurationTest.php +++ b/tests/S3/UseArnRegion/ConfigurationTest.php @@ -2,16 +2,13 @@ namespace Aws\Test\S3\UseArnRegion; use Aws\S3\UseArnRegion\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\S3\UseArnRegion\Configuration */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - /** * @dataProvider correctValueCases * diff --git a/tests/S3Control/EndpointArnMiddlewareTest.php b/tests/S3Control/EndpointArnMiddlewareTest.php index 4f02d08544..de289691bc 100644 --- a/tests/S3Control/EndpointArnMiddlewareTest.php +++ b/tests/S3Control/EndpointArnMiddlewareTest.php @@ -6,11 +6,10 @@ use Aws\Exception\InvalidRegionException; use Aws\Exception\UnresolvedEndpointException; use Aws\Middleware; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\S3Control\S3ControlTestingTrait; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Response; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; /** @@ -18,7 +17,6 @@ */ class EndpointArnMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; use S3ControlTestingTrait; /** diff --git a/tests/Script/ComposerTest.php b/tests/Script/ComposerTest.php index 1f2baa609a..8144caeb70 100644 --- a/tests/Script/ComposerTest.php +++ b/tests/Script/ComposerTest.php @@ -3,14 +3,11 @@ use Aws; use Aws\Script\Composer\Composer; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Symfony\Component\Filesystem\Filesystem; class ComposerTest extends TestCase { - use PHPUnitCompatTrait; - public function invalidServiceNameProvider() { return [ diff --git a/tests/SdkTest.php b/tests/SdkTest.php index e000f7df33..698b1539a3 100644 --- a/tests/SdkTest.php +++ b/tests/SdkTest.php @@ -5,15 +5,13 @@ use Aws\MultiRegionClient; use Aws\S3\S3MultiRegionClient; use Aws\Sdk; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Sdk */ class SdkTest extends TestCase { - use PHPUnitCompatTrait; public function testEnsuresMissingMethodThrowsException() { diff --git a/tests/Signature/S3SignatureV4Test.php b/tests/Signature/S3SignatureV4Test.php index 0cf7198ac6..45c57d47ff 100644 --- a/tests/Signature/S3SignatureV4Test.php +++ b/tests/Signature/S3SignatureV4Test.php @@ -3,25 +3,21 @@ use Aws\Credentials\Credentials; use Aws\Signature\S3SignatureV4; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use GuzzleHttp\Psr7\Request; require_once __DIR__ . '/sig_hack.php'; -use PHPUnit\Framework\TestCase; - /** * @covers Aws\Signature\S3SignatureV4 */ class S3SignatureV4Test extends TestCase { - use PHPUnitCompatTrait; - - public static function _setUpBeforeClass() + public static function set_up_before_class() { $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC'); } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { unset($_SERVER['aws_time']); } diff --git a/tests/Signature/SignatureProviderTest.php b/tests/Signature/SignatureProviderTest.php index e04fb2cd94..f65c1c566c 100644 --- a/tests/Signature/SignatureProviderTest.php +++ b/tests/Signature/SignatureProviderTest.php @@ -2,16 +2,13 @@ namespace Aws\Test\Signature; use Aws\Signature\SignatureProvider; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Signature\SignatureProvider */ class SignatureProviderTest extends TestCase { - use PHPUnitCompatTrait; - public function versionProvider() { return [ diff --git a/tests/Signature/SignatureV4Test.php b/tests/Signature/SignatureV4Test.php index 0ccb6ffad8..cd0c8f3679 100644 --- a/tests/Signature/SignatureV4Test.php +++ b/tests/Signature/SignatureV4Test.php @@ -3,33 +3,30 @@ use Aws\Credentials\Credentials; use Aws\Signature\SignatureV4; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\NoSeekStream; require_once __DIR__ . '/sig_hack.php'; -use PHPUnit\Framework\TestCase; /** * @covers Aws\Signature\SignatureV4 */ class SignatureV4Test extends TestCase { - use PHPUnitCompatTrait; - const DEFAULT_KEY = 'AKIDEXAMPLE'; const DEFAULT_SECRET = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'; const DEFAULT_DATETIME = 'Mon, 09 Sep 2011 23:36:00 GMT'; - public function _setUp() + public function set_up() { $_SERVER['aws_time'] = strtotime('December 5, 2013 00:00:00 UTC'); } - public function _tearDown() + public function tear_down() { - parent::tearDown(); + parent::tear_down(); unset($_SERVER['aws_time']); } @@ -37,8 +34,8 @@ public function _tearDown() public function testReturnsRegionAndService() { $s = new SignatureV4('foo', 'bar'); - $this->assertSame('foo', $this->readAttribute($s, 'service')); - $this->assertSame('bar', $this->readAttribute($s, 'region')); + $this->assertSame('foo', $this->getPropertyValue($s, 'service')); + $this->assertSame('bar', $this->getPropertyValue($s, 'region')); } public function testAddsSecurityTokenIfPresent() @@ -86,19 +83,19 @@ public function testMaintainsCappedCache() $request = new Request('GET', 'http://www.example.com'); $credentials = new Credentials('fizz', 'buzz'); $sig->signRequest($request, $credentials); - $this->assertCount(1, $this->readAttribute($sig, 'cache')); + $this->assertCount(1, $this->getPropertyValue($sig, 'cache')); $credentials = new Credentials('fizz', 'baz'); $sig->signRequest($request, $credentials); - $this->assertCount(2, $this->readAttribute($sig, 'cache')); + $this->assertCount(2, $this->getPropertyValue($sig, 'cache')); $credentials = new Credentials('fizz', 'paz'); $sig->signRequest($request, $credentials); - $this->assertCount(3, $this->readAttribute($sig, 'cache')); + $this->assertCount(3, $this->getPropertyValue($sig, 'cache')); $credentials = new Credentials('fizz', 'foobar'); $sig->signRequest($request, $credentials); - $this->assertCount(1, $this->readAttribute($sig, 'cache')); + $this->assertCount(1, $this->getPropertyValue($sig, 'cache')); } private function getFixtures() diff --git a/tests/Sqs/SqsClientTest.php b/tests/Sqs/SqsClientTest.php index a3ba034678..0b9e7f0d0d 100644 --- a/tests/Sqs/SqsClientTest.php +++ b/tests/Sqs/SqsClientTest.php @@ -4,16 +4,14 @@ use Aws\Middleware; use Aws\Result; use Aws\Sqs\SqsClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\Test\UsesServiceTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Sqs\SqsClient */ class SqsClientTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testGetQueueArn() diff --git a/tests/StreamRequestPayloadMiddlewareTest.php b/tests/StreamRequestPayloadMiddlewareTest.php index dd98140f96..d3deb9675f 100644 --- a/tests/StreamRequestPayloadMiddlewareTest.php +++ b/tests/StreamRequestPayloadMiddlewareTest.php @@ -9,10 +9,10 @@ use Aws\Middleware; use Aws\Result; use Aws\StreamRequestPayloadMiddleware; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; +use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; /** @@ -20,7 +20,7 @@ */ class StreamRequestPayloadMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; + use ArraySubsetAsserts; /** * @dataProvider generateTestCases diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index 2b720b1582..78589b0e6a 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -7,17 +7,14 @@ use Aws\Sts\RegionalEndpoints\ConfigurationInterface; use Aws\Sts\RegionalEndpoints\ConfigurationProvider; use Aws\Sts\RegionalEndpoints\Exception\ConfigurationException; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * git\Sts\RegionalEndpoints\ConfigurationProvider */ class ConfigurationProviderTest extends TestCase { - use PHPUnitCompatTrait; - private static $originalEnv; private $iniFile = << getenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE) ?: '', @@ -59,7 +56,7 @@ private function clearEnv() return $dir; } - public static function _tearDownAfterClass() + public static function tear_down_after_class() { putenv(ConfigurationProvider::ENV_ENDPOINTS_TYPE . '=' . self::$originalEnv['endpoints_type']); diff --git a/tests/Sts/RegionalEndpoints/ConfigurationTest.php b/tests/Sts/RegionalEndpoints/ConfigurationTest.php index f7767a5b53..ec4120c89e 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationTest.php @@ -3,16 +3,13 @@ namespace Aws\Test\Sts\RegionalEndpoints; use Aws\Sts\RegionalEndpoints\Configuration; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers \Aws\Sts\RegionalEndpoints\Configuration */ class ConfigurationTest extends TestCase { - use PHPUnitCompatTrait; - public function testGetsCorrectValues() { $config = new Configuration('regional'); diff --git a/tests/Sts/StsClientTest.php b/tests/Sts/StsClientTest.php index e7a0f63732..03b15cebcb 100644 --- a/tests/Sts/StsClientTest.php +++ b/tests/Sts/StsClientTest.php @@ -8,17 +8,14 @@ use Aws\Result; use Aws\Sts\RegionalEndpoints\Configuration; use Aws\Sts\StsClient; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Psr7\Uri; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Sts\StsClient */ class StsClientTest extends TestCase { - use PHPUnitCompatTrait; - public function testCanCreateCredentialsObjectFromStsResult() { $result = new Result([ diff --git a/tests/TraceMiddlewareTest.php b/tests/TraceMiddlewareTest.php index b5fca3fcf5..8c60138200 100644 --- a/tests/TraceMiddlewareTest.php +++ b/tests/TraceMiddlewareTest.php @@ -7,21 +7,18 @@ use Aws\Exception\AwsException; use Aws\HandlerList; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\TraceMiddleware; use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Promise; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\TraceMiddleware */ class TraceMiddlewareTest extends TestCase { - use PHPUnitCompatTrait; - public function testEmitsDebugInfo() { $str = ''; diff --git a/tests/WaiterTest.php b/tests/WaiterTest.php index 7b22116918..05baefc709 100644 --- a/tests/WaiterTest.php +++ b/tests/WaiterTest.php @@ -6,7 +6,6 @@ use Aws\DynamoDb\DynamoDbClient; use Aws\Exception\AwsException; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Promise; use GuzzleHttp\Promise\FulfilledPromise; @@ -15,14 +14,13 @@ use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7; use Psr\Http\Message\RequestInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\Waiter */ class WaiterTest extends TestCase { - use PHPUnitCompatTrait; use UsesServiceTrait; public function testErrorOnBadConfig() diff --git a/tests/WrappedHttpHandlerTest.php b/tests/WrappedHttpHandlerTest.php index 5ee622d8cc..186e04e842 100644 --- a/tests/WrappedHttpHandlerTest.php +++ b/tests/WrappedHttpHandlerTest.php @@ -10,21 +10,19 @@ use Aws\CommandInterface; use Aws\Exception\AwsException; use Aws\Result; -use Aws\Test\Polyfill\PHPUnit\PHPUnitCompatTrait; use Aws\WrappedHttpHandler; use GuzzleHttp\Promise\RejectedPromise; use Psr\Http\Message\RequestInterface; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\ResponseInterface; -use PHPUnit\Framework\TestCase; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; /** * @covers Aws\WrappedHttpHandler */ class WrappedHttpHandlerTest extends TestCase { - use PHPUnitCompatTrait; use TestServiceTrait; public function testParsesResponses() diff --git a/tests/bootstrap.php b/tests/bootstrap.php index b331f5e341..3591ad7425 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -29,8 +29,6 @@ class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warnin $version = class_exists('PHPUnit_Runner_Version') ? PHPUnit_Runner_Version::id() : PHPUnit\Runner\Version::id(); $versionData = explode('.', $version); -include_once(sprintf("%s/Polyfill/PHPUnit%s/PHPUnitCompatTrait.php", __DIR__, $versionData[0])); - if (PHP_VERSION_ID >= 70400 && $versionData[0] == 5) { $vendorGeneratorPath = __DIR__ . '/../vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php'; $patchGeneratorPath = __DIR__ . '/bootstrap/PHPUnit_Framework_MockObject_Generator_7.4.php'; From 661ac2f59084f4ee86965a16127e138ae3bcb311 Mon Sep 17 00:00:00 2001 From: Zombaya Date: Thu, 11 Aug 2022 21:17:23 +0200 Subject: [PATCH 29/31] Replace $this->expectNotToPerformAssertions() with $this->addToAssertionCount(1) --- tests/Api/ValidatorTest.php | 2 +- tests/EndpointParameterMiddlewareTest.php | 2 +- tests/S3/Crypto/S3EncryptionClientTest.php | 4 ++-- tests/S3/Crypto/S3EncryptionClientV2Test.php | 4 ++-- tests/S3/S3UriParserTest.php | 4 ++-- tests/S3/StreamWrapperV2ExistenceTest.php | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/Api/ValidatorTest.php b/tests/Api/ValidatorTest.php index 719d499197..5975323fe0 100644 --- a/tests/Api/ValidatorTest.php +++ b/tests/Api/ValidatorTest.php @@ -619,7 +619,7 @@ public function testValidatesInput($shape, $input, $result) try { $validator->validate('Foo', $shape, $input); - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); if ($result !== true) { $this->fail('Should have failed with ' . $result); } diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index d59f32169a..44089b2feb 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -78,7 +78,7 @@ public function testCorrectlyOutputsHost( $expectedHost ) { if ($cmdName === 'NoEndpointOp') { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); } $client = $this->generateTestClient($service, $clientArgs); $command = $client->getCommand($cmdName, $params); diff --git a/tests/S3/Crypto/S3EncryptionClientTest.php b/tests/S3/Crypto/S3EncryptionClientTest.php index c7bc88ad56..6eb53f30fa 100644 --- a/tests/S3/Crypto/S3EncryptionClientTest.php +++ b/tests/S3/Crypto/S3EncryptionClientTest.php @@ -265,7 +265,7 @@ public function testPutObjectValidatesCipher( if ($exception) { $this->setupProvidedExpectedException($exception); } else { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); } $s3 = $this->getS3Client(); @@ -302,7 +302,7 @@ public function testPutObjectValidatesKeySize( if ($exception) { $this->setupProvidedExpectedException($exception); } else { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); } $cipherOptions = [ diff --git a/tests/S3/Crypto/S3EncryptionClientV2Test.php b/tests/S3/Crypto/S3EncryptionClientV2Test.php index 05e4ff0a40..4930182eb0 100644 --- a/tests/S3/Crypto/S3EncryptionClientV2Test.php +++ b/tests/S3/Crypto/S3EncryptionClientV2Test.php @@ -273,7 +273,7 @@ public function testPutObjectValidatesCipher( if ($exception) { $this->setupProvidedExpectedException($exception); } else { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); } $s3 = $this->getS3Client(); @@ -314,7 +314,7 @@ public function testPutObjectValidatesKeySize( if ($exception) { $this->setupProvidedExpectedException($exception); } else { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); } $cipherOptions = [ diff --git a/tests/S3/S3UriParserTest.php b/tests/S3/S3UriParserTest.php index 3d6eb4a910..39c9b4d864 100644 --- a/tests/S3/S3UriParserTest.php +++ b/tests/S3/S3UriParserTest.php @@ -101,12 +101,12 @@ public function testParsesUrls($uri, $result, $isError = false) ksort($actual); $this->assertSame($result, $actual); } catch (\InvalidArgumentException $e) { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); if (!$isError) { throw $e; } } catch (InvalidArnException $e) { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); if (!$isError) { throw $e; } diff --git a/tests/S3/StreamWrapperV2ExistenceTest.php b/tests/S3/StreamWrapperV2ExistenceTest.php index a9746080ff..301cd44975 100644 --- a/tests/S3/StreamWrapperV2ExistenceTest.php +++ b/tests/S3/StreamWrapperV2ExistenceTest.php @@ -875,7 +875,7 @@ public function testProvidesDirectoriesForS3() public function testCanSetDelimiterStreamContext() { - $this->expectNotToPerformAssertions(); + $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); $this->addMockResults($this->client, [ [ 'IsTruncated' => false, From e67a48e98b17f2fd5f5b224ce607347340fb83d4 Mon Sep 17 00:00:00 2001 From: Sean O'Brien <60306702+stobrien89@users.noreply.github.com> Date: Mon, 12 Sep 2022 14:26:45 -0400 Subject: [PATCH 30/31] fix spacing --- src/Api/Serializer/JsonBody.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Api/Serializer/JsonBody.php b/src/Api/Serializer/JsonBody.php index 39838b64b4..0b116e0e46 100644 --- a/src/Api/Serializer/JsonBody.php +++ b/src/Api/Serializer/JsonBody.php @@ -35,7 +35,7 @@ public static function getContentType(Service $service) $jsonVersion = $service->getMetadata('jsonVersion'); if (empty($jsonVersion)) { throw new \InvalidArgumentException('invalid json'); - }else { + } else { return 'application/x-amz-json-' . @number_format($service->getMetadata('jsonVersion'), 1); } From 06e01bfb67245a352028c9993b226cc4181de1a9 Mon Sep 17 00:00:00 2001 From: Sean O'Brien <60306702+stobrien89@users.noreply.github.com> Date: Mon, 12 Sep 2022 15:14:36 -0400 Subject: [PATCH 31/31] Fix spacing --- tests/S3/S3ClientTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/S3/S3ClientTest.php b/tests/S3/S3ClientTest.php index b2c64a595f..d38820d6b2 100644 --- a/tests/S3/S3ClientTest.php +++ b/tests/S3/S3ClientTest.php @@ -332,7 +332,7 @@ public function testsIfExists( } else { $this->assertSame($exists, $s3->doesBucketExistV2($bucket, $accept403)); } - }else { + } else { if ($key) { $this->assertSame($exists, $s3->doesObjectExist($bucket, $key)); } else {