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 0e716eed51..336c0b672e 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)); }