diff --git a/BigQuery/tests/Snippet/BigQueryClientTest.php b/BigQuery/tests/Snippet/BigQueryClientTest.php index 1796ce1293dc..d7bca8300937 100644 --- a/BigQuery/tests/Snippet/BigQueryClientTest.php +++ b/BigQuery/tests/Snippet/BigQueryClientTest.php @@ -19,19 +19,20 @@ use Google\Cloud\BigQuery\BigQueryClient; use Google\Cloud\BigQuery\Bytes; -use Google\Cloud\BigQuery\Date; -use Google\Cloud\BigQuery\Numeric; -use Google\Cloud\BigQuery\Time; -use Google\Cloud\BigQuery\Timestamp; use Google\Cloud\BigQuery\Connection\ConnectionInterface; use Google\Cloud\BigQuery\Dataset; +use Google\Cloud\BigQuery\Date; use Google\Cloud\BigQuery\Job; +use Google\Cloud\BigQuery\Numeric; use Google\Cloud\BigQuery\QueryJobConfiguration; use Google\Cloud\BigQuery\QueryResults; +use Google\Cloud\BigQuery\Time; +use Google\Cloud\BigQuery\Timestamp; use Google\Cloud\BigQuery\ValueMapper; use Google\Cloud\Core\Int64; use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Prophecy\Argument; /** @@ -71,7 +72,7 @@ class BigQueryClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(BigQueryTestClient::class); + $this->client = TestHelpers::stub(BigQueryTestClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } @@ -132,7 +133,10 @@ public function testQueryWithLocation() $array = $config->toArray(); $this->assertInstanceOf(QueryJobConfiguration::class, $config); - $this->assertEquals('SELECT name FROM `my_project.users_dataset.users` LIMIT 100', $array['configuration']['query']['query']); + $this->assertEquals( + 'SELECT name FROM `my_project.users_dataset.users` LIMIT 100', + $array['configuration']['query']['query'] + ); $this->assertEquals('asia-northeast1', $array['jobReference']['location']); } @@ -442,6 +446,7 @@ public function testGetServiceAccount() } } +//@codingStandardsIgnoreStart class BigQueryTestClient extends BigQueryClient { public function query($query, array $options = []) @@ -462,3 +467,4 @@ protected function generateJobId() return BigQueryClientTest::JOB_ID; } } +//@codingStandardsIgnoreEnd diff --git a/BigQuery/tests/Snippet/CopyJobConfigurationTest.php b/BigQuery/tests/Snippet/CopyJobConfigurationTest.php index dee8508dfe08..d9ee96c93e7b 100644 --- a/BigQuery/tests/Snippet/CopyJobConfigurationTest.php +++ b/BigQuery/tests/Snippet/CopyJobConfigurationTest.php @@ -20,6 +20,7 @@ use Google\Cloud\BigQuery\BigQueryClient; use Google\Cloud\BigQuery\CopyJobConfiguration; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; /** * @group bigquery @@ -71,7 +72,7 @@ public function testSetters($method, $expected, $bq = null) public function setterDataProvider() { - $bq = \Google\Cloud\Core\Testing\TestHelpers::stub(BigQueryClient::class, [ + $bq = TestHelpers::stub(BigQueryClient::class, [ ['projectId' => self::PROJECT_ID] ]); diff --git a/BigQuery/tests/Snippet/ExtractJobConfigurationTest.php b/BigQuery/tests/Snippet/ExtractJobConfigurationTest.php index 36228a85a9ca..6e5938f39c4d 100644 --- a/BigQuery/tests/Snippet/ExtractJobConfigurationTest.php +++ b/BigQuery/tests/Snippet/ExtractJobConfigurationTest.php @@ -21,6 +21,7 @@ use Google\Cloud\BigQuery\ExtractJobConfiguration; use Google\Cloud\BigQuery\Table; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; /** * @group bigquery @@ -72,7 +73,7 @@ public function testSetters($method, $expected, $bq = null) public function setterDataProvider() { - $bq = \Google\Cloud\Core\Testing\TestHelpers::stub(BigQueryClient::class, [ + $bq = TestHelpers::stub(BigQueryClient::class, [ ['projectId' => self::PROJECT_ID] ]); diff --git a/BigQuery/tests/Snippet/LoadJobConfigurationTest.php b/BigQuery/tests/Snippet/LoadJobConfigurationTest.php index 16350828e723..38ebe82ffa27 100644 --- a/BigQuery/tests/Snippet/LoadJobConfigurationTest.php +++ b/BigQuery/tests/Snippet/LoadJobConfigurationTest.php @@ -20,6 +20,7 @@ use Google\Cloud\BigQuery\BigQueryClient; use Google\Cloud\BigQuery\LoadJobConfiguration; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; /** * @group bigquery @@ -82,7 +83,7 @@ public function testSetters($method, $expected, $bq = null) public function setterDataProvider() { - $bq = \Google\Cloud\Core\Testing\TestHelpers::stub(BigQueryClient::class, [ + $bq = TestHelpers::stub(BigQueryClient::class, [ ['projectId' => self::PROJECT_ID] ]); diff --git a/BigQuery/tests/Snippet/QueryJobConfigurationTest.php b/BigQuery/tests/Snippet/QueryJobConfigurationTest.php index 8649bd28745e..a0c860e35f6d 100644 --- a/BigQuery/tests/Snippet/QueryJobConfigurationTest.php +++ b/BigQuery/tests/Snippet/QueryJobConfigurationTest.php @@ -21,6 +21,7 @@ use Google\Cloud\BigQuery\QueryJobConfiguration; use Google\Cloud\BigQuery\ValueMapper; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; /** * @group bigquery @@ -73,7 +74,7 @@ public function testSetters($method, $expected, $bq = null) public function setterDataProvider() { - $bq = \Google\Cloud\Core\Testing\TestHelpers::stub(BigQueryClient::class, [ + $bq = TestHelpers::stub(BigQueryClient::class, [ ['projectId' => self::PROJECT_ID] ]); diff --git a/BigQuery/tests/Snippet/QueryResultsTest.php b/BigQuery/tests/Snippet/QueryResultsTest.php index 479638fbaf03..368c92c1b6bf 100644 --- a/BigQuery/tests/Snippet/QueryResultsTest.php +++ b/BigQuery/tests/Snippet/QueryResultsTest.php @@ -22,6 +22,7 @@ use Google\Cloud\BigQuery\QueryResults; use Google\Cloud\BigQuery\ValueMapper; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Prophecy\Argument; /** @@ -63,7 +64,7 @@ public function setUp() ]; $this->connection = $this->prophesize(ConnectionInterface::class); - $this->qr = \Google\Cloud\Core\Testing\TestHelpers::stub(QueryResults::class, [ + $this->qr = TestHelpers::stub(QueryResults::class, [ $this->connection->reveal(), self::JOB_ID, self::PROJECT, diff --git a/BigQuery/tests/Snippet/TableTest.php b/BigQuery/tests/Snippet/TableTest.php index 0c421e41430c..03eb5e7344b3 100644 --- a/BigQuery/tests/Snippet/TableTest.php +++ b/BigQuery/tests/Snippet/TableTest.php @@ -28,8 +28,9 @@ use Google\Cloud\BigQuery\Table; use Google\Cloud\BigQuery\ValueMapper; use Google\Cloud\Core\Iterator\ItemIterator; -use Google\Cloud\Core\Upload\MultipartUploader; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; +use Google\Cloud\Core\Upload\MultipartUploader; use Google\Cloud\Storage\Connection\Rest as StorageConnection; use Google\Cloud\Storage\StorageClient; use Prophecy\Argument; @@ -73,7 +74,7 @@ public function setUp() $this->mapper = new ValueMapper(false); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->table = \Google\Cloud\Core\Testing\TestHelpers::stub(Table::class, [ + $this->table = TestHelpers::stub(Table::class, [ $this->connection->reveal(), self::ID, self::DSID, @@ -202,7 +203,7 @@ public function testStartJob() public function testCopy() { - $bq = \Google\Cloud\Core\Testing\TestHelpers::stub(BigQueryClient::class); + $bq = TestHelpers::stub(BigQueryClient::class); $snippet = $this->snippetFromMethod(Table::class, 'copy'); $snippet->addLocal('bigQuery', $bq); $bq->___setProperty('connection', $this->connection->reveal()); @@ -229,7 +230,7 @@ public function testCopy() public function testExtract() { - $storage = \Google\Cloud\Core\Testing\TestHelpers::stub(StorageClient::class); + $storage = TestHelpers::stub(StorageClient::class); $storage->___setProperty('connection', $this->prophesize(StorageConnection::class)->reveal()); $snippet = $this->snippetFromMethod(Table::class, 'extract'); $snippet->addLocal('storage', $storage); @@ -274,7 +275,7 @@ public function testLoad() public function testLoadFromStorage() { - $storage = \Google\Cloud\Core\Testing\TestHelpers::stub(StorageClient::class); + $storage = TestHelpers::stub(StorageClient::class); $storage->___setProperty('connection', $this->prophesize(StorageConnection::class)->reveal()); $snippet = $this->snippetFromMethod(Table::class, 'loadFromStorage'); $snippet->addLocal('storage', $storage); @@ -336,7 +337,10 @@ public function testInfo() $snippet->addLocal('table', $this->table); $res = $snippet->invoke(); - $this->assertEquals('https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/mynewdataset', $res->output()); + $this->assertEquals( + 'https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/mynewdataset', + $res->output() + ); } public function testReload() @@ -353,7 +357,10 @@ public function testReload() $this->table->___setProperty('connection', $this->connection->reveal()); $res = $snippet->invoke(); - $this->assertEquals('https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/myupdateddataset', $res->output()); + $this->assertEquals( + 'https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/myupdateddataset', + $res->output() + ); } public function testId() diff --git a/BigQuery/tests/System/BigQueryTestCase.php b/BigQuery/tests/System/BigQueryTestCase.php index d503310dc197..4b5ef26eb8e4 100644 --- a/BigQuery/tests/System/BigQueryTestCase.php +++ b/BigQuery/tests/System/BigQueryTestCase.php @@ -59,12 +59,8 @@ public static function setUpBeforeClass() protected static function createTable(Dataset $dataset, $name, array $options = []) { if (!isset($options['schema'])) { - $options['schema']['fields'] = json_decode( - file_get_contents(__DIR__ . '/data/table-schema.json'), true - ); + $options['schema']['fields'] = json_decode(file_get_contents(__DIR__ . '/data/table-schema.json'), true); } return $dataset->createTable(uniqid(self::TESTING_PREFIX), $options); } } - - diff --git a/BigQuery/tests/Unit/BigQueryClientTest.php b/BigQuery/tests/Unit/BigQueryClientTest.php index dca5f11f1e63..ed5105f18906 100644 --- a/BigQuery/tests/Unit/BigQueryClientTest.php +++ b/BigQuery/tests/Unit/BigQueryClientTest.php @@ -323,20 +323,16 @@ public function testGetsDatasetsWithToken() { $client = $this->getClient(); $this->connection->listDatasets(Argument::any()) - ->willReturn( - [ - 'nextPageToken' => 'token', - 'datasets' => [ - ['datasetReference' => ['datasetId' => 'someOtherdatasetId']] - ] - ], - [ - 'datasets' => [ - ['datasetReference' => ['datasetId' => self::DATASET_ID]] - ] + ->willReturn([ + 'nextPageToken' => 'token', + 'datasets' => [ + ['datasetReference' => ['datasetId' => 'someOtherdatasetId']] + ] + ], [ + 'datasets' => [ + ['datasetReference' => ['datasetId' => self::DATASET_ID]] ] - ) - ->shouldBeCalledTimes(2); + ])->shouldBeCalledTimes(2); $client->___setProperty('connection', $this->connection->reveal()); $dataset = iterator_to_array($client->datasets()); diff --git a/BigQuery/tests/Unit/DatasetTest.php b/BigQuery/tests/Unit/DatasetTest.php index bd66499c26f4..01c7f80ff7fc 100644 --- a/BigQuery/tests/Unit/DatasetTest.php +++ b/BigQuery/tests/Unit/DatasetTest.php @@ -146,20 +146,16 @@ public function testGetsTablesWithoutToken() public function testGetsTablesWithToken() { $this->connection->listTables(Argument::any()) - ->willReturn( - [ - 'nextPageToken' => 'token', - 'tables' => [ - ['tableReference' => ['tableId' => 'someOthertableId']] - ] - ], - [ - 'tables' => [ - ['tableReference' => ['tableId' => $this->tableId]] - ] + ->willReturn([ + 'nextPageToken' => 'token', + 'tables' => [ + ['tableReference' => ['tableId' => 'someOthertableId']] + ] + ], [ + 'tables' => [ + ['tableReference' => ['tableId' => $this->tableId]] ] - ) - ->shouldBeCalledTimes(2); + ])->shouldBeCalledTimes(2); $dataset = $this->getDataset($this->connection); $tables = iterator_to_array($dataset->tables()); diff --git a/BigQuery/tests/Unit/JobConfigurationTraitTest.php b/BigQuery/tests/Unit/JobConfigurationTraitTest.php index 7b5ca7e74dff..1186802d2961 100644 --- a/BigQuery/tests/Unit/JobConfigurationTraitTest.php +++ b/BigQuery/tests/Unit/JobConfigurationTraitTest.php @@ -18,8 +18,9 @@ namespace Google\Cloud\BigQuery\Tests\Unit; use Google\Cloud\BigQuery\JobConfigurationTrait; -use Ramsey\Uuid\Uuid; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; +use Ramsey\Uuid\Uuid; /** * @group bigquery @@ -34,7 +35,7 @@ class JobConfigurationTraitTest extends TestCase public function setUp() { - $this->trait = \Google\Cloud\Core\Testing\TestHelpers::impl(JobConfigurationTrait::class); + $this->trait = TestHelpers::impl(JobConfigurationTrait::class); } public function testJobConfigurationProperties() diff --git a/BigQuery/tests/Unit/JobWaitTraitTest.php b/BigQuery/tests/Unit/JobWaitTraitTest.php index 922a41b4ba4d..7eba6b80caa4 100644 --- a/BigQuery/tests/Unit/JobWaitTraitTest.php +++ b/BigQuery/tests/Unit/JobWaitTraitTest.php @@ -19,6 +19,7 @@ use Google\Cloud\BigQuery\Job; use Google\Cloud\BigQuery\JobWaitTrait; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; /** @@ -31,7 +32,7 @@ class JobWaitTraitTest extends TestCase public function setUp() { - $this->trait = \Google\Cloud\Core\Testing\TestHelpers::impl(JobWaitTrait::class); + $this->trait = TestHelpers::impl(JobWaitTrait::class); $this->job = $this->prophesize(Job::class)->reveal(); } @@ -41,11 +42,11 @@ public function testWaitSucceedsWhenAlreadyComplete() $isReloadCalled = false; $this->trait->call('wait', [ - function() use (&$isCompleteCalled) { + function () use (&$isCompleteCalled) { $isCompleteCalled = true; return true; }, - function() use (&$isReloadCalled) { + function () use (&$isReloadCalled) { $isReloadCalled = true; return ['complete' => true]; }, @@ -63,11 +64,11 @@ public function testWaitCallsReloadThenSucceeds() $isReloadCalled = false; $this->trait->call('wait', [ - function() use (&$isCompleteCallCount, &$isReloadCalled) { + function () use (&$isCompleteCallCount, &$isReloadCalled) { $isCompleteCallCount++; return $isReloadCalled ? true : false; }, - function() use (&$isReloadCalled) { + function () use (&$isReloadCalled) { $isReloadCalled = true; return ['complete' => true]; }, @@ -86,8 +87,12 @@ function() use (&$isReloadCalled) { public function testWaitThrowsExceptionWhenMaxAttemptsMet() { $this->trait->call('wait', [ - function() { return false; }, - function () { return ['complete' => false]; }, + function () { + return false; + }, + function () { + return ['complete' => false]; + }, $this->job, 1 ]); diff --git a/BigQuery/tests/Unit/TableTest.php b/BigQuery/tests/Unit/TableTest.php index 2f0f372ac9a4..195ed9def8ce 100644 --- a/BigQuery/tests/Unit/TableTest.php +++ b/BigQuery/tests/Unit/TableTest.php @@ -678,6 +678,7 @@ public function testGetsIdentity() } } +//@codingStandardsIgnoreStart class TableStub extends Table { protected function usleep($ms) @@ -685,3 +686,4 @@ protected function usleep($ms) return; } } +//@codingStandardsIgnoreEnd diff --git a/BigQuery/tests/Unit/ValueMapperTest.php b/BigQuery/tests/Unit/ValueMapperTest.php index 7a6ef4156476..a2e7bca298b6 100644 --- a/BigQuery/tests/Unit/ValueMapperTest.php +++ b/BigQuery/tests/Unit/ValueMapperTest.php @@ -45,7 +45,7 @@ public function testThrowsExceptionWithUnhandledClass() */ public function testToParameterThrowsExceptionWithUnhandledType() { - $f = fopen('php://temp','r'); + $f = fopen('php://temp', 'r'); fclose($f); $mapper = new ValueMapper(false); $mapper->toParameter($f); diff --git a/Core/tests/Snippet/LongRunning/LongRunningOperationTest.php b/Core/tests/Snippet/LongRunning/LongRunningOperationTest.php index 8d2271825fa6..bf67d690ca03 100644 --- a/Core/tests/Snippet/LongRunning/LongRunningOperationTest.php +++ b/Core/tests/Snippet/LongRunning/LongRunningOperationTest.php @@ -20,6 +20,7 @@ use Google\Cloud\Core\LongRunning\LongRunningConnectionInterface; use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Prophecy\Argument; /** @@ -39,9 +40,14 @@ public function setUp() { $this->connection = $this->prophesize(LongRunningConnectionInterface::class); $this->callables = [ - ['typeUrl' => self::TYPE, 'callable' => function($res) { return $res; }] + [ + 'typeUrl' => self::TYPE, + 'callable' => function ($res) { + return $res; + } + ] ]; - $this->operation = \Google\Cloud\Core\Testing\TestHelpers::stub(LongRunningOperation::class, [ + $this->operation = TestHelpers::stub(LongRunningOperation::class, [ $this->connection->reveal(), self::NAME, $this->callables diff --git a/Core/tests/Snippet/Testing/Snippet/Parser/ParserTest.php b/Core/tests/Snippet/Testing/Snippet/Parser/ParserTest.php index 3f109d1dee01..fe193fc823f8 100644 --- a/Core/tests/Snippet/Testing/Snippet/Parser/ParserTest.php +++ b/Core/tests/Snippet/Testing/Snippet/Parser/ParserTest.php @@ -41,8 +41,7 @@ public function setUp() $this->docBlock = new DocBlock(null); $this->classSnippet = $this->parser->classExample(Parser::class); $this->methodSnippet = $this->parser->methodExample(Parser::class, 'methodExample'); - $this->secondMethodSnippet = $this->parser->methodExample( - Parser::class, 'methodExample', 1); + $this->secondMethodSnippet = $this->parser->methodExample(Parser::class, 'methodExample', 1); $this->classExamples = $this->parser->examplesFromClass($this->parser); $this->methodExamples = $this->parser->examplesFromMethod($this->parser, 'examplesFromMethod'); $this->allExamples = $this->parser->allExamples($this->parser); diff --git a/Core/tests/Unit/ArrayTraitTest.php b/Core/tests/Unit/ArrayTraitTest.php index 94facab388e0..cae83506e733 100644 --- a/Core/tests/Unit/ArrayTraitTest.php +++ b/Core/tests/Unit/ArrayTraitTest.php @@ -18,19 +18,20 @@ namespace Google\Cloud\Core\Tests\Unit; use Google\Cloud\Core\ArrayTrait; -use Prophecy\Argument; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group core */ class ArrayTraitTest extends TestCase { - private $implementation; + private $impl; public function setUp() { - $this->implementation = new ArrayTraitStub(); + $this->impl = TestHelpers::impl(ArrayTrait::class); } public function testPluck() @@ -38,7 +39,7 @@ public function testPluck() $value = '123'; $key = 'key'; $array = [$key => $value]; - $actualValue = $this->implementation->call('pluck', [$key, &$array]); + $actualValue = $this->impl->call('pluck', [$key, &$array]); $this->assertEquals($value, $actualValue); $this->assertEquals([], $array); @@ -50,7 +51,7 @@ public function testPluck() public function testPluckThrowsExceptionWithInvalidKey() { $array = []; - $this->implementation->call('pluck', ['not_here', &$array]); + $this->impl->call('pluck', ['not_here', &$array]); } public function testPluckArray() @@ -62,15 +63,15 @@ public function testPluckArray() ]; $expectedArray = $array; - $actualValues = $this->implementation->call('pluckArray', [$keys, &$array]); + $actualValues = $this->impl->call('pluckArray', [$keys, &$array]); - $this->assertEquals($expectedArray, $actualValues); - $this->assertEquals([], $array); + $this->assertEquals($expectedArray, $actualValues); + $this->assertEquals([], $array); } public function testIsAssocTrue() { - $actual = $this->implementation->call('isAssoc', [[ + $actual = $this->impl->call('isAssoc', [[ 'test' => 1, 'test' => 2 ]]); @@ -80,7 +81,7 @@ public function testIsAssocTrue() public function testIsAssocFalse() { - $actual = $this->implementation->call('isAssoc', [[1, 2, 3]]); + $actual = $this->impl->call('isAssoc', [[1, 2, 3]]); $this->assertFalse($actual); } @@ -96,7 +97,7 @@ public function testArrayFilterRemoveNull() 'array' => [], ]; - $res = $this->implementation->call('arrayFilterRemoveNull', [$input]); + $res = $this->impl->call('arrayFilterRemoveNull', [$input]); $this->assertArrayNotHasKey('null', $res); $this->assertArrayHasKey('false', $res); $this->assertArrayHasKey('zero', $res); @@ -105,13 +106,3 @@ public function testArrayFilterRemoveNull() $this->assertArrayHasKey('array', $res); } } - -class ArrayTraitStub -{ - use ArrayTrait; - - public function call($fn, array $args) - { - return call_user_func_array([$this, $fn], $args); - } -} diff --git a/Core/tests/Unit/Batch/BatchDaemonTraitTest.php b/Core/tests/Unit/Batch/BatchDaemonTraitTest.php index c983ed7c3c88..46b68914fccc 100644 --- a/Core/tests/Unit/Batch/BatchDaemonTraitTest.php +++ b/Core/tests/Unit/Batch/BatchDaemonTraitTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Core\Tests\Unit\Batch; use Google\Cloud\Core\Batch\BatchDaemonTrait; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; /** @@ -28,7 +29,7 @@ class BatchDaemonTraitTest extends TestCase { public function setUp() { - $this->impl = new MyBatchDaemonTraitClass(); + $this->impl = TestHelpers::impl(BatchDaemonTrait::class); } public function testIsDaemonRunning() @@ -37,9 +38,9 @@ public function testIsDaemonRunning() $orig = getenv('IS_BATCH_DAEMON_RUNNING'); try { putenv('IS_BATCH_DAEMON_RUNNING'); - $this->assertFalse($this->impl->isDaemonRunning()); + $this->assertFalse($this->impl->call('isDaemonRunning')); putenv('IS_BATCH_DAEMON_RUNNING=true'); - $this->assertTrue($this->impl->isDaemonRunning()); + $this->assertTrue($this->impl->call('isDaemonRunning')); } finally { if ($orig === false) { putenv('IS_BATCH_DAEMON_RUNNING'); @@ -49,15 +50,3 @@ public function testIsDaemonRunning() } } } - -class MyBatchDaemonTraitClass -{ - use BatchDaemonTrait { - isDaemonRunning as privateIsDaemonRunning; - } - - function isDaemonRunning() - { - return $this->privateIsDaemonRunning(); - } -} diff --git a/Core/tests/Unit/Batch/BatchRunnerTest.php b/Core/tests/Unit/Batch/BatchRunnerTest.php index 024c0fa97eca..e00ac9b8a305 100644 --- a/Core/tests/Unit/Batch/BatchRunnerTest.php +++ b/Core/tests/Unit/Batch/BatchRunnerTest.php @@ -52,7 +52,9 @@ public function testRegisterJobClosure() ); $result = $runner->registerJob( 'test', - function() {} + function () { + return; + } ); $this->assertTrue(false, 'It should throw InvalidArgumentException'); } diff --git a/Core/tests/Unit/Batch/BatchTraitTest.php b/Core/tests/Unit/Batch/BatchTraitTest.php index 2f36e8c5fe0c..677915f9bc7c 100644 --- a/Core/tests/Unit/Batch/BatchTraitTest.php +++ b/Core/tests/Unit/Batch/BatchTraitTest.php @@ -21,8 +21,9 @@ use Google\Cloud\Core\Batch\BatchRunner; use Google\Cloud\Core\Batch\BatchTrait; use Google\Cloud\Core\Batch\ProcessItemInterface; -use Prophecy\Argument; +use Google\Cloud\Core\Tests\Unit\Batch\Fixtures\BatchClass; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group core @@ -99,53 +100,3 @@ public function testSetCommonBatchPropertiesThrowsExceptionWithoutBatchMethod() $impl->setCommonBatchProperties(['identifier' => self::ID]); } } - -class BatchClass -{ - use BatchTrait { - flush as publicFlush; - send as publicSend; - setCommonBatchProperties as privateSetCommonBatchProperties; - } - - private $cb; - - public function __construct(array $options = []) - { - $options += [ - 'batchRunner' => null, - 'identifier' => BatchTraitTest::ID, - 'batchMethod' => BatchTraitTest::BATCH_METHOD, - 'debugOutput' => false, - 'debugOutputResource' => null, - 'cb' => null - ]; - - $this->batchRunner = $options['batchRunner']; - $this->identifier = $options['identifier']; - $this->batchMethod = $options['batchMethod']; - $this->debugOutput = $options['debugOutput']; - $this->debugOutputResource = $options['debugOutputResource']; - $this->cb = $options['cb']; - } - - function flush() - { - return $this->publicFlush(); - } - - function send(array $items) - { - return $this->publicSend($items); - } - - function setCommonBatchProperties(array $options) - { - $this->privateSetCommonBatchProperties($options); - } - - function getCallback() - { - return $this->cb; - } -} diff --git a/Core/tests/Unit/Batch/Fixtures/BatchClass.php b/Core/tests/Unit/Batch/Fixtures/BatchClass.php new file mode 100644 index 000000000000..8218c5c64acc --- /dev/null +++ b/Core/tests/Unit/Batch/Fixtures/BatchClass.php @@ -0,0 +1,71 @@ + null, + 'identifier' => BatchTraitTest::ID, + 'batchMethod' => BatchTraitTest::BATCH_METHOD, + 'debugOutput' => false, + 'debugOutputResource' => null, + 'cb' => null + ]; + + $this->batchRunner = $options['batchRunner']; + $this->identifier = $options['identifier']; + $this->batchMethod = $options['batchMethod']; + $this->debugOutput = $options['debugOutput']; + $this->debugOutputResource = $options['debugOutputResource']; + $this->cb = $options['cb']; + } + + public function flush() + { + return $this->publicFlush(); + } + + public function send(array $items) + { + return $this->publicSend($items); + } + + public function setCommonBatchProperties(array $options) + { + $this->privateSetCommonBatchProperties($options); + } + + public function getCallback() + { + return $this->cb; + } +} diff --git a/Core/tests/Unit/Batch/Fixtures/TestSerializableObjectWithClosure.php b/Core/tests/Unit/Batch/Fixtures/TestSerializableObjectWithClosure.php new file mode 100644 index 000000000000..b668fb2fbbc9 --- /dev/null +++ b/Core/tests/Unit/Batch/Fixtures/TestSerializableObjectWithClosure.php @@ -0,0 +1,34 @@ +closure = function () { + return; + }; + } + + public function callback() + { + } +} diff --git a/Core/tests/Unit/Batch/HandleFailureTraitTest.php b/Core/tests/Unit/Batch/HandleFailureTraitTest.php index 17e23fc47036..8e4bed05830f 100644 --- a/Core/tests/Unit/Batch/HandleFailureTraitTest.php +++ b/Core/tests/Unit/Batch/HandleFailureTraitTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Core\Tests\Unit\Batch; use Google\Cloud\Core\Batch\HandleFailureTrait; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; /** @@ -42,7 +43,7 @@ public function delTree($dir) public function setUp() { - $this->impl = new HandleFailureClass(); + $this->impl = TestHelpers::impl(HandleFailureTrait::class); $this->testDir = sprintf( '%s/google-cloud-unit-test-%d', sys_get_temp_dir(), @@ -63,45 +64,44 @@ public function tearDown() */ public function testInitFailureFileThrowsException() { - putenv( - 'GOOGLE_CLOUD_BATCH_DAEMON_FAILURE_DIR=/tmp/non-existent/subdir'); - $this->impl->initFailureFile(); + putenv('GOOGLE_CLOUD_BATCH_DAEMON_FAILURE_DIR=/tmp/non-existent/subdir'); + $this->impl->call('initFailureFile'); } public function testInitFailureFile() { - $this->impl->initFailureFile(); + $this->impl->call('initFailureFile'); $this->assertEquals( sprintf('%s/batch-daemon-failure', sys_get_temp_dir()), - $this->impl->getBaseDir() + $this->impl->___getProperty('baseDir') ); $this->assertEquals( sprintf( '%s/failed-items-%d', - $this->impl->getBaseDir(), + $this->impl->___getProperty('baseDir'), getmypid() ), - $this->impl->getFailureFile() + $this->impl->___getProperty('failureFile') ); putenv('GOOGLE_CLOUD_BATCH_DAEMON_FAILURE_DIR=/tmp'); - $this->impl->initFailureFile(); - $this->assertEquals('/tmp', $this->impl->getBaseDir()); + $this->impl->call('initFailureFile'); + $this->assertEquals('/tmp', $this->impl->___getProperty('baseDir')); $this->assertEquals( sprintf( '%s/failed-items-%d', - $this->impl->getBaseDir(), + $this->impl->___getProperty('baseDir'), getmypid() ), - $this->impl->getFailureFile() + $this->impl->___getProperty('failureFile') ); } public function testHandleFailure() { putenv('GOOGLE_CLOUD_BATCH_DAEMON_FAILURE_DIR=' . $this->testDir); - $this->impl->initFailureFile(); + $this->impl->call('initFailureFile'); $this->impl->handleFailure(1, array('apple', 'orange')); - $files = $this->impl->getFailedFiles(); + $files = $this->impl->call('getFailedFiles'); $this->assertCount(1, $files); $unserialized = unserialize(file_get_contents($files[0])); $this->assertEquals( @@ -110,31 +110,3 @@ public function testHandleFailure() ); } } - -class HandleFailureClass -{ - use HandleFailureTrait { - initFailureFile as privateInitFailureFile; - getFailedFiles as privateGetFailedFiles; - } - - public function getFailureFile() - { - return $this->failureFile; - } - - public function getBaseDir() - { - return $this->baseDir; - } - - public function initFailureFile() - { - return $this->privateInitFailureFile(); - } - - public function getFailedFiles() - { - return $this->privateGetFailedFiles(); - } -} diff --git a/Core/tests/Unit/Batch/InMemoryConfigStorageTest.php b/Core/tests/Unit/Batch/InMemoryConfigStorageTest.php index af1f86fc0d6f..983c476269e3 100644 --- a/Core/tests/Unit/Batch/InMemoryConfigStorageTest.php +++ b/Core/tests/Unit/Batch/InMemoryConfigStorageTest.php @@ -18,8 +18,8 @@ namespace Google\Cloud\Core\Tests\Unit\Batch; use Google\Cloud\Core\Batch\BatchJob; -use Google\Cloud\Core\Batch\JobConfig; use Google\Cloud\Core\Batch\InMemoryConfigStorage; +use Google\Cloud\Core\Batch\JobConfig; use PHPUnit\Framework\TestCase; /** @@ -39,8 +39,7 @@ public function testSingletonEquality() public function testConstructorIsForbidden() { - $reflection = new \ReflectionClass( - '\Google\Cloud\Core\Batch\InMemoryConfigStorage'); + $reflection = new \ReflectionClass(InMemoryConfigStorage::class); $constructor = $reflection->getConstructor(); $this->assertFalse($constructor->isPublic()); } diff --git a/Core/tests/Unit/Batch/JobTraitTest.php b/Core/tests/Unit/Batch/JobTraitTest.php index c13fe1743877..94d99f19bc04 100644 --- a/Core/tests/Unit/Batch/JobTraitTest.php +++ b/Core/tests/Unit/Batch/JobTraitTest.php @@ -39,6 +39,7 @@ public function testDefaults() } } +//@codingStandardsIgnoreStart class TestJob implements JobInterface { use JobTrait; @@ -48,3 +49,4 @@ public function run() // Do nothing } } +//@codingStandardsIgnoreEnd diff --git a/Core/tests/Unit/Batch/SimpleJobTraitTest.php b/Core/tests/Unit/Batch/SimpleJobTraitTest.php index c0e8054862dc..37ce47301043 100644 --- a/Core/tests/Unit/Batch/SimpleJobTraitTest.php +++ b/Core/tests/Unit/Batch/SimpleJobTraitTest.php @@ -61,6 +61,7 @@ public function testRegistersConfig() } } +//@codingStandardsIgnoreStart class SimpleClass { use SimpleJobTrait { @@ -84,3 +85,4 @@ public function hasRun() return $this->hasRun; } } +//@codingStandardsIgnoreEnd diff --git a/Core/tests/Unit/Batch/SysvConfigStorageTest.php b/Core/tests/Unit/Batch/SysvConfigStorageTest.php index ec140c28595a..3cfb4822541b 100644 --- a/Core/tests/Unit/Batch/SysvConfigStorageTest.php +++ b/Core/tests/Unit/Batch/SysvConfigStorageTest.php @@ -21,6 +21,7 @@ use Google\Cloud\Core\Batch\JobConfig; use Google\Cloud\Core\Batch\SysvConfigStorage; use Google\Cloud\Core\SysvTrait; +use Google\Cloud\Core\Tests\Unit\Batch\Fixtures\TestSerializableObjectWithClosure; use PHPUnit\Framework\TestCase; /** @@ -43,7 +44,8 @@ public function setUp() { if (! $this->isSysvIPCLOaded()) { $this->markTestSkipped( - 'Skipping because SystemV IPC extensions are not loaded'); + 'Skipping because SystemV IPC extensions are not loaded' + ); } $this->storage = new SysvConfigStorage(); $this->originalShmSize = getenv('GOOGLE_CLOUD_BATCH_SHM_SIZE'); @@ -139,17 +141,3 @@ public function testEnvVarCustomization() $this->assertEquals('B', $p->getValue($storage)); } } - -class TestSerializableObjectWithClosure -{ - public $closure; - - public function __construct() - { - $this->closure = function () {}; - } - - public function callback() - { - } -} diff --git a/Core/tests/Unit/Batch/SysvProcessorTest.php b/Core/tests/Unit/Batch/SysvProcessorTest.php index aa8eaccbf058..7e6bd6e49973 100644 --- a/Core/tests/Unit/Batch/SysvProcessorTest.php +++ b/Core/tests/Unit/Batch/SysvProcessorTest.php @@ -38,7 +38,8 @@ public function setUp() putenv('GOOGLE_CLOUD_SYSV_ID=U'); if (! $this->isSysvIPCLOaded()) { $this->markTestSkipped( - 'Skipping because SystemV IPC extensions are not loaded'); + 'Skipping because SystemV IPC extensions are not loaded' + ); } $this->processor = new SysvProcessor(); } @@ -72,7 +73,8 @@ public function testSubmit($item, $exptectedType) } else { $this->assertEquals( $item, - unserialize(file_get_contents($message))); + unserialize(file_get_contents($message)) + ); @unlink($message); } } diff --git a/Core/tests/Unit/CallTraitTest.php b/Core/tests/Unit/CallTraitTest.php index 45ff7e9af6d1..4d5ab958949c 100644 --- a/Core/tests/Unit/CallTraitTest.php +++ b/Core/tests/Unit/CallTraitTest.php @@ -43,6 +43,7 @@ public function testErr() } } +//@codingStandardsIgnoreStart class CallTraitStub { use CallTrait; @@ -57,3 +58,4 @@ public function info() return $this->info; } } +//@codingStandardsIgnoreEnd diff --git a/Core/tests/Unit/ClientTraitTest.php b/Core/tests/Unit/ClientTraitTest.php index 7fdcccc5d856..0bf7a42a076d 100644 --- a/Core/tests/Unit/ClientTraitTest.php +++ b/Core/tests/Unit/ClientTraitTest.php @@ -19,6 +19,7 @@ use Google\Cloud\Core\ClientTrait; use Google\Cloud\Core\Compute\Metadata; +use Google\Cloud\Core\Testing\TestHelpers; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; @@ -33,9 +34,9 @@ class ClientTraitTest extends TestCase public function setUp() { - $this->impl = \Google\Cloud\Core\Testing\TestHelpers::impl(ClientTrait::class); + $this->impl = TestHelpers::impl(ClientTrait::class); - $this->dependency = \Google\Cloud\Core\Testing\TestHelpers::impl(ClientTraitStubGrpcDependencyChecks::class, [ + $this->dependency = TestHelpers::impl(ClientTraitStubGrpcDependencyChecks::class, [ 'dependencyStatus' ]); } @@ -266,7 +267,7 @@ public function testDetectProjectIdOnGce() $m = $this->prophesize(Metadata::class); $m->getProjectId()->willReturn($projectId)->shouldBeCalled(); - $trait = \Google\Cloud\Core\Testing\TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); + $trait = TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); $trait->___setProperty('metadata', $m); $res = $trait->call('detectProjectId', [[]]); @@ -281,7 +282,7 @@ public function testDetectNumericProjectIdOnGce() $m = $this->prophesize(Metadata::class); $m->getNumericProjectId()->willReturn($projectId)->shouldBeCalled(); - $trait = \Google\Cloud\Core\Testing\TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); + $trait = TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); $trait->___setProperty('metadata', $m); $res = $trait->call('detectProjectId', [['preferNumericProjectId' => true]]); @@ -299,7 +300,7 @@ public function testDetectProjectIdOnGceButOhNoThereStillIsntAProjectId() $m = $this->prophesize(Metadata::class); $m->getProjectId()->willReturn($projectId)->shouldBeCalled(); - $trait = \Google\Cloud\Core\Testing\TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); + $trait = TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); $trait->___setProperty('metadata', $m); $res = $trait->call('detectProjectId', [[ @@ -317,7 +318,7 @@ public function testDetectProjectIdEmulator() $m = $this->prophesize(Metadata::class); $m->getProjectId()->willReturn(false)->shouldBeCalled(); - $trait = \Google\Cloud\Core\Testing\TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); + $trait = TestHelpers::impl(ClientTraitStubOnGce::class, ['metadata']); $trait->___setProperty('metadata', $m); $res = $trait->call('detectProjectId', [[ @@ -332,6 +333,7 @@ public function testDetectProjectIdEmulator() } } +//@codingStandardsIgnoreStart trait ClientTraitStubOnGce { use ClientTrait; @@ -356,3 +358,4 @@ protected function isGrpcLoaded() return $this->dependencyStatus; } } +//@codingStandardsIgnoreEnd diff --git a/Core/tests/Unit/ConcurrencyControlTraitTest.php b/Core/tests/Unit/ConcurrencyControlTraitTest.php index 03e98e57784c..dfa699c690ad 100644 --- a/Core/tests/Unit/ConcurrencyControlTraitTest.php +++ b/Core/tests/Unit/ConcurrencyControlTraitTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Core\Tests\Unit; use Google\Cloud\Core\ConcurrencyControlTrait; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; /** @@ -31,7 +32,7 @@ class ConcurrencyControlTraitTest extends TestCase public function setUp() { - $this->trait = \Google\Cloud\Core\Testing\TestHelpers::impl(ConcurrencyControlTrait::class); + $this->trait = TestHelpers::impl(ConcurrencyControlTrait::class); } public function testApplyEtagHeader() diff --git a/Core/tests/Unit/EmulatorTraitTest.php b/Core/tests/Unit/EmulatorTraitTest.php index f1c41223631f..c2511809c92f 100644 --- a/Core/tests/Unit/EmulatorTraitTest.php +++ b/Core/tests/Unit/EmulatorTraitTest.php @@ -18,8 +18,9 @@ namespace Google\Cloud\Core\Tests\Unit; use Google\Cloud\Core\EmulatorTrait; -use Prophecy\Argument; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group core @@ -30,7 +31,7 @@ class EmulatorTraitTest extends TestCase public function setUp() { - $this->impl = \Google\Cloud\Core\Testing\TestHelpers::impl(EmulatorTrait::class); + $this->impl = TestHelpers::impl(EmulatorTrait::class); } public function testEmulatorBaseUri() diff --git a/Core/tests/Unit/ExponentialBackoffTest.php b/Core/tests/Unit/ExponentialBackoffTest.php index 05dd5ef71d46..7d3aad999eda 100644 --- a/Core/tests/Unit/ExponentialBackoffTest.php +++ b/Core/tests/Unit/ExponentialBackoffTest.php @@ -30,7 +30,7 @@ class ExponentialBackoffTest extends TestCase public function setUp() { - $this->delayFunction = function() { + $this->delayFunction = function () { return; }; } @@ -79,7 +79,7 @@ public function testThrowsExceptionWhenRetryFunctionReturnsFalse() { $actualAttempts = 0; $hasTriggeredException = false; - $retryFunction = function(\Exception $ex) { + $retryFunction = function (\Exception $ex) { return false; }; $backoff = new ExponentialBackoff(null, $retryFunction); diff --git a/Core/tests/Unit/Fixtures.php b/Core/tests/Unit/Fixtures.php index 960ef4e781f5..a11b8c4fe007 100644 --- a/Core/tests/Unit/Fixtures.php +++ b/Core/tests/Unit/Fixtures.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Core\Tests\Unit; +//@codingStandardsIgnoreStart class Fixtures { public static function JSON_KEY_FIXTURE() @@ -29,3 +30,4 @@ public static function SERVICE_FIXTURE() return __DIR__ . '/fixtures/service-fixture.json'; } } +//@codingStandardsIgnoreEnd diff --git a/Core/tests/Unit/GrpcRequestWrapperTest.php b/Core/tests/Unit/GrpcRequestWrapperTest.php index 5726700fab29..7d3583e2522b 100644 --- a/Core/tests/Unit/GrpcRequestWrapperTest.php +++ b/Core/tests/Unit/GrpcRequestWrapperTest.php @@ -67,7 +67,11 @@ public function testSuccessfullySendsRequest($response, $expectedMessage, $seria $actualResponse = $requestWrapper->send( function ($test, $options) use ($response, $requestOptions) { - $this->assertEquals($requestOptions['requestTimeout'] * 1000, $options['retrySettings']['noRetriesRpcTimeoutMillis']); + $this->assertEquals( + $requestOptions['requestTimeout'] * 1000, + $options['retrySettings']['noRetriesRpcTimeoutMillis'] + ); + return $response; }, ['test', []], @@ -106,7 +110,8 @@ public function testThrowsExceptionWhenRequestFails() $requestWrapper = new GrpcRequestWrapper(); $requestWrapper->send(function () { - throw new ApiException('message', + throw new ApiException( + 'message', \Google\Rpc\Code::NOT_FOUND, \Google\ApiCore\ApiStatus::NOT_FOUND ); diff --git a/Core/tests/Unit/GrpcTraitTest.php b/Core/tests/Unit/GrpcTraitTest.php index b0cd4253204d..862b45370ad7 100644 --- a/Core/tests/Unit/GrpcTraitTest.php +++ b/Core/tests/Unit/GrpcTraitTest.php @@ -25,9 +25,10 @@ use Google\Cloud\Core\GrpcRequestWrapper; use Google\Cloud\Core\GrpcTrait; use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use google\protobuf; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group core @@ -43,7 +44,7 @@ public function setUp() { $this->checkAndSkipGrpcTests(); - $this->implementation = \Google\Cloud\Core\Testing\TestHelpers::impl(GrpcTrait::class); + $this->implementation = TestHelpers::impl(GrpcTrait::class); $this->requestWrapper = $this->prophesize(GrpcRequestWrapper::class); } @@ -110,7 +111,7 @@ public function testSendsRequestNotFoundWhitelisted() $msg = null; try { - $this->implementation->send(function () {}, [['grpcOptions' => $grpcOptions]], true); + $this->implementation->send($this->noop(), [['grpcOptions' => $grpcOptions]], true); } catch (NotFoundException $e) { $msg = $e->getMessage(); } @@ -133,7 +134,7 @@ public function testSendsRequestNotFoundNotWhitelisted() $msg = null; try { - $this->implementation->send(function () {}, [['grpcOptions' => $grpcOptions]], false); + $this->implementation->send($this->noop(), [['grpcOptions' => $grpcOptions]], false); } catch (NotFoundException $e) { $msg = $e->getMessage(); } @@ -152,7 +153,9 @@ public function testGetsGaxConfig() 'libName' => 'gccl', 'libVersion' => $version, 'transport' => 'grpc', - 'credentials' => new CredentialsWrapper($fetcher, function () { return true; }) + 'credentials' => new CredentialsWrapper($fetcher, function () { + return true; + }) ]; $this->assertEquals( @@ -176,7 +179,10 @@ public function testFormatsTimestamp() 'nanos' => '1' ]; - $this->assertEquals('2016-08-15T06:35:09.000000001Z', $this->implementation->call('formatTimestampFromApi', [$timestamp])); + $this->assertEquals( + '2016-08-15T06:35:09.000000001Z', + $this->implementation->call('formatTimestampFromApi', [$timestamp]) + ); } public function testFormatsStruct() @@ -359,4 +365,11 @@ public function unpackValueProvider() ] ]; } + + private function noop() + { + return function () { + return; + }; + } } diff --git a/Core/tests/Unit/Iterator/PageIteratorTest.php b/Core/tests/Unit/Iterator/PageIteratorTest.php index 21e357445f76..887268febca1 100644 --- a/Core/tests/Unit/Iterator/PageIteratorTest.php +++ b/Core/tests/Unit/Iterator/PageIteratorTest.php @@ -151,10 +151,6 @@ public function theCall(array $options) ]; } - if (isset($options['firstPage'])) { - - } - if (isset($options['multiPage'])) { return [ $options['itemsKey'] => self::$page1, diff --git a/Core/tests/Unit/JsonTraitTest.php b/Core/tests/Unit/JsonTraitTest.php index 1b431e11bde2..04237262d76a 100644 --- a/Core/tests/Unit/JsonTraitTest.php +++ b/Core/tests/Unit/JsonTraitTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Core\Tests\Unit; use Google\Cloud\Core\JsonTrait; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; /** @@ -29,7 +30,7 @@ class JsonTraitTest extends TestCase public function setUp() { - $this->implementation = \Google\Cloud\Core\Testing\TestHelpers::impl(JsonTrait::class); + $this->implementation = TestHelpers::impl(JsonTrait::class); } public function testJsonEncode() diff --git a/Core/tests/Unit/Lock/CommonLockTrait.php b/Core/tests/Unit/Lock/CommonLockTrait.php index a516693a4fff..dfdf66ca2306 100644 --- a/Core/tests/Unit/Lock/CommonLockTrait.php +++ b/Core/tests/Unit/Lock/CommonLockTrait.php @@ -67,4 +67,3 @@ public function testSynchronizeLockThrowsException() }); } } - diff --git a/Core/tests/Unit/Lock/FlockLockTest.php b/Core/tests/Unit/Lock/FlockLockTest.php index e9f9d4537e65..3261ddd28535 100644 --- a/Core/tests/Unit/Lock/FlockLockTest.php +++ b/Core/tests/Unit/Lock/FlockLockTest.php @@ -76,4 +76,3 @@ public function testThrowsExceptionWhenFopenFails() $this->lock->acquire(); } } - diff --git a/Core/tests/Unit/Lock/SemaphoreLockTest.php b/Core/tests/Unit/Lock/SemaphoreLockTest.php index 3fac6b643085..8f34ceda6cd5 100644 --- a/Core/tests/Unit/Lock/SemaphoreLockTest.php +++ b/Core/tests/Unit/Lock/SemaphoreLockTest.php @@ -84,4 +84,3 @@ public function testThrowsExceptionWhenSemGetFails() $this->lock->acquire(); } } - diff --git a/Core/tests/Unit/Logger/AppEngineFlexHandlerTest.php b/Core/tests/Unit/Logger/AppEngineFlexHandlerTest.php index 3476546685ae..27f62651f74c 100644 --- a/Core/tests/Unit/Logger/AppEngineFlexHandlerTest.php +++ b/Core/tests/Unit/Logger/AppEngineFlexHandlerTest.php @@ -34,9 +34,7 @@ public function setUp() { $dir = sys_get_temp_dir(); $this->stream = tmpfile(); - $handler = new AppEngineFlexHandler( - Logger::DEBUG, true, 0640, false, $this->stream - ); + $handler = new AppEngineFlexHandler(Logger::DEBUG, true, 0640, false, $this->stream); $this->log = new Logger('gcloud-test'); $this->log->pushHandler($handler); } diff --git a/Core/tests/Unit/Report/EmptyMetadataProviderTest.php b/Core/tests/Unit/Report/EmptyMetadataProviderTest.php index 0f22f7740231..903ea0a36570 100644 --- a/Core/tests/Unit/Report/EmptyMetadataProviderTest.php +++ b/Core/tests/Unit/Report/EmptyMetadataProviderTest.php @@ -60,4 +60,3 @@ public function testLabels() $this->assertEquals([], $this->metadataProvider->labels()); } } - diff --git a/Core/tests/Unit/Report/SimpleMetadataProviderTest.php b/Core/tests/Unit/Report/SimpleMetadataProviderTest.php index 224c0ac15f3a..c9325b77c1b2 100644 --- a/Core/tests/Unit/Report/SimpleMetadataProviderTest.php +++ b/Core/tests/Unit/Report/SimpleMetadataProviderTest.php @@ -88,4 +88,3 @@ public function testLabels() ); } } - diff --git a/Core/tests/Unit/RequestBuilderTest.php b/Core/tests/Unit/RequestBuilderTest.php index 162bdf167b1d..a3252059eff7 100644 --- a/Core/tests/Unit/RequestBuilderTest.php +++ b/Core/tests/Unit/RequestBuilderTest.php @@ -87,7 +87,11 @@ public function testBuildsNestedRequestWithStringSplitting() 'referenceProp' => 'reference' ]; - $request = $builder->build('myOtherResource.resources.evenMoreNestedThing', 'evenMoreNestedResource', $parameters); + $request = $builder->build( + 'myOtherResource.resources.evenMoreNestedThing', + 'evenMoreNestedResource', + $parameters + ); $uri = $request->getUri(); $this->assertEquals('/path', $uri->getPath()); diff --git a/Core/tests/Unit/RequestWrapperTest.php b/Core/tests/Unit/RequestWrapperTest.php index 1ba91099968a..eaa60d9476fe 100644 --- a/Core/tests/Unit/RequestWrapperTest.php +++ b/Core/tests/Unit/RequestWrapperTest.php @@ -396,6 +396,7 @@ public function testDefaultToAnonymousCredentialsWhenNoOthersExist() } } +//@codingStandardsIgnoreStart class RequestWrapperStub extends RequestWrapper { protected function getADC() @@ -403,3 +404,4 @@ protected function getADC() throw new \DomainException('Not found'); } } +//@codingStandardsIgnoreEnd diff --git a/Core/tests/Unit/RetryDeciderTraitTest.php b/Core/tests/Unit/RetryDeciderTraitTest.php index 566bfbc8c9c5..6a86939cfee1 100644 --- a/Core/tests/Unit/RetryDeciderTraitTest.php +++ b/Core/tests/Unit/RetryDeciderTraitTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Core\Tests\Unit; use Google\Cloud\Core\RetryDeciderTrait; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; /** @@ -25,11 +26,11 @@ */ class RetryDeciderTraitTest extends TestCase { - private $implementation; + private $impl; public function setUp() { - $this->implementation = new RetryDeciderTraitStub(); + $this->impl = TestHelpers::impl(RetryDeciderTrait::class); } /** @@ -37,9 +38,9 @@ public function setUp() */ public function testDisableRetry($exception) { - $this->implementation->call('setHttpRetryCodes', [[]]); - $this->implementation->call('setHttpRetryMessages', [[]]); - $retryFunction = $this->implementation->call('getRetryFunction'); + $this->impl->call('setHttpRetryCodes', [[]]); + $this->impl->call('setHttpRetryMessages', [[]]); + $retryFunction = $this->impl->call('getRetryFunction'); $this->assertFalse($retryFunction($exception)); } @@ -49,7 +50,7 @@ public function testDisableRetry($exception) */ public function testShouldRetry($exception, $shouldRetryMessage, $expected) { - $retryFunction = $this->implementation->call('getRetryFunction', [$shouldRetryMessage]); + $retryFunction = $this->impl->call('getRetryFunction', [$shouldRetryMessage]); $this->assertEquals($expected, $retryFunction($exception)); } @@ -72,13 +73,3 @@ public function retryProvider() ]; } } - -class RetryDeciderTraitStub -{ - use RetryDeciderTrait; - - public function call($fn, array $args = []) - { - return call_user_func_array([$this, $fn], $args); - } -} diff --git a/Core/tests/Unit/ServiceBuilderTest.php b/Core/tests/Unit/ServiceBuilderTest.php index c79a7b5da4b8..32399a82c661 100644 --- a/Core/tests/Unit/ServiceBuilderTest.php +++ b/Core/tests/Unit/ServiceBuilderTest.php @@ -59,7 +59,7 @@ public function testBuildsClients($serviceName, $expectedClient, array $args = [ $config = [ 'projectId' => 'myProject', 'scopes' => ['somescope'], - 'httpHandler' => function() { + 'httpHandler' => function () { return; } ] + $args; @@ -122,7 +122,8 @@ public function testKeyfilePathAuthPassthrough( * @dataProvider serviceProvider */ public function testKeyfileAuthPassthrough( - $serviceName, $expectedClient, + $serviceName, + $expectedClient, array $args = [], callable $beforeCallable = null ) { diff --git a/Core/tests/Unit/SysvTraitTest.php b/Core/tests/Unit/SysvTraitTest.php index 338b0c94fe61..5770450af118 100644 --- a/Core/tests/Unit/SysvTraitTest.php +++ b/Core/tests/Unit/SysvTraitTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Core\Tests\Unit; use Google\Cloud\Core\SysvTrait; +use Google\Cloud\Core\Testing\TestHelpers; use PHPUnit\Framework\TestCase; /** @@ -27,18 +28,18 @@ class SysvTraitTest extends TestCase { public function setUp() { - $this->impl = new MySysvClass(); + $this->impl = TestHelpers::impl(SysvTrait::class); } public function testGetSysvKey() { - if (!$this->impl->isSysvIPCLoaded()) { + if (!$this->impl->call('isSysvIPCLoaded')) { $this->markTestSkipped( 'SysV IPC extensions are not available, skipped' ); } - $key1 = $this->impl->getSysvKey(1); - $key2 = $this->impl->getSysvKey(2); + $key1 = $this->impl->call('getSysvKey', [1]); + $key2 = $this->impl->call('getSysvKey', [2]); $this->assertEquals(1, $key2 - $key1); } @@ -47,24 +48,6 @@ public function testIsSysvIPCLoaded() $expected = extension_loaded('sysvmsg') && extension_loaded('sysvsem') && extension_loaded('sysvshm'); - $this->assertEquals($expected, $this->impl->isSysvIPCLoaded()); - } -} - -class MySysvClass -{ - use SysvTrait { - isSysvIPCLoaded as privateIsSysvIPCLoaded; - getSysvKey as privateGetSysvKey; - } - - function isSysvIPCLoaded() - { - return $this->privateIsSysvIPCLoaded(); - } - - function getSysvKey($id) - { - return $this->privateGetSysvKey($id); + $this->assertEquals($expected, $this->impl->call('isSysvIPCLoaded')); } } diff --git a/Core/tests/Unit/Upload/ResumableUploaderTest.php b/Core/tests/Unit/Upload/ResumableUploaderTest.php index d87799806b8c..32414272ab6e 100644 --- a/Core/tests/Unit/Upload/ResumableUploaderTest.php +++ b/Core/tests/Unit/Upload/ResumableUploaderTest.php @@ -68,7 +68,7 @@ public function testUploadsDataWithCallback() $response = new Response(200, ['Location' => 'theResumeUri'], $this->successBody); $called = false; - $callback = function() use (&$called) { + $callback = function () use (&$called) { $called = true; }; diff --git a/Core/tests/Unit/Upload/SignedUrlUploaderTest.php b/Core/tests/Unit/Upload/SignedUrlUploaderTest.php index 02c0f971e629..af42773a2d92 100644 --- a/Core/tests/Unit/Upload/SignedUrlUploaderTest.php +++ b/Core/tests/Unit/Upload/SignedUrlUploaderTest.php @@ -52,10 +52,22 @@ public function testGetResumeUri() $this->requestWrapper->send( Argument::that(function ($arg) { - if (!($arg instanceof RequestInterface)) return false; - if ($arg->getHeaderLine('Content-Type') !== 'application/octet-stream') return false; - if ($arg->getHeaderLine('Content-Length') != 0) return false; - if ($arg->getHeaderLine('x-goog-resumable') !== 'start') return false; + if (!($arg instanceof RequestInterface)) { + return false; + } + + if ($arg->getHeaderLine('Content-Type') !== 'application/octet-stream') { + return false; + } + + if ($arg->getHeaderLine('Content-Length') != 0) { + return false; + } + + if ($arg->getHeaderLine('x-goog-resumable') !== 'start') { + return false; + } + return true; }), Argument::type('array') diff --git a/Core/tests/Unit/Upload/StreamableUploaderTest.php b/Core/tests/Unit/Upload/StreamableUploaderTest.php index b78381f7f176..a8019195527d 100644 --- a/Core/tests/Unit/Upload/StreamableUploaderTest.php +++ b/Core/tests/Unit/Upload/StreamableUploaderTest.php @@ -47,7 +47,7 @@ public function testStreamingWrites() { $resumeResponse = new Response(200, ['Location' => 'http://some-resume-uri.example.com'], $this->successBody); $this->requestWrapper->send( - Argument::that(function($request){ + Argument::that(function ($request) { return (string) $request->getUri() == 'http://www.example.com'; }), Argument::type('array') @@ -55,7 +55,7 @@ public function testStreamingWrites() $uploadResponse = new Response(200, [], $this->successBody); $upload = $this->requestWrapper->send( - Argument::that(function($request){ + Argument::that(function ($request) { return (string) $request->getUri() == 'http://some-resume-uri.example.com'; }), Argument::type('array') @@ -156,7 +156,7 @@ public function testLastChunkSendsCorrectHeaders() )->willReturn($resumeUriResponse)->shouldBeCalled(); $this->requestWrapper->send( - Argument::that(function($request) { + Argument::that(function ($request) { return $request->getHeaderLine('Content-Length') == '10'; }), Argument::type('array') diff --git a/Core/tests/Unit/ValidateTraitTest.php b/Core/tests/Unit/ValidateTraitTest.php index 828d73161c61..57dd694c8e05 100644 --- a/Core/tests/Unit/ValidateTraitTest.php +++ b/Core/tests/Unit/ValidateTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Core\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\ValidateTrait; use PHPUnit\Framework\TestCase; @@ -29,7 +30,7 @@ class ValidateTraitTest extends TestCase public function setUp() { - $this->stub = new ValidateTraitStub; + $this->stub = TestHelpers::impl(ValidateTrait::class); } public function testValidateBatch() @@ -40,7 +41,7 @@ public function testValidateBatch() (object)[], ]; - $this->stub->v($input, \stdClass::class); + $this->stub->call('validateBatch', [$input, \stdClass::class]); } /** @@ -55,7 +56,7 @@ public function testValidateBatchInvalidInput() $this->stub ]; - $this->stub->v($input, \stdClass::class); + $this->stub->call('validateBatch', [$input, \stdClass::class]); } public function testAdditionalCheckCalled() @@ -67,20 +68,14 @@ public function testAdditionalCheckCalled() (object)[], ]; - $this->stub->v($input, \stdClass::class, function ($input) use (&$called) { - $called++; - }); + $this->stub->call('validateBatch', [ + $input, + \stdClass::class, + function ($input) use (&$called) { + $called++; + } + ]); $this->assertCount($called, $input); } } - -class ValidateTraitStub -{ - use ValidateTrait; - - public function v(array $input, $type, callable $check = null) - { - return $this->validateBatch($input, $type, $check); - } -} diff --git a/Core/tests/Unit/WhitelistTraitTest.php b/Core/tests/Unit/WhitelistTraitTest.php index 316c1f29b8bc..0eebd01e7b2b 100644 --- a/Core/tests/Unit/WhitelistTraitTest.php +++ b/Core/tests/Unit/WhitelistTraitTest.php @@ -19,6 +19,7 @@ use Google\Cloud\Core\Exception\NotFoundException; use Google\Cloud\Core\Exception\ServiceException; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\WhitelistTrait; use PHPUnit\Framework\TestCase; @@ -31,7 +32,7 @@ class WhitelistTraitTest extends TestCase public function setUp() { - $this->trait = new WhitelistTraitStub; + $this->trait = TestHelpers::impl(WhitelistTrait::class); } public function testModifyWhitelistedError() @@ -47,13 +48,3 @@ public function testModifyWhitelistedError() ); } } - -class WhitelistTraitStub -{ - use WhitelistTrait; - - public function call($method, array $args) - { - return call_user_func_array([$this, $method], $args); - } -} diff --git a/Datastore/tests/Snippet/DatastoreClientTest.php b/Datastore/tests/Snippet/DatastoreClientTest.php index 3d71785e5d0f..7e3d36b75320 100644 --- a/Datastore/tests/Snippet/DatastoreClientTest.php +++ b/Datastore/tests/Snippet/DatastoreClientTest.php @@ -154,7 +154,10 @@ public function testKeysWithAncestors() $this->assertEquals(['kind' => 'Person'], $res->returnVal()[0]->keyObject()['path'][2]); $this->assertEquals(['kind' => 'Person', 'name' => 'Dad Mike'], $res->returnVal()[0]->keyObject()['path'][1]); - $this->assertEquals(['kind' => 'Person', 'name' => 'Grandpa Joe'], $res->returnVal()[0]->keyObject()['path'][0]); + $this->assertEquals( + ['kind' => 'Person', 'name' => 'Grandpa Joe'], + $res->returnVal()[0]->keyObject()['path'][0] + ); } public function testEntity() @@ -710,7 +713,8 @@ private function validateTransactionOptions($type, array $options = []) if (!empty((array) $options)) { return $options === $args['transactionOptions'][$type]; } else { - return is_object($args['transactionOptions'][$type]) && empty((array) $args['transactionOptions'][$type]); + return is_object($args['transactionOptions'][$type]) + && empty((array) $args['transactionOptions'][$type]); } return true; diff --git a/Datastore/tests/Snippet/KeyTest.php b/Datastore/tests/Snippet/KeyTest.php index 215e04437c18..c84c138562bb 100644 --- a/Datastore/tests/Snippet/KeyTest.php +++ b/Datastore/tests/Snippet/KeyTest.php @@ -48,7 +48,7 @@ public function testClassComplexPath() $ds = $this->prophesize(DatastoreClient::class); $ds->key(Argument::any(), Argument::any()) - ->will(function($args) { + ->will(function ($args) { return new Key('my-awesome-project', [ 'path' => [ ['kind' => $args[0], 'name' => $args[1]] @@ -69,7 +69,7 @@ public function testClassErrorOnAppend() { $ds = $this->prophesize(DatastoreClient::class); $ds->key(Argument::any(), Argument::any()) - ->will(function($args) { + ->will(function ($args) { return new Key('my-awesome-project', [ 'path' => [ ['kind' => $args[0], 'name' => $args[1]] @@ -129,7 +129,7 @@ public function testAncestorKey() { $ds = $this->prophesize(DatastoreClient::class); $ds->key(Argument::any(), Argument::any()) - ->will(function($args) { + ->will(function ($args) { return new Key('my-awesome-project', [ 'path' => [ ['kind' => $args[0], 'name' => $args[1]] @@ -150,7 +150,7 @@ public function testStateIncomplete() { $ds = $this->prophesize(DatastoreClient::class); $ds->key(Argument::any(), Argument::any()) - ->will(function($args) { + ->will(function ($args) { return new Key('my-awesome-project', [ 'path' => [ ['kind' => $args[0], 'id' => $args[1]] @@ -170,7 +170,7 @@ public function testStateNamed() { $ds = $this->prophesize(DatastoreClient::class); $ds->key(Argument::any(), Argument::any()) - ->will(function($args) { + ->will(function ($args) { return new Key('my-awesome-project', [ 'path' => [ ['kind' => $args[0], 'id' => $args[1]] @@ -190,7 +190,7 @@ public function testSetLastElementIdentifier() { $ds = $this->prophesize(DatastoreClient::class); $ds->key(Argument::any(), Argument::any()) - ->will(function($args) { + ->will(function ($args) { return new Key('my-awesome-project', [ 'path' => [ ['kind' => $args[0]] diff --git a/Datastore/tests/Snippet/Query/GqlQueryTest.php b/Datastore/tests/Snippet/Query/GqlQueryTest.php index cc6ea98722dc..9f18f3f3f375 100644 --- a/Datastore/tests/Snippet/Query/GqlQueryTest.php +++ b/Datastore/tests/Snippet/Query/GqlQueryTest.php @@ -17,13 +17,14 @@ namespace Google\Cloud\Datastore\Tests\Snippet\Query; +use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Datastore\Connection\ConnectionInterface; use Google\Cloud\Datastore\DatastoreClient; use Google\Cloud\Datastore\EntityIterator; use Google\Cloud\Datastore\EntityMapper; use Google\Cloud\Datastore\Operation; use Google\Cloud\Datastore\Query\GqlQuery; -use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Prophecy\Argument; /** @@ -37,9 +38,9 @@ class GqlQueryTest extends SnippetTestCase public function setUp() { - $this->datastore = new DatastoreClient; + $this->datastore = TestHelpers::stub(DatastoreClient::class, [], ['operation']); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->operation = \Google\Cloud\Core\Testing\TestHelpers::stub(Operation::class, [ + $this->operation = TestHelpers::stub(Operation::class, [ $this->connection->reveal(), 'my-awesome-project', '', @@ -72,14 +73,11 @@ public function testClass() $this->operation->___setProperty('connection', $this->connection->reveal()); + $this->datastore->___setProperty('operation', $this->operation); + $snippet = $this->snippetFromClass(GqlQuery::class); - $snippet->addLocal('operation', $this->operation); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($datastore); - $property = $reflection->getProperty(\'operation\'); - $property->setAccessible(true); - $property->setValue($datastore, $operation); - $property->setAccessible(false);' - ); + $snippet->replace('$datastore = new DatastoreClient();', ''); + $snippet->addLocal('datastore', $this->datastore); $res = $snippet->invoke(['query', 'res']); $this->assertEquals('Google', $res->output()); diff --git a/Datastore/tests/Snippet/Query/QueryTest.php b/Datastore/tests/Snippet/Query/QueryTest.php index acb5eed0a2f0..4025a0fe1c7c 100644 --- a/Datastore/tests/Snippet/Query/QueryTest.php +++ b/Datastore/tests/Snippet/Query/QueryTest.php @@ -17,6 +17,8 @@ namespace Google\Cloud\Datastore\Tests\Snippet\Query; +use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Datastore\Connection\ConnectionInterface; use Google\Cloud\Datastore\DatastoreClient; use Google\Cloud\Datastore\EntityIterator; @@ -24,7 +26,6 @@ use Google\Cloud\Datastore\Key; use Google\Cloud\Datastore\Operation; use Google\Cloud\Datastore\Query\Query; -use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Prophecy\Argument; /** @@ -41,9 +42,9 @@ public function setUp() { $mapper = new EntityMapper('my-awesome-project', true, false); - $this->datastore = new DatastoreClient; + $this->datastore = TestHelpers::stub(DatastoreClient::class, [], ['operation']); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->operation = \Google\Cloud\Core\Testing\TestHelpers::stub(Operation::class, [ + $this->operation = TestHelpers::stub(Operation::class, [ $this->connection->reveal(), 'my-awesome-project', '', @@ -79,14 +80,11 @@ public function testClass() $this->operation->___setProperty('connection', $this->connection->reveal()); + $this->datastore->___setProperty('operation', $this->operation); + $snippet = $this->snippetFromClass(Query::class); - $snippet->addLocal('operation', $this->operation); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($datastore); - $property = $reflection->getProperty(\'operation\'); - $property->setAccessible(true); - $property->setValue($datastore, $operation); - $property->setAccessible(false);' - ); + $snippet->replace('$datastore = new DatastoreClient();', ''); + $snippet->addLocal('datastore', $this->datastore); $res = $snippet->invoke('res'); $this->assertEquals('Google', $res->output()); @@ -153,7 +151,10 @@ public function testHasAncestor() $snippet->invoke(); - $this->assertEquals('__key__', $this->query->queryObject()['filter']['compositeFilter']['filters'][0]['propertyFilter']['property']['name']); + $this->assertEquals( + '__key__', + $this->query->queryObject()['filter']['compositeFilter']['filters'][0]['propertyFilter']['property']['name'] + ); } public function testHasAncestorWithType() @@ -165,7 +166,10 @@ public function testHasAncestorWithType() $snippet->invoke(); - $this->assertEquals('__key__', $this->query->queryObject()['filter']['compositeFilter']['filters'][0]['propertyFilter']['property']['name']); + $this->assertEquals( + '__key__', + $this->query->queryObject()['filter']['compositeFilter']['filters'][0]['propertyFilter']['property']['name'] + ); } public function testOrder() diff --git a/Datastore/tests/Snippet/ReadOnlyTransactionTest.php b/Datastore/tests/Snippet/ReadOnlyTransactionTest.php index c8649b503e39..ebfb2cca334d 100644 --- a/Datastore/tests/Snippet/ReadOnlyTransactionTest.php +++ b/Datastore/tests/Snippet/ReadOnlyTransactionTest.php @@ -126,10 +126,7 @@ public function testLookup() $snippet->addLocal('datastore', $this->client); $snippet->addLocal('transaction', $this->transaction); - $this->connection->lookup(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return true; - })) + $this->connection->lookup(Argument::withEntry('transaction', self::TRANSACTION)) ->shouldBeCalled() ->willReturn([ 'found' => [ @@ -164,10 +161,7 @@ public function testLookupBatch() $snippet->addLocal('datastore', $this->client); $snippet->addLocal('transaction', $this->transaction); - $this->connection->lookup(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return true; - })) + $this->connection->lookup(Argument::withEntry('transaction', self::TRANSACTION)) ->shouldBeCalled() ->willReturn([ 'found' => [ @@ -218,10 +212,7 @@ public function testRunQuery() $snippet->addLocal('transaction', $this->transaction); $snippet->addLocal('query', $this->prophesize(QueryInterface::class)->reveal()); - $this->connection->runQuery(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return true; - })) + $this->connection->runQuery(Argument::withEntry('transaction', self::TRANSACTION)) ->shouldBeCalled() ->willReturn([ 'batch' => [ diff --git a/Datastore/tests/Snippet/TransactionTest.php b/Datastore/tests/Snippet/TransactionTest.php index 41a1b0953617..72a1a46a1f6d 100644 --- a/Datastore/tests/Snippet/TransactionTest.php +++ b/Datastore/tests/Snippet/TransactionTest.php @@ -99,16 +99,16 @@ public function testInsert() $snippet->addLocal('datastore', $this->client); $snippet->addLocal('transaction', $this->transaction); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return array_keys($args['mutations'][0])[0] === 'insert'; - })) - ->shouldBeCalled() - ->willReturn([ - 'mutationResults' => [ - ['version' => 1] - ] - ]); + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'insert'; + }) + ))->shouldBeCalled()->willReturn([ + 'mutationResults' => [ + ['version' => 1] + ] + ]); $this->refreshOperation($this->transaction, $this->connection->reveal(), [ 'projectId' => self::PROJECT @@ -123,16 +123,16 @@ public function testInsertBatch() $snippet->addLocal('datastore', $this->client); $snippet->addLocal('transaction', $this->transaction); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return array_keys($args['mutations'][0])[0] === 'insert'; - })) - ->shouldBeCalled() - ->willReturn([ - 'mutationResults' => [ - ['version' => 1] - ] - ]); + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'insert'; + }) + ))->shouldBeCalled()->willReturn([ + 'mutationResults' => [ + ['version' => 1] + ] + ]); $this->allocateIdsConnectionMock(); @@ -152,16 +152,16 @@ public function testUpdate() 'populatedByService' => true ])); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return array_keys($args['mutations'][0])[0] === 'update'; - })) - ->shouldBeCalled() - ->willReturn([ - 'mutationResults' => [ - ['version' => 1] - ] - ]); + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'update'; + }) + ))->shouldBeCalled()->willReturn([ + 'mutationResults' => [ + ['version' => 1] + ] + ]); $this->refreshOperation($this->transaction, $this->connection->reveal(), [ 'projectId' => self::PROJECT @@ -180,11 +180,12 @@ public function testUpdateBatch() $this->client->entity($this->client->key('Person', 'John'), [], ['populatedByService' => true]) ]); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return array_keys($args['mutations'][0])[0] === 'update'; - })) - ->shouldBeCalled(); + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'update'; + }) + ))->shouldBeCalled(); $res = $snippet->invoke(); } @@ -198,10 +199,12 @@ public function testUpsert() 'populatedByService' => true ])); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return array_keys($args['mutations'][0])[0] === 'upsert'; - })) + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'upsert'; + }) + )) ->shouldBeCalled() ->willReturn([ 'mutationResults' => [ @@ -226,10 +229,12 @@ public function testUpsertBatch() $this->client->entity($this->client->key('Person', 'John'), [], ['populatedByService' => true]) ]); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return array_keys($args['mutations'][0])[0] === 'upsert'; - })) + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'upsert'; + }) + )) ->shouldBeCalled(); $res = $snippet->invoke(); @@ -241,10 +246,12 @@ public function testDelete() $snippet->addLocal('datastore', $this->client); $snippet->addLocal('transaction', $this->transaction); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - return array_keys($args['mutations'][0])[0] === 'delete'; - })) + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'delete'; + }) + )) ->shouldBeCalled() ->willReturn([ 'mutationResults' => [ @@ -265,12 +272,12 @@ public function testDeleteBatch() $snippet->addLocal('datastore', $this->client); $snippet->addLocal('transaction', $this->transaction); - $this->connection->commit(Argument::that(function ($args) { - if ($args['transaction'] !== self::TRANSACTION) return false; - if (array_keys($args['mutations'][0])[0] !== 'delete') return false; - return true; - })) - ->shouldBeCalled(); + $this->connection->commit(Argument::allOf( + Argument::withEntry('transaction', self::TRANSACTION), + Argument::that(function ($args) { + return array_keys($args['mutations'][0])[0] === 'delete'; + }) + ))->shouldBeCalled(); $res = $snippet->invoke(); } diff --git a/Datastore/tests/System/DatastoreTestCase.php b/Datastore/tests/System/DatastoreTestCase.php index bb194b01a56b..c7e5dee4f3e9 100644 --- a/Datastore/tests/System/DatastoreTestCase.php +++ b/Datastore/tests/System/DatastoreTestCase.php @@ -66,7 +66,7 @@ public static function tearDownFixtures() $transaction = self::$client->transaction(); self::$localDeletionQueue->process(function ($items) use ($backoff, $transaction) { - $backoff->execute(function() use ($items, $transaction) { + $backoff->execute(function () use ($items, $transaction) { $transaction->deleteBatch($items); }); }); diff --git a/Datastore/tests/System/RunQueryTest.php b/Datastore/tests/System/RunQueryTest.php index 4a7c358951cd..d70447e8a539 100644 --- a/Datastore/tests/System/RunQueryTest.php +++ b/Datastore/tests/System/RunQueryTest.php @@ -259,7 +259,7 @@ public function testGqlQueryWithLiteral() private function runQueryAndSortResults($query) { $results = iterator_to_array(self::$client->runQuery($query)); - usort($results, function($a, $b) { + usort($results, function ($a, $b) { return $a['knownDances'] - $b['knownDances']; }); diff --git a/Datastore/tests/Unit/BlobTest.php b/Datastore/tests/Unit/BlobTest.php index 3a09bc744e09..9d89a1bc7b41 100644 --- a/Datastore/tests/Unit/BlobTest.php +++ b/Datastore/tests/Unit/BlobTest.php @@ -35,7 +35,7 @@ public function testBlobString() public function testBlobResource() { $string = 'hello world'; - $stream = fopen('php://memory','r+'); + $stream = fopen('php://memory', 'r+'); fwrite($stream, $string); rewind($stream); diff --git a/Datastore/tests/Unit/DatastoreClientTest.php b/Datastore/tests/Unit/DatastoreClientTest.php index cf6d22a0aefe..560606fb98cd 100644 --- a/Datastore/tests/Unit/DatastoreClientTest.php +++ b/Datastore/tests/Unit/DatastoreClientTest.php @@ -195,8 +195,13 @@ public function testTransaction($method, $type, $key) Argument::withEntry('projectId', self::PROJECT), // can't do direct comparisons between (object)[]. Argument::that(function ($arg) use ($key) { - if (!($arg['transactionOptions'][$key] instanceof \stdClass)) return false; - if ((array) $arg['transactionOptions'][$key]) return false; + if (!($arg['transactionOptions'][$key] instanceof \stdClass)) { + return false; + } + + if ((array) $arg['transactionOptions'][$key]) { + return false; + } return true; }) diff --git a/Datastore/tests/Unit/DatastoreSessionHandlerTest.php b/Datastore/tests/Unit/DatastoreSessionHandlerTest.php index 55c028490792..4423bcc68c52 100644 --- a/Datastore/tests/Unit/DatastoreSessionHandlerTest.php +++ b/Datastore/tests/Unit/DatastoreSessionHandlerTest.php @@ -17,7 +17,6 @@ namespace Google\Cloud\Datastore\Tests\Unit; - use Exception; use Google\Cloud\Datastore\DatastoreClient; use Google\Cloud\Datastore\DatastoreSessionHandler; @@ -192,7 +191,7 @@ public function testWrite() ->willReturn($key); $that = $this; $this->datastore->entity($key, Argument::type('array'), Argument::type('array')) - ->will(function($args) use ($that, $key, $entity) { + ->will(function ($args) use ($that, $key, $entity) { $that->assertEquals($key, $args[0]); $that->assertEquals('sessiondata', $args[1]['data']); $that->assertInternalType('int', $args[1]['t']); @@ -237,7 +236,7 @@ public function testWriteWithException() ->willReturn($key); $that = $this; $this->datastore->entity($key, Argument::type('array'), Argument::type('array')) - ->will(function($args) use ($that, $key, $entity) { + ->will(function ($args) use ($that, $key, $entity) { $that->assertEquals($key, $args[0]); $that->assertEquals('sessiondata', $args[1]['data']); $that->assertInternalType('int', $args[1]['t']); @@ -282,7 +281,7 @@ public function testWriteWithEntityOptions() ->willReturn($key); $that = $this; $this->datastore->entity($key, Argument::type('array'), Argument::type('array')) - ->will(function($args) use ($that, $key, $entity) { + ->will(function ($args) use ($that, $key, $entity) { $that->assertEquals($key, $args[0]); $that->assertEquals('sessiondata', $args[1]['data']); $that->assertInternalType('int', $args[1]['t']); @@ -328,7 +327,7 @@ public function testWriteWithEmptyEntityOptions() ->willReturn($key); $that = $this; $this->datastore->entity($key, Argument::type('array'), Argument::type('array')) - ->will(function($args) use ($that, $key, $entity) { + ->will(function ($args) use ($that, $key, $entity) { $that->assertEquals($key, $args[0]); $that->assertEquals('sessiondata', $args[1]['data']); $that->assertInternalType('int', $args[1]['t']); @@ -468,7 +467,7 @@ public function testGc() Argument::type('int') ) ->shouldBeCalledTimes(1) - ->will(function($args) use ($that, $query) { + ->will(function ($args) use ($that, $query) { $that->assertEquals('t', $args[0]); $that->assertEquals('<', $args[1]); $that->assertInternalType('int', $args[2]); @@ -478,6 +477,7 @@ public function testGc() $that->assertGreaterThanOrEqual(100, $diff); return $query->reveal(); }); + $query->order('t') ->shouldBeCalledTimes(1) ->willReturn($query->reveal()); @@ -499,16 +499,15 @@ public function testGc() Argument::type('array') ) ->shouldBeCalledTimes(1) - ->will( - function($args) - use ($that, $query, $entity1, $entity2) { - $that->assertEquals($query->reveal(), $args[0]); - $that->assertEquals( - ['namespaceId' => self::NAMESPACE_ID], - $args[1] - ); - return [$entity1, $entity2]; - }); + ->will(function ($args) use ($that, $query, $entity1, $entity2) { + $that->assertEquals($query->reveal(), $args[0]); + $that->assertEquals( + ['namespaceId' => self::NAMESPACE_ID], + $args[1] + ); + return [$entity1, $entity2]; + }); + $this->datastore->deleteBatch([$key1, $key2]) ->shouldBeCalledTimes(1); $datastoreSessionHandler = new DatastoreSessionHandler( @@ -544,7 +543,7 @@ public function testGcWithException() Argument::type('int') ) ->shouldBeCalledTimes(1) - ->will(function($args) use ($that, $query) { + ->will(function ($args) use ($that, $query) { $that->assertEquals('t', $args[0]); $that->assertEquals('<', $args[1]); $that->assertInternalType('int', $args[2]); @@ -554,6 +553,7 @@ public function testGcWithException() $that->assertGreaterThanOrEqual(100, $diff); return $query->reveal(); }); + $query->order('t') ->shouldBeCalledTimes(1) ->willReturn($query->reveal()); @@ -575,16 +575,15 @@ public function testGcWithException() Argument::type('array') ) ->shouldBeCalledTimes(1) - ->will( - function($args) - use ($that, $query, $entity1, $entity2) { - $that->assertEquals($query->reveal(), $args[0]); - $that->assertEquals( - ['namespaceId' => self::NAMESPACE_ID], - $args[1] - ); - return [$entity1, $entity2]; - }); + ->will(function ($args) use ($that, $query, $entity1, $entity2) { + $that->assertEquals($query->reveal(), $args[0]); + $that->assertEquals( + ['namespaceId' => self::NAMESPACE_ID], + $args[1] + ); + return [$entity1, $entity2]; + }); + $this->datastore->deleteBatch([$key1, $key2]) ->shouldBeCalledTimes(1) ->willThrow(new Exception()); diff --git a/Datastore/tests/Unit/DatastoreTraitTest.php b/Datastore/tests/Unit/DatastoreTraitTest.php index ed83e2d738ad..458d4be1c801 100644 --- a/Datastore/tests/Unit/DatastoreTraitTest.php +++ b/Datastore/tests/Unit/DatastoreTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Datastore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Datastore\DatastoreClient; use Google\Cloud\Datastore\DatastoreTrait; use Google\Cloud\Datastore\Key; @@ -32,7 +33,7 @@ class DatastoreTraitTest extends TestCase public function setUp() { - $this->stub = new DatastoreTraitStub; + $this->stub = TestHelpers::impl(DatastoreTrait::class); } public function testPartitionId() @@ -46,13 +47,3 @@ public function testPartitionId() $this->assertEquals('bar', $res['namespaceId']); } } - -class DatastoreTraitStub -{ - use DatastoreTrait; - - public function call($fn, array $args) - { - return call_user_func_array([$this, $fn], $args); - } -} diff --git a/Datastore/tests/Unit/EntityMapperTest.php b/Datastore/tests/Unit/EntityMapperTest.php index aabda91c5355..10e94a875316 100644 --- a/Datastore/tests/Unit/EntityMapperTest.php +++ b/Datastore/tests/Unit/EntityMapperTest.php @@ -221,9 +221,9 @@ public function testResponseToPropertiesEntityValueCustomType() ] ]; - $res = $this->mapper->responseToEntityProperties($data, TestEntity::class)['properties']; + $res = $this->mapper->responseToEntityProperties($data, SampleEntity::class)['properties']; - $this->assertInstanceOf(TestEntity::class, $res['foo']); + $this->assertInstanceOf(SampleEntity::class, $res['foo']); $this->assertEquals('baz', $res['foo']->get()['bar']); } @@ -247,9 +247,9 @@ public function testResponseToPropertiesEntityValueCustomTypeNestedPropertyUsesD ] ]; - $res = $this->mapper->responseToEntityProperties($data, TestEntity::class)['properties']; + $res = $this->mapper->responseToEntityProperties($data, SampleEntity::class)['properties']; - $this->assertInstanceOf(TestEntity::class, $res['foo']); + $this->assertInstanceOf(SampleEntity::class, $res['foo']); $this->assertTrue(is_array($res['foo']['bar'])); } @@ -279,11 +279,11 @@ public function testResponseToPropertiesEntityNestedValueCustomType() ] ]; - $res = $this->mapper->responseToEntityProperties($data, TestEntity::class)['properties']; + $res = $this->mapper->responseToEntityProperties($data, SampleEntity::class)['properties']; - $this->assertInstanceOf(TestEntity::class, $res['foo']); - $this->assertInstanceOf(TestEntity::class, $res['foo']['nest']); - $this->assertInstanceOf(TestEntity::class, $res['foo']['nest']['nest']); + $this->assertInstanceOf(SampleEntity::class, $res['foo']); + $this->assertInstanceOf(SampleEntity::class, $res['foo']['nest']); + $this->assertInstanceOf(SampleEntity::class, $res['foo']['nest']['nest']); $this->assertEquals('bar', $res['foo']['nest']['nest']['foo']); } @@ -709,15 +709,20 @@ public function testValueObjectNestedArrays() ] ]); - $this->assertEmpty((array) $res['entityValue']['properties']['foo']['arrayValue']['values'][2]['entityValue']['properties']); - $this->assertEmpty((array) $res['entityValue']['properties']['foo']['arrayValue']['values'][3]['entityValue']['properties']); + $this->assertEmpty( + (array) $res['entityValue']['properties']['foo']['arrayValue']['values'][2]['entityValue']['properties'] + ); + + $this->assertEmpty( + (array) $res['entityValue']['properties']['foo']['arrayValue']['values'][3]['entityValue']['properties'] + ); } public function testValueObjectResource() { $string = 'test data'; - $stream = fopen('php://memory','r+'); + $stream = fopen('php://memory', 'r+'); fwrite($stream, $string); rewind($stream); @@ -730,7 +735,7 @@ public function testValueObjectResourceNotEncoded() { $string = 'test data'; - $stream = fopen('php://memory','r+'); + $stream = fopen('php://memory', 'r+'); fwrite($stream, $string); rewind($stream); @@ -868,38 +873,3 @@ public function testObjectPropertyInt64() ], $res); } } - -class TestEntity implements EntityInterface, \arrayaccess -{ - use EntityTrait; - - public static function mappings() - { - return [ - 'foo' => TestEntity::class, - 'nest' => TestEntity::class - ]; - } - - public function offsetSet($key, $val) - { - $this->entity[$key] = $val; - } - - public function offsetExists($key) - { - return isset($this->entity[$key]); - } - - public function offsetUnset($key) - { - unset($this->entity[$key]); - } - - public function offsetGet($key) - { - return isset($this->entity[$key]) - ? $this->entity[$key] - : null; - } -} diff --git a/Datastore/tests/Unit/Fixtures.php b/Datastore/tests/Unit/Fixtures.php index 4065b271faad..dc42f96a12fc 100644 --- a/Datastore/tests/Unit/Fixtures.php +++ b/Datastore/tests/Unit/Fixtures.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Datastore\Tests\Unit; +//@codingStandardsIgnoreStart class Fixtures { public static function ENTITY_BATCH_LOOKUP_FIXTURE() @@ -44,3 +45,4 @@ public static function ENTITY_RESULT_NO_PROPERTIES_FIXTURE() return __DIR__ . '/fixtures/entity-result-no-properties.json'; } } +//@codingStandardsIgnoreEnd diff --git a/Datastore/tests/Unit/OperationTest.php b/Datastore/tests/Unit/OperationTest.php index be1d577ada93..dad2e7f01af6 100644 --- a/Datastore/tests/Unit/OperationTest.php +++ b/Datastore/tests/Unit/OperationTest.php @@ -180,10 +180,10 @@ public function testInvalidKeyType() public function testEntityCustomClass() { $e = $this->operation->entity('Foo', [], [ - 'className' => MyEntity::class + 'className' => SampleEntity::class ]); - $this->assertInstanceOf(MyEntity::class, $e); + $this->assertInstanceOf(SampleEntity::class, $e); } /** @@ -477,7 +477,7 @@ public function testRunQueryPaged() { $queryResult = json_decode(file_get_contents(Fixtures::QUERY_RESULTS_FIXTURE()), true); $this->connection->runQuery(Argument::type('array')) - ->will(function($args, $mock) use ($queryResult) { + ->will(function ($args, $mock) use ($queryResult) { // The 2nd call will return the 2nd page of results! $mock->runQuery(Argument::type('array')) ->willReturn($queryResult['paged'][1]); @@ -568,15 +568,12 @@ public function testRunQueryWithoutReadOptions() public function testCommit() { - $this->connection->commit(Argument::that(function($arg) { - if ($arg['mode'] !== 'NON_TRANSACTIONAL') return false; - - if (count($arg['mutations']) > 0) return false; - - return true; - })) - ->shouldBeCalled() - ->willReturn(['foo']); + $this->connection->commit(Argument::allOf( + Argument::withEntry('mode', 'NON_TRANSACTIONAL'), + Argument::that(function ($arg) { + return count($arg['mutations']) === 0; + }) + ))->shouldBeCalled()->willReturn(['foo']); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -585,15 +582,12 @@ public function testCommit() public function testCommitInTransaction() { - $this->connection->commit(Argument::that(function($arg) { - if ($arg['mode'] !== 'TRANSACTIONAL') return false; - - if (count($arg['mutations']) > 0) return false; - - return true; - })) - ->shouldBeCalled() - ->willReturn(['foo']); + $this->connection->commit(Argument::allOf( + Argument::withEntry('mode', 'TRANSACTIONAL'), + Argument::that(function ($arg) { + return count($arg['mutations']) === 0; + }) + ))->shouldBeCalled()->willReturn(['foo']); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -604,7 +598,7 @@ public function testCommitInTransaction() public function testCommitWithMutation() { - $this->connection->commit(Argument::that(function($arg) { + $this->connection->commit(Argument::that(function ($arg) { return count($arg['mutations']) === 1; }))->shouldBeCalled()->willReturn(['foo']); @@ -667,9 +661,13 @@ public function testMutate() $id = 12345; $this->connection->commit(Argument::that(function ($arg) { - if (count($arg['mutations']) !== 1) return false; + if (count($arg['mutations']) !== 1) { + return false; + } - if (!isset($arg['mutations'][0]['insert'])) return false; + if (!isset($arg['mutations'][0]['insert'])) { + return false; + } return true; }))->shouldBeCalled(); @@ -703,8 +701,13 @@ public function testMutateWithBaseVersion() public function testMutateWithKey() { $this->connection->commit(Argument::that(function ($arg) { - if (!isset($arg['mutations'][0]['delete'])) return false; - if (!isset($arg['mutations'][0]['delete']['path'])) return false; + if (!isset($arg['mutations'][0]['delete'])) { + return false; + } + + if (!isset($arg['mutations'][0]['delete']['path'])) { + return false; + } return true; }))->willReturn('foo'); @@ -811,11 +814,11 @@ public function testMapEntityResultArrayOfClassNames() $entity = $this->operation->lookup([$key], [ 'className' => [ - 'Kind' => MyEntity::class + 'Kind' => SampleEntity::class ] ]); - $this->assertInstanceOf(MyEntity::class, $entity['found'][0]); + $this->assertInstanceOf(SampleEntity::class, $entity['found'][0]); } /** @@ -836,7 +839,7 @@ public function testMapEntityResultArrayOfClassNamesMissingKindMapItem() $entity = $this->operation->lookup([$key], [ 'className' => [ - 'Kind2' => MyEntity::class + 'Kind2' => SampleEntity::class ] ]); } @@ -871,11 +874,7 @@ public function testNonTransactionalReadOptions() public function testReadConsistencyInReadOptions() { - $this->connection->lookup(Argument::that(function ($arg) { - if ($arg['readOptions']['readConsistency'] !== 'test') return true; - - return true; - })) + $this->connection->lookup(Argument::withEntry('readOptions', ['readConsistency' => 'test'])) ->willReturn([]); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -894,5 +893,3 @@ public function testInvalidBatchType() $this->operation->lookup(['foo']); } } - -class MyEntity extends Entity {} diff --git a/Datastore/tests/Unit/Query/QueryTest.php b/Datastore/tests/Unit/Query/QueryTest.php index 536ebf5e1c69..ba7585980546 100644 --- a/Datastore/tests/Unit/Query/QueryTest.php +++ b/Datastore/tests/Unit/Query/QueryTest.php @@ -308,10 +308,27 @@ public function testHasAncestorWithKeyObject() $res = $this->query->queryObject(); - $this->assertEquals('__key__', $res['filter']['compositeFilter']['filters'][0]['propertyFilter']['property']['name']); - $this->assertEquals('Kind', $res['filter']['compositeFilter']['filters'][0]['propertyFilter']['value']['keyValue']['path'][0]['kind']); - $this->assertEquals('Name', $res['filter']['compositeFilter']['filters'][0]['propertyFilter']['value']['keyValue']['path'][0]['name']); - $this->assertEquals('foo', $res['filter']['compositeFilter']['filters'][0]['propertyFilter']['value']['keyValue']['partitionId']['projectId']); + $propertyFilter = $res['filter']['compositeFilter']['filters'][0]['propertyFilter']; + + $this->assertEquals( + '__key__', + $propertyFilter['property']['name'] + ); + + $this->assertEquals( + 'Kind', + $propertyFilter['value']['keyValue']['path'][0]['kind'] + ); + + $this->assertEquals( + 'Name', + $propertyFilter['value']['keyValue']['path'][0]['name'] + ); + + $this->assertEquals( + 'foo', + $propertyFilter['value']['keyValue']['partitionId']['projectId'] + ); } public function testDistinctOn() diff --git a/Datastore/tests/Unit/SampleEntity.php b/Datastore/tests/Unit/SampleEntity.php new file mode 100644 index 000000000000..2ab3a09f9f6a --- /dev/null +++ b/Datastore/tests/Unit/SampleEntity.php @@ -0,0 +1,56 @@ + SampleEntity::class, + 'nest' => SampleEntity::class + ]; + } + + public function offsetSet($key, $val) + { + $this->entity[$key] = $val; + } + + public function offsetExists($key) + { + return isset($this->entity[$key]); + } + + public function offsetUnset($key) + { + unset($this->entity[$key]); + } + + public function offsetGet($key) + { + return isset($this->entity[$key]) + ? $this->entity[$key] + : null; + } +} diff --git a/Datastore/tests/Unit/TransactionTest.php b/Datastore/tests/Unit/TransactionTest.php index 062d9cef3b7e..71cd52741687 100644 --- a/Datastore/tests/Unit/TransactionTest.php +++ b/Datastore/tests/Unit/TransactionTest.php @@ -417,8 +417,15 @@ public function transactionProvider() return [ // return callables to get around phpunit's annoying habit of running data providers way too early. - [function () { return $this->transaction; }], - [function () { return $this->readOnly; }] + [ + function () { + return $this->transaction; + } + ], [ + function () { + return $this->readOnly; + } + ] ]; } } diff --git a/Debugger/tests/Snippet/DebuggeeTest.php b/Debugger/tests/Snippet/DebuggeeTest.php index 4ab91e3d7458..c6cd1553d2a9 100644 --- a/Debugger/tests/Snippet/DebuggeeTest.php +++ b/Debugger/tests/Snippet/DebuggeeTest.php @@ -135,10 +135,13 @@ public function testUpdateBreakpointBatch() public function testSetBreakpoint() { - $this->connection->setBreakpoint(Argument::any())->willReturn(['breakpoint' => ['id' => 'breakpoint1']])->shouldBeCalled(); + $this->connection->setBreakpoint(Argument::any()) + ->willReturn(['breakpoint' => ['id' => 'breakpoint1']])->shouldBeCalled(); + $debuggee = new Debuggee($this->connection->reveal(), ['project' => 'project']); $snippet = $this->snippetFromMethod(Debuggee::class, 'setBreakpoint'); $snippet->addLocal('debuggee', $debuggee); + $resp = $snippet->invoke('breakpoint'); $breakpoint = $resp->returnVal(); $this->assertInstanceOf(Breakpoint::class, $breakpoint); diff --git a/Debugger/tests/Snippet/DebuggerClientTest.php b/Debugger/tests/Snippet/DebuggerClientTest.php index becaebb91199..542a3002fdc7 100644 --- a/Debugger/tests/Snippet/DebuggerClientTest.php +++ b/Debugger/tests/Snippet/DebuggerClientTest.php @@ -18,9 +18,10 @@ namespace Google\Cloud\Debugger\Snippets\Trace; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Debugger\Connection\ConnectionInterface; -use Google\Cloud\Debugger\DebuggerClient; use Google\Cloud\Debugger\Debuggee; +use Google\Cloud\Debugger\DebuggerClient; use Prophecy\Argument; /** @@ -34,7 +35,7 @@ class DebuggerClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(DebuggerClient::class); + $this->client = TestHelpers::stub(DebuggerClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } diff --git a/Debugger/tests/Snippet/ExtendedSourceContextTest.php b/Debugger/tests/Snippet/ExtendedSourceContextTest.php index 32e08337371c..72ed7a2fa7ce 100644 --- a/Debugger/tests/Snippet/ExtendedSourceContextTest.php +++ b/Debugger/tests/Snippet/ExtendedSourceContextTest.php @@ -46,6 +46,7 @@ public function testContext() } } +//@codingStandardsIgnoreStart class TestSourceContext implements SourceContext { public function info() @@ -55,3 +56,4 @@ public function info() ]; } } +//@codingStandardsIgnoreEnd diff --git a/Debugger/tests/System/app/web/app.php b/Debugger/tests/System/app/web/app.php index acb6f9ca19c7..022454e38ae0 100644 --- a/Debugger/tests/System/app/web/app.php +++ b/Debugger/tests/System/app/web/app.php @@ -21,7 +21,7 @@ $app = new Silex\Application(); -$app->get('/', function() { +$app->get('/', function () { return 'Silex version ' . Silex\Application::VERSION; }); diff --git a/Debugger/tests/Unit/BreakpointStorage/SysvBreakpointStorageTest.php b/Debugger/tests/Unit/BreakpointStorage/SysvBreakpointStorageTest.php index 8be8b0481d12..c92730f47ff3 100644 --- a/Debugger/tests/Unit/BreakpointStorage/SysvBreakpointStorageTest.php +++ b/Debugger/tests/Unit/BreakpointStorage/SysvBreakpointStorageTest.php @@ -37,7 +37,8 @@ public function setUp() { if (!$this->isSysvIPCLoaded()) { $this->markTestSkipped( - 'Skipping because SystemV IPC extensions are not loaded'); + 'Skipping because SystemV IPC extensions are not loaded' + ); } $this->storage = new SysvBreakpointStorage(); } diff --git a/Debugger/tests/Unit/DebuggerClientTest.php b/Debugger/tests/Unit/DebuggerClientTest.php index 11b6fc9796a0..0e39e2dde746 100644 --- a/Debugger/tests/Unit/DebuggerClientTest.php +++ b/Debugger/tests/Unit/DebuggerClientTest.php @@ -17,35 +17,40 @@ namespace Google\Cloud\Debugger\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Debugger\Connection\ConnectionInterface; -use Google\Cloud\Debugger\DebuggerClient; use Google\Cloud\Debugger\Debuggee; -use Prophecy\Argument; +use Google\Cloud\Debugger\DebuggerClient; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group debugger */ class DebuggerClientTest extends TestCase { + const PROJECT = 'my-project'; + private $client; private $connection; public function setUp() { - $this->client = new DebuggerTestClient(['projectId' => 'project1']); + $this->client = TestHelpers::stub(DebuggerClient::class, [ + ['projectId' => self::PROJECT] + ]); $this->connection = $this->prophesize(ConnectionInterface::class); } public function testListsDebuggees() { - $this->connection->listDebuggees(['project' => 'project1'])->willReturn([ + $this->connection->listDebuggees(['project' => self::PROJECT])->willReturn([ 'debuggees' => [ - ['id' => 'debuggee1', 'project' => 'project1'], - ['id' => 'debuggee2', 'project' => 'project1'], + ['id' => 'debuggee1', 'project' => self::PROJECT], + ['id' => 'debuggee2', 'project' => self::PROJECT], ] ]); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $debuggees = $this->client->debuggees(); $this->assertCount(2, $debuggees); $this->assertEquals('debuggee1', $debuggees[0]->id()); @@ -54,8 +59,8 @@ public function testListsDebuggees() public function testListsDebuggeesEmpty() { - $this->connection->listDebuggees(['project' => 'project1'])->willReturn([]); - $this->client->setConnection($this->connection->reveal()); + $this->connection->listDebuggees(['project' => self::PROJECT])->willReturn([]); + $this->client->___setProperty('connection', $this->connection->reveal()); $debuggees = $this->client->debuggees(); $this->assertCount(0, $debuggees); } @@ -74,11 +79,3 @@ public function testLazilyBuildsDebuggee() $this->assertNull($debuggee->id()); } } - -class DebuggerTestClient extends DebuggerClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } -} diff --git a/Debugger/tests/Unit/VariableTableTest.php b/Debugger/tests/Unit/VariableTableTest.php index 5073f1d197ef..b026f31feffb 100644 --- a/Debugger/tests/Unit/VariableTableTest.php +++ b/Debugger/tests/Unit/VariableTableTest.php @@ -132,7 +132,7 @@ public function primitiveValues() ['some string', 'string', 'some string'], [1234, 'integer', '1234'], [1234.2, 'double', '1234.2'], - [NULL, 'NULL', 'NULL'] + [null, 'NULL', 'NULL'] ]; } @@ -287,6 +287,9 @@ public function testLimitsTotalSize() $index = $bufferFullReference->info()['varTableIndex']; $bufferFullVariable = $variables[$index]; - $this->assertEquals(VariableTable::BUFFER_FULL_MESSAGE, $bufferFullVariable->info()['status']['description']['format']); + $this->assertEquals( + VariableTable::BUFFER_FULL_MESSAGE, + $bufferFullVariable->info()['status']['description']['format'] + ); } } diff --git a/ErrorReporting/tests/Unit/BootstrapTest.php b/ErrorReporting/tests/Unit/BootstrapTest.php index 03968b57fb2f..e9eb34cd223a 100644 --- a/ErrorReporting/tests/Unit/BootstrapTest.php +++ b/ErrorReporting/tests/Unit/BootstrapTest.php @@ -24,7 +24,9 @@ use Prophecy\Argument; use PHPUnit\Framework\TestCase; +//@codingStandardsIgnoreStart require_once __DIR__ . '/fakeGlobalFunctions.php'; +//@codingStandardsIgnoreEnd /** * @group error-reporting @@ -45,7 +47,8 @@ public function testPrependFileLocation() $prependFileLocation = Bootstrap::prependFileLocation(); $this->assertFileExists( $prependFileLocation, - "The prepend file doesn't exist at $prependFileLocation"); + "The prepend file doesn't exist at $prependFileLocation" + ); } /** @@ -109,9 +112,8 @@ public function levelAndErrorLevelString() /** * @dataProvider exceptionProvider */ - public function testExceptionHandler( - $exception - ) { + public function testExceptionHandler($exception) + { $expectedMessage = sprintf('PHP Notice: %s', (string)$exception); $expectedContext = [ 'context' => [ @@ -218,10 +220,12 @@ public function testErrorHandlerWithMinorError() 'file', 1 ); + $this->assertTrue($result); } - public function testErrorHandlerWithoutLogger() { + public function testErrorHandlerWithoutLogger() + { Bootstrap::$psrLogger = null; MockValues::$errorReporting = E_ERROR; $result = Bootstrap::errorHandler( diff --git a/ErrorReporting/tests/Unit/fakeGlobalFunctions.php b/ErrorReporting/tests/Unit/fakeGlobalFunctions.php index aad6a31c75da..fb18cc39feab 100644 --- a/ErrorReporting/tests/Unit/fakeGlobalFunctions.php +++ b/ErrorReporting/tests/Unit/fakeGlobalFunctions.php @@ -1,34 +1,36 @@ MockValues::$type, - 'message' => MockValues::$message, - 'file' => MockValues::$file, - 'line' => MockValues::$line - ]; - }; +namespace Google\Cloud\ErrorReporting; + +class MockValues +{ + public static $type; + public static $message; + public static $file; + public static $line; + public static $errorReporting; + public static $stderr; +} - function error_reporting() - { - return MockValues::$errorReporting; - }; +function error_get_last() +{ + return [ + 'type' => MockValues::$type, + 'message' => MockValues::$message, + 'file' => MockValues::$file, + 'line' => MockValues::$line + ]; +} - function fwrite($target, $message) - { - if ($target != STDERR) { - throw new \RuntimeException('Only for STDERR'); - } - MockValues::$stderr = $message; - }; +function error_reporting() +{ + return MockValues::$errorReporting; +} + +function fwrite($target, $message) +{ + if ($target != STDERR) { + throw new \RuntimeException('Only for STDERR'); + } + MockValues::$stderr = $message; } diff --git a/Firestore/tests/Conformance/FirestoreTest.php b/Firestore/tests/Conformance/FirestoreTest.php index 94650435f0c0..146cae0d0e31 100644 --- a/Firestore/tests/Conformance/FirestoreTest.php +++ b/Firestore/tests/Conformance/FirestoreTest.php @@ -17,6 +17,8 @@ namespace Google\Cloud\Firestore\Tests\Conformance; +use Google\ApiCore\Serializer; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\FieldPath; @@ -24,7 +26,6 @@ use Google\Cloud\Firestore\FirestoreClient; use Google\Cloud\Firestore\PathTrait; use Google\Cloud\Tests\ArrayHasSameValuesToken; -use Google\ApiCore\Serializer; use GuzzleHttp\Client; use PHPUnit\Framework\TestCase; use Prophecy\Argument; @@ -37,7 +38,8 @@ class FirestoreTest extends TestCase { use PathTrait; - const TEST_FILE = 'https://raw.githubusercontent.com/GoogleCloudPlatform/google-cloud-common/master/testing/firestore/testdata/test-suite.binprotos'; + const TEST_FILE = 'https://raw.githubusercontent.com/GoogleCloudPlatform/'. + 'google-cloud-common/master/testing/firestore/testdata/test-suite.binprotos'; private $client; private $connection; @@ -63,7 +65,7 @@ class FirestoreTest extends TestCase public function setUp() { - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(FirestoreClient::class, [ + $this->client = TestHelpers::stub(FirestoreClient::class, [ [ 'projectId' => 'projectID' ] @@ -106,7 +108,7 @@ public function testConformance($description, $type, array $test) $method = 'runDelete'; break; - default : + default: throw \Exception('Invalid test type '. $type); break; } @@ -330,7 +332,6 @@ private function generateFields($data) { $fields = json_decode($data, true); return $this->injectSentinels($fields); - } private function injectSentinels(array $fields) @@ -377,10 +378,12 @@ public function cases() $protos[] = [$case['description'], $type, $case[$type]]; } + return $protos; } - private static function loadProto($bytes, $index) { + private static function loadProto($bytes, $index) + { list($num, $index) = \VarInt::decode($bytes, $index); $binProto = substr($bytes, $index, $num); $testProto = new \Tests\Test(); diff --git a/Firestore/tests/Snippet/CollectionReferenceTest.php b/Firestore/tests/Snippet/CollectionReferenceTest.php index 4cbc1b4a6bbd..63c0119aff80 100644 --- a/Firestore/tests/Snippet/CollectionReferenceTest.php +++ b/Firestore/tests/Snippet/CollectionReferenceTest.php @@ -17,14 +17,15 @@ namespace Google\Cloud\Firestore\Tests\Snippet; -use Prophecy\Argument; -use Google\Cloud\Firestore\Query; use Google\Cloud\Core\Testing\GrpcTestTrait; -use Google\Cloud\Firestore\ValueMapper; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; -use Google\Cloud\Firestore\DocumentReference; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\CollectionReference; use Google\Cloud\Firestore\Connection\ConnectionInterface; +use Google\Cloud\Firestore\DocumentReference; +use Google\Cloud\Firestore\Query; +use Google\Cloud\Firestore\ValueMapper; +use Prophecy\Argument; /** * @group firestore @@ -44,7 +45,7 @@ class CollectionReferenceTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->collection = \Google\Cloud\Core\Testing\TestHelpers::stub(CollectionReference::class, [ + $this->collection = TestHelpers::stub(CollectionReference::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), self::NAME diff --git a/Firestore/tests/Snippet/DocumentReferenceStub.php b/Firestore/tests/Snippet/DocumentReferenceStub.php new file mode 100644 index 000000000000..270a133b007b --- /dev/null +++ b/Firestore/tests/Snippet/DocumentReferenceStub.php @@ -0,0 +1,30 @@ +batch; + } +} diff --git a/Firestore/tests/Snippet/DocumentReferenceTest.php b/Firestore/tests/Snippet/DocumentReferenceTest.php index 5fafb313c8fd..8c8a71422c24 100644 --- a/Firestore/tests/Snippet/DocumentReferenceTest.php +++ b/Firestore/tests/Snippet/DocumentReferenceTest.php @@ -19,6 +19,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\CollectionReference; use Google\Cloud\Firestore\Connection\ConnectionInterface; @@ -46,12 +47,12 @@ class DocumentReferenceTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->document = \Google\Cloud\Core\Testing\TestHelpers::stub(DocumentReferenceStub::class, [ + $this->document = TestHelpers::stub(DocumentReferenceStub::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), $this->prophesize(CollectionReference::class)->reveal(), self::DOCUMENT - ]); + ], ['connection', 'batch']); $this->batch = $this->prophesize(WriteBatch::class); } @@ -106,7 +107,7 @@ public function testCreate() $this->batch->create(self::DOCUMENT, Argument::any(), Argument::any()) ->shouldBeCalled()->willReturn($this->batch->reveal()); - $this->document->setBatch($this->batch->reveal()); + $this->document->___setProperty('batch', $this->batch->reveal()); $snippet = $this->snippetFromMethod(DocumentReference::class, 'create'); $snippet->addLocal('document', $this->document); @@ -122,7 +123,7 @@ public function testSet() $this->batch->set(self::DOCUMENT, Argument::any(), Argument::any()) ->shouldBeCalled()->willReturn($this->batch->reveal()); - $this->document->setBatch($this->batch->reveal()); + $this->document->___setProperty('batch', $this->batch->reveal()); $snippet = $this->snippetFromMethod(DocumentReference::class, 'set'); $snippet->addLocal('document', $this->document); @@ -138,7 +139,7 @@ public function testUpdate() $this->batch->update(self::DOCUMENT, Argument::any(), Argument::any()) ->shouldBeCalled()->willReturn($this->batch->reveal()); - $this->document->setBatch($this->batch->reveal()); + $this->document->___setProperty('batch', $this->batch->reveal()); $snippet = $this->snippetFromMethod(DocumentReference::class, 'update'); $snippet->addLocal('document', $this->document); @@ -156,7 +157,7 @@ public function testUpdateSentinels() ['path' => 'lastLogin', 'value' => FieldValue::serverTimestamp()] ], Argument::any())->shouldBeCalled()->willReturn($this->batch->reveal()); - $this->document->setBatch($this->batch->reveal()); + $this->document->___setProperty('batch', $this->batch->reveal()); $snippet = $this->snippetFromMethod(DocumentReference::class, 'update', 1); $snippet->addLocal('document', $this->document); @@ -166,13 +167,13 @@ public function testUpdateSentinels() public function testUpdateSpecialChars() { $this->batch->commit(Argument::any()) - ->shouldBeCalled() - ->willReturn([[]]); + ->shouldBeCalled() + ->willReturn([[]]); $this->batch->update(self::DOCUMENT, Argument::any(), Argument::any()) ->shouldBeCalled()->willReturn($this->batch->reveal()); - $this->document->setBatch($this->batch->reveal()); + $this->document->___setProperty('batch', $this->batch->reveal()); $snippet = $this->snippetFromMethod(DocumentReference::class, 'update', 2); $snippet->addLocal('document', $this->document); @@ -188,7 +189,7 @@ public function testDelete() $this->batch->delete(self::DOCUMENT, Argument::any()) ->shouldBeCalled()->willReturn($this->batch->reveal()); - $this->document->setBatch($this->batch->reveal()); + $this->document->___setProperty('batch', $this->batch->reveal()); $snippet = $this->snippetFromMethod(DocumentReference::class, 'delete'); $snippet->addLocal('document', $this->document); @@ -238,18 +239,3 @@ public function testCollections() $this->assertContainsOnlyInstancesOf(CollectionReference::class, $res->returnVal()); } } - -class DocumentReferenceStub extends DocumentReference -{ - private $batch; - - public function setBatch(WriteBatch $batch) - { - $this->batch = $batch; - } - - protected function batchFactory() - { - return $this->batch; - } -} diff --git a/Firestore/tests/Snippet/DocumentSnapshotTest.php b/Firestore/tests/Snippet/DocumentSnapshotTest.php index 25501d34fc97..cbfb066897b3 100644 --- a/Firestore/tests/Snippet/DocumentSnapshotTest.php +++ b/Firestore/tests/Snippet/DocumentSnapshotTest.php @@ -17,14 +17,15 @@ namespace Google\Cloud\Firestore\Tests\Snippet; -use Google\Cloud\Core\Timestamp; +use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; +use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\DocumentReference; use Google\Cloud\Firestore\DocumentSnapshot; use Google\Cloud\Firestore\FirestoreClient; use Google\Cloud\Firestore\ValueMapper; -use Google\Cloud\Core\Testing\GrpcTestTrait; use Prophecy\Argument; /** @@ -47,7 +48,7 @@ public function setUp() $ref->id()->willReturn(array_pop($parts)); $ref->path()->willReturn(explode('/documents/', self::DOCUMENT)[1]); - $this->snapshot = \Google\Cloud\Core\Testing\TestHelpers::stub(DocumentSnapshot::class, [ + $this->snapshot = TestHelpers::stub(DocumentSnapshot::class, [ $ref->reveal(), new ValueMapper($this->prophesize(ConnectionInterface::class)->reveal(), false), [], @@ -67,7 +68,7 @@ public function testClass() ['missing' => self::DOCUMENT] ])); - $client = \Google\Cloud\Core\Testing\TestHelpers::stub(FirestoreClient::class); + $client = TestHelpers::stub(FirestoreClient::class); $client->___setProperty('connection', $connection->reveal()); $snippet = $this->snippetFromClass(DocumentSnapshot::class); $snippet->setLine(2, ''); diff --git a/Firestore/tests/Snippet/FieldValueTest.php b/Firestore/tests/Snippet/FieldValueTest.php index 25ae6c9773d3..aae1654abc48 100644 --- a/Firestore/tests/Snippet/FieldValueTest.php +++ b/Firestore/tests/Snippet/FieldValueTest.php @@ -17,13 +17,14 @@ namespace Google\Cloud\Firestore\Tests\Snippet; -use Prophecy\Argument; use Google\Cloud\Core\Testing\GrpcTestTrait; -use Google\Cloud\Firestore\FieldValue; -use Google\Cloud\Firestore\FirestoreClient; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\Connection\ConnectionInterface; +use Google\Cloud\Firestore\FieldValue; +use Google\Cloud\Firestore\FirestoreClient; use Google\Cloud\Firestore\V1beta1\DocumentTransform_FieldTransform_ServerValue; +use Prophecy\Argument; /** * @group firestore @@ -41,7 +42,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->firestore = \Google\Cloud\Core\Testing\TestHelpers::stub(FirestoreClient::class); + $this->firestore = TestHelpers::stub(FirestoreClient::class); } public function testDeleteField() diff --git a/Firestore/tests/Snippet/FirestoreClientTest.php b/Firestore/tests/Snippet/FirestoreClientTest.php index 536977eb1900..31fe04b616d8 100644 --- a/Firestore/tests/Snippet/FirestoreClientTest.php +++ b/Firestore/tests/Snippet/FirestoreClientTest.php @@ -22,6 +22,7 @@ use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\CollectionReference; use Google\Cloud\Firestore\Connection\ConnectionInterface; @@ -52,7 +53,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(FirestoreClient::class, [ + $this->client = TestHelpers::stub(FirestoreClient::class, [ ['projectId' => self::PROJECT] ]); } diff --git a/Firestore/tests/Snippet/QuerySnapshotTest.php b/Firestore/tests/Snippet/QuerySnapshotTest.php index b061b72f7300..241838e00e0b 100644 --- a/Firestore/tests/Snippet/QuerySnapshotTest.php +++ b/Firestore/tests/Snippet/QuerySnapshotTest.php @@ -17,13 +17,14 @@ namespace Google\Cloud\Firestore\Tests\Snippet; +use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\FirestoreClient; use Google\Cloud\Firestore\Query; use Google\Cloud\Firestore\QuerySnapshot; use Google\Cloud\Firestore\ValueMapper; -use Google\Cloud\Core\Testing\GrpcTestTrait; use Prophecy\Argument; /** @@ -40,7 +41,7 @@ class QuerySnapshotTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->snapshot = \Google\Cloud\Core\Testing\TestHelpers::stub(QuerySnapshot::class, [ + $this->snapshot = TestHelpers::stub(QuerySnapshot::class, [ $this->prophesize(Query::class)->reveal(), [] ], ['rows']); @@ -54,7 +55,7 @@ public function testClass() ->shouldBeCalled() ->willReturn(new \ArrayIterator([])); - $client = \Google\Cloud\Core\Testing\TestHelpers::stub(FirestoreClient::class); + $client = TestHelpers::stub(FirestoreClient::class); $client->___setProperty('connection', $this->connection->reveal()); $snippet = $this->snippetFromClass(QuerySnapshot::class); diff --git a/Firestore/tests/Snippet/QueryTest.php b/Firestore/tests/Snippet/QueryTest.php index 8e77a56794d9..52f378352db0 100644 --- a/Firestore/tests/Snippet/QueryTest.php +++ b/Firestore/tests/Snippet/QueryTest.php @@ -21,6 +21,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\Parser\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\Query; use Google\Cloud\Firestore\QuerySnapshot; @@ -44,7 +45,7 @@ class QueryTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->query = \Google\Cloud\Core\Testing\TestHelpers::stub(Query::class, [ + $this->query = TestHelpers::stub(Query::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), self::NAME, diff --git a/Firestore/tests/Snippet/TransactionTest.php b/Firestore/tests/Snippet/TransactionTest.php index 48f60fd65b02..ee9975471011 100644 --- a/Firestore/tests/Snippet/TransactionTest.php +++ b/Firestore/tests/Snippet/TransactionTest.php @@ -19,6 +19,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\CollectionReference; use Google\Cloud\Firestore\Connection\ConnectionInterface; @@ -56,7 +57,7 @@ class TransactionTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->transaction = \Google\Cloud\Core\Testing\TestHelpers::stub(TransactionStub::class, [ + $this->transaction = TestHelpers::stub(TransactionStub::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), self::DATABASE, @@ -80,7 +81,7 @@ public function testClass() $this->connection->rollback(Argument::any()) ->shouldBeCalled(); - $client = \Google\Cloud\Core\Testing\TestHelpers::stub(FirestoreClient::class); + $client = TestHelpers::stub(FirestoreClient::class); $client->___setProperty('connection', $this->connection->reveal()); $snippet = $this->snippetFromClass(Transaction::class); @@ -262,6 +263,7 @@ public function testDocumentsDoesntExist() } } +//@codingStandardsIgnoreStart class TransactionStub extends Transaction { private $database; @@ -289,3 +291,4 @@ public function setWriter(WriteBatch $writer) $this->___setProperty('writer', $writer); } } +//@codingStandardsIgnoreEnd diff --git a/Firestore/tests/Snippet/WriteBatchTest.php b/Firestore/tests/Snippet/WriteBatchTest.php index c2076f282635..be10b23248d7 100644 --- a/Firestore/tests/Snippet/WriteBatchTest.php +++ b/Firestore/tests/Snippet/WriteBatchTest.php @@ -17,13 +17,14 @@ namespace Google\Cloud\Firestore\Tests\Snippet; +use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\Parser\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\Connection\ConnectionInterface; +use Google\Cloud\Firestore\V1beta1\DocumentTransform_FieldTransform_ServerValue; use Google\Cloud\Firestore\ValueMapper; use Google\Cloud\Firestore\WriteBatch; -use Google\Cloud\Core\Testing\GrpcTestTrait; -use Google\Cloud\Firestore\V1beta1\DocumentTransform_FieldTransform_ServerValue; use Prophecy\Argument; /** @@ -43,7 +44,7 @@ class WriteBatchTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->batch = \Google\Cloud\Core\Testing\TestHelpers::stub(WriteBatch::class, [ + $this->batch = TestHelpers::stub(WriteBatch::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), self::DATABASE diff --git a/Firestore/tests/System/FirestoreTestCase.php b/Firestore/tests/System/FirestoreTestCase.php index d16e33232026..5c194d8e1856 100644 --- a/Firestore/tests/System/FirestoreTestCase.php +++ b/Firestore/tests/System/FirestoreTestCase.php @@ -60,7 +60,7 @@ public static function tearDownFixtures() self::$localDeletionQueue->process(function ($items) use ($backoff) { foreach ($items as $collection) { - $backoff->execute(function() use ($collection) { + $backoff->execute(function () use ($collection) { foreach ($collection->documents() as $document) { $document->reference()->delete(); } diff --git a/Firestore/tests/System/ValueMapperTest.php b/Firestore/tests/System/ValueMapperTest.php index a67080aae269..d1010c3d7ee2 100644 --- a/Firestore/tests/System/ValueMapperTest.php +++ b/Firestore/tests/System/ValueMapperTest.php @@ -69,10 +69,12 @@ public function values() [new Timestamp(\DateTime::createFromFormat('U', time()))], ['foo'], [self::$document], - [new GeoPoint(10,-10)], - [[1,2,3,4]], - [['foo' => 'bar', 'bat' => [1,2,3,4]]], - [NAN, function ($val) { return is_nan($val); }] + [new GeoPoint(10, -10)], + [[1, 2, 3, 4]], + [['foo' => 'bar', 'bat' => [1, 2, 3, 4]]], + [NAN, function ($val) { + return is_nan($val); + }] ]; } diff --git a/Firestore/tests/Unit/CollectionReferenceTest.php b/Firestore/tests/Unit/CollectionReferenceTest.php index 47309742d143..68441afbaf36 100644 --- a/Firestore/tests/Unit/CollectionReferenceTest.php +++ b/Firestore/tests/Unit/CollectionReferenceTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\CollectionReference; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\DocumentReference; @@ -42,7 +43,7 @@ class CollectionReferenceTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->collection = \Google\Cloud\Core\Testing\TestHelpers::stub(CollectionReference::class, [ + $this->collection = TestHelpers::stub(CollectionReference::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), self::NAME @@ -104,7 +105,7 @@ public function testAdd() ]; unset($args['writes'][0]['update']['name']); - + return $args === $expected; }))->shouldBeCalled()->willReturn([[]]); @@ -130,7 +131,7 @@ public function testRandomNames(DocumentReference $doc) public function randomNames() { $connection = $this->prophesize(ConnectionInterface::class); - $collection = \Google\Cloud\Core\Testing\TestHelpers::stub(CollectionReference::class, [ + $collection = TestHelpers::stub(CollectionReference::class, [ $connection->reveal(), new ValueMapper($connection->reveal(), false), self::NAME diff --git a/Firestore/tests/Unit/DocumentReferenceTest.php b/Firestore/tests/Unit/DocumentReferenceTest.php index 9e54701c8f12..3dcd099d55cf 100644 --- a/Firestore/tests/Unit/DocumentReferenceTest.php +++ b/Firestore/tests/Unit/DocumentReferenceTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Core\TimeTrait; use Google\Cloud\Firestore\CollectionReference; @@ -49,7 +50,7 @@ public function setUp() $this->connection = $this->prophesize(ConnectionInterface::class); $valueMapper = new ValueMapper($this->connection->reveal(), false); - $this->document = \Google\Cloud\Core\Testing\TestHelpers::stub(DocumentReference::class, [ + $this->document = TestHelpers::stub(DocumentReference::class, [ $this->connection->reveal(), $valueMapper, new CollectionReference($this->connection->reveal(), $valueMapper, self::COLLECTION), diff --git a/Firestore/tests/Unit/DocumentSnapshotTest.php b/Firestore/tests/Unit/DocumentSnapshotTest.php index 52d370537950..d3aba0b2a8ae 100644 --- a/Firestore/tests/Unit/DocumentSnapshotTest.php +++ b/Firestore/tests/Unit/DocumentSnapshotTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\DocumentReference; @@ -43,7 +44,7 @@ public function setUp() $ref->id()->willReturn(self::ID); $ref->path()->willReturn('a/b'); - $this->snapshot = \Google\Cloud\Core\Testing\TestHelpers::stub(DocumentSnapshot::class, [ + $this->snapshot = TestHelpers::stub(DocumentSnapshot::class, [ $ref->reveal(), new ValueMapper($this->prophesize(ConnectionInterface::class)->reveal(), false), [], [], true diff --git a/Firestore/tests/Unit/FirestoreClientTest.php b/Firestore/tests/Unit/FirestoreClientTest.php index 6ff4748b2d03..ebd19891bd9b 100644 --- a/Firestore/tests/Unit/FirestoreClientTest.php +++ b/Firestore/tests/Unit/FirestoreClientTest.php @@ -21,6 +21,8 @@ use Google\Cloud\Core\Exception\AbortedException; use Google\Cloud\Core\GeoPoint; use Google\Cloud\Core\Iterator\ItemIterator; +use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\CollectionReference; use Google\Cloud\Firestore\Connection\ConnectionInterface; @@ -28,7 +30,6 @@ use Google\Cloud\Firestore\FieldPath; use Google\Cloud\Firestore\FirestoreClient; use Google\Cloud\Firestore\WriteBatch; -use Google\Cloud\Core\Testing\GrpcTestTrait; use PHPUnit\Framework\TestCase; use Prophecy\Argument; @@ -51,7 +52,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub( + $this->client = TestHelpers::stub( FirestoreClient::class, [['projectId' => self::PROJECT]] ); @@ -119,14 +120,16 @@ public function testCollectionsPaged() 'collection-c', ]; - $this->connection->listCollectionIds(Argument::that(function ($options) { - if ($options['foo'] !== 'bar') return false; - if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { - return false; - } + $this->connection->listCollectionIds(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::that(function ($options) { + if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { + return false; + } - return true; - }))->willReturn([ + return true; + }) + ))->willReturn([ 'collectionIds' => $collectionIds, 'nextPageToken' => 'foo' ])->shouldBeCalledTimes(2); @@ -143,7 +146,9 @@ public function testCollectionsPaged() foreach ($collections as $collection) { $i++; $arr[] = $collection; - if ($i == 6) break; + if ($i == 6) { + break; + } } $this->assertCount(6, $arr); @@ -318,7 +323,7 @@ public function testRunTransaction() $this->client->___setProperty('connection', $this->connection->reveal()); - $this->client->runTransaction(function ($t) {}); + $this->client->runTransaction($this->noop()); } public function testRunTransactionRetryable() @@ -329,7 +334,7 @@ public function testRunTransactionRetryable() $this->connection->beginTransaction([ 'database' => 'projects/'. self::PROJECT .'/databases/'. self::DATABASE - ])->shouldBeCalled()->will(function($args, $mock) use ($transactionId, $transactionId2) { + ])->shouldBeCalled()->will(function ($args, $mock) use ($transactionId, $transactionId2) { $mock->beginTransaction(Argument::withEntry('retryTransaction', $transactionId))->willReturn([ 'transaction' => $transactionId2 ]); @@ -339,22 +344,16 @@ public function testRunTransactionRetryable() ]; }); - $this->connection->commit(Argument::that(function ($args) use ($transactionId) { - if ($args['database'] !== 'projects/'. self::PROJECT .'/databases/'. self::DATABASE) return false; - if ($args['transaction'] !== $transactionId) return false; - - return true; - })) - ->shouldBeCalled() - ->will(function ($args, $mock) use ($timestamp, $transactionId2) { - $mock->commit(Argument::that(function ($args) use ($transactionId2) { - if ($args['database'] !== 'projects/'. self::PROJECT .'/databases/'. self::DATABASE) return false; - if ($args['transaction'] !== $transactionId2) return false; - - return true; - }))->willReturn([ - 'commitTime' => $timestamp, - ]); + $this->connection->commit(Argument::allOf( + Argument::withEntry('database', 'projects/'. self::PROJECT .'/databases/'. self::DATABASE), + Argument::withEntry('transaction', $transactionId) + ))->shouldBeCalled()->will(function ($args, $mock) use ($timestamp, $transactionId2) { + $mock->commit(Argument::allOf( + Argument::withEntry('database', 'projects/'. self::PROJECT .'/databases/'. self::DATABASE), + Argument::withEntry('transaction', $transactionId2) + ))->willReturn([ + 'commitTime' => $timestamp, + ]); throw new AbortedException(''); }); @@ -400,7 +399,9 @@ public function testRunTransactionNotRetryable() $this->client->___setProperty('connection', $this->connection->reveal()); - $res = $this->client->runTransaction(function ($t) { throw new \RangeException('foo'); }); + $res = $this->client->runTransaction(function ($t) { + throw new \RangeException('foo'); + }); } /** @@ -470,7 +471,7 @@ public function testInvalidNestedTransaction() $this->client->___setProperty('connection', $this->connection->reveal()); $this->client->runTransaction(function ($t) { - $this->client->runTransaction(function (){}); + $this->client->runTransaction($this->noop()); }); } @@ -499,4 +500,11 @@ public function testFieldPath() $this->assertInstanceOf(FieldPath::class, $path); $this->assertEquals($parts, $path->path()); } + + private function noop() + { + return function () { + return; + }; + } } diff --git a/Firestore/tests/Unit/PathTraitTest.php b/Firestore/tests/Unit/PathTraitTest.php index 8fd65e28c1fe..2b13c868ad4f 100644 --- a/Firestore/tests/Unit/PathTraitTest.php +++ b/Firestore/tests/Unit/PathTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\PathTrait; use PHPUnit\Framework\TestCase; @@ -36,7 +37,7 @@ class PathTraitTest extends TestCase public function setUp() { - $this->impl = \Google\Cloud\Core\Testing\TestHelpers::impl(PathTrait::class); + $this->impl = TestHelpers::impl(PathTrait::class); } public function testFullName() @@ -227,8 +228,14 @@ public function relativeNames() return [ [sprintf('projects/%s/databases/%s/documents/%s', self::PROJECT, self::DATABASE, self::ROOT), self::ROOT], [sprintf('projects/%s/databases/%s/documents', self::PROJECT, self::DATABASE), ''], - [sprintf('projects/%s/databases/%s/documents/%s', self::PROJECT, self::DATABASE, self::COLLECTION), self::COLLECTION], - [sprintf('projects/%s/databases/%s/documents/%s', self::PROJECT, self::DATABASE, self::DOCUMENT), self::DOCUMENT] + [ + sprintf('projects/%s/databases/%s/documents/%s', self::PROJECT, self::DATABASE, self::COLLECTION), + self::COLLECTION + ], + [ + sprintf('projects/%s/databases/%s/documents/%s', self::PROJECT, self::DATABASE, self::DOCUMENT), + self::DOCUMENT + ] ]; } diff --git a/Firestore/tests/Unit/QuerySnapshotTest.php b/Firestore/tests/Unit/QuerySnapshotTest.php index ed07475f0671..b9d2e221a035 100644 --- a/Firestore/tests/Unit/QuerySnapshotTest.php +++ b/Firestore/tests/Unit/QuerySnapshotTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; use Google\Cloud\Core\Exception\AbortedException; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\Query; use Google\Cloud\Firestore\QuerySnapshot; @@ -37,7 +38,7 @@ class QuerySnapshotTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->snapshot = \Google\Cloud\Core\Testing\TestHelpers::stub(QuerySnapshot::class, [ + $this->snapshot = TestHelpers::stub(QuerySnapshot::class, [ $this->prophesize(Query::class)->reveal(), [] ], ['rows']); diff --git a/Firestore/tests/Unit/QueryTest.php b/Firestore/tests/Unit/QueryTest.php index 62d4064483ce..f5bd49021057 100644 --- a/Firestore/tests/Unit/QueryTest.php +++ b/Firestore/tests/Unit/QueryTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; use Google\Cloud\Core\Testing\ArrayHasSameValuesToken; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\CollectionReference; use Google\Cloud\Firestore\Connection\ConnectionInterface; @@ -53,7 +54,7 @@ class QueryTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->query = \Google\Cloud\Core\Testing\TestHelpers::stub(Query::class, [ + $this->query = TestHelpers::stub(Query::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), self::PARENT, @@ -66,7 +67,8 @@ public function setUp() */ public function testConstructMissingFrom() { - new Query($this->connection->reveal(), + new Query( + $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), self::PARENT, [] @@ -767,18 +769,19 @@ public function testPositionInequalityFilter() ] ] ], - "where" => [ - "fieldFilter" => [ - "field" => [ - "fieldPath" => "foo" - ], - "op" => 3, - "value" => [ - "stringValue" => "bar" + 'where' => [ + 'fieldFilter' => [ + 'field' => [ + 'fieldPath' => 'foo' + ], + 'op' => 3, + 'value' => [ + 'stringValue' => 'bar' + ] ] ] ] - ]]); + ]); } /** diff --git a/Firestore/tests/Unit/SnapshotTraitTest.php b/Firestore/tests/Unit/SnapshotTraitTest.php index b5645081ccba..c29df8692bd8 100644 --- a/Firestore/tests/Unit/SnapshotTraitTest.php +++ b/Firestore/tests/Unit/SnapshotTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\DocumentReference; @@ -43,7 +44,7 @@ class SnapshotTraitTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->impl = \Google\Cloud\Core\Testing\TestHelpers::impl(SnapshotTrait::class); + $this->impl = TestHelpers::impl(SnapshotTrait::class); $this->valueMapper = new ValueMapper($this->connection->reveal(), false); } @@ -131,7 +132,12 @@ public function testGetSnapshotReadTime() $this->impl->call('getSnapshot', [ $this->connection->reveal(), self::NAME, - ['readTime' => new Timestamp(\DateTimeImmutable::createFromFormat('U', (string) $timestamp['seconds']), $timestamp['nanos'])] + [ + 'readTime' => new Timestamp( + \DateTimeImmutable::createFromFormat('U', (string) $timestamp['seconds']), + $timestamp['nanos'] + ) + ] ]); } diff --git a/Firestore/tests/Unit/TransactionTest.php b/Firestore/tests/Unit/TransactionTest.php index bbaba3d8deec..d62c6b13ae6c 100644 --- a/Firestore/tests/Unit/TransactionTest.php +++ b/Firestore/tests/Unit/TransactionTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\DocumentReference; @@ -49,7 +50,7 @@ public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); $this->valueMapper = new ValueMapper($this->connection->reveal(), false); - $this->transaction = \Google\Cloud\Core\Testing\TestHelpers::stub(Transaction::class, [ + $this->transaction = TestHelpers::stub(Transaction::class, [ $this->connection->reveal(), $this->valueMapper, sprintf('projects/%s/databases/%s', self::PROJECT, self::DATABASE), diff --git a/Firestore/tests/Unit/ValueMapperTest.php b/Firestore/tests/Unit/ValueMapperTest.php index c630c0d2b30f..b72fd8e34729 100644 --- a/Firestore/tests/Unit/ValueMapperTest.php +++ b/Firestore/tests/Unit/ValueMapperTest.php @@ -20,6 +20,7 @@ use Google\Cloud\Core\Blob; use Google\Cloud\Core\GeoPoint; use Google\Cloud\Core\Int64; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Core\TimeTrait; use Google\Cloud\Firestore\CollectionReference; @@ -45,7 +46,7 @@ class ValueMapperTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->mapper = \Google\Cloud\Core\Testing\TestHelpers::stub(ValueMapper::class, [ + $this->mapper = TestHelpers::stub(ValueMapper::class, [ $this->connection->reveal(), false ], ['connection', 'returnInt64AsObject']); @@ -150,13 +151,16 @@ function ($val) { $this->assertInstanceOf(DocumentReference::class, $val); $this->assertInstanceOf(CollectionReference::class, $val->parent()); $this->assertEquals('projects/example_project/databases/(default)/documents/a/b', $val->name()); - $this->assertEquals('projects/example_project/databases/(default)/documents/a', $val->parent()->name()); + $this->assertEquals( + 'projects/example_project/databases/(default)/documents/a', + $val->parent()->name() + ); } ] ]; } - function testDecodeValuesIntAsObject() + public function testDecodeValuesIntAsObject() { $val = ['integerValue' => 15]; @@ -170,7 +174,7 @@ function testDecodeValuesIntAsObject() /** * @expectedException RuntimeException */ - function testDecodeValuesInvalidValue() + public function testDecodeValuesInvalidValue() { $val = ['fooValue' => 15]; $res = $this->mapper->decodeValues(['val' => $val]); diff --git a/Firestore/tests/Unit/WriteBatchTest.php b/Firestore/tests/Unit/WriteBatchTest.php index b090c07ff4b2..0c079afeb74b 100644 --- a/Firestore/tests/Unit/WriteBatchTest.php +++ b/Firestore/tests/Unit/WriteBatchTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Firestore\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Firestore\Connection\ConnectionInterface; use Google\Cloud\Firestore\DocumentReference; @@ -46,7 +47,7 @@ class WriteBatchTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->batch = \Google\Cloud\Core\Testing\TestHelpers::stub(WriteBatch::class, [ + $this->batch = TestHelpers::stub(WriteBatch::class, [ $this->connection->reveal(), new ValueMapper($this->connection->reveal(), false), sprintf('projects/%s/databases/%s', self::PROJECT, self::DATABASE) @@ -283,7 +284,10 @@ public function testWriteUpdateTimePrecondition($name, $ref) $this->batch->delete($ref, [ 'precondition' => [ - 'updateTime' => new Timestamp(\DateTimeImmutable::createFromFormat('U', (string) $ts['seconds']), $ts['nanos']) + 'updateTime' => new Timestamp( + \DateTimeImmutable::createFromFormat('U', (string) $ts['seconds']), + $ts['nanos'] + ) ] ]); diff --git a/Language/tests/Snippet/AnnotationTest.php b/Language/tests/Snippet/AnnotationTest.php index 747067d51cb8..a93586f2ee80 100644 --- a/Language/tests/Snippet/AnnotationTest.php +++ b/Language/tests/Snippet/AnnotationTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Language\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Language\Annotation; use Google\Cloud\Language\Connection\ConnectionInterface; +use Google\Cloud\Language\LanguageClient; use Prophecy\Argument; /** @@ -76,19 +78,18 @@ public function setUp() public function testClass() { + $snippet = $this->snippetFromClass(Annotation::class); + $connection = $this->prophesize(ConnectionInterface::class); $connection->annotateText(Argument::any()) ->shouldBeCalled() ->willReturn([]); - $snippet = $this->snippetFromClass(Annotation::class); - $snippet->addLocal('connectionStub', $connection->reveal()); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($language); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($language, $connectionStub); - $property->setAccessible(false);' - ); + $language = TestHelpers::stub(LanguageClient::class); + $language->___setProperty('connection', $connection->reveal()); + + $snippet->replace('$language = new LanguageClient();', ''); + $snippet->addLocal('language', $language); $res = $snippet->invoke('annotation'); $this->assertInstanceOf(Annotation::class, $res->returnVal()); diff --git a/Language/tests/Snippet/LanguageClientTest.php b/Language/tests/Snippet/LanguageClientTest.php index 960a6a8da9b7..00d39e35f799 100644 --- a/Language/tests/Snippet/LanguageClientTest.php +++ b/Language/tests/Snippet/LanguageClientTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Language\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Language\Connection\ConnectionInterface; use Google\Cloud\Language\LanguageClient; use Prophecy\Argument; @@ -33,7 +34,7 @@ class LanguageClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(LanguageClient::class); + $this->client = TestHelpers::stub(LanguageClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } diff --git a/Language/tests/Unit/LanguageClientTest.php b/Language/tests/Unit/LanguageClientTest.php index 5a18e7d25d22..28a8641a0821 100644 --- a/Language/tests/Unit/LanguageClientTest.php +++ b/Language/tests/Unit/LanguageClientTest.php @@ -17,12 +17,13 @@ namespace Google\Cloud\Language\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Language\Annotation; use Google\Cloud\Language\Connection\ConnectionInterface; use Google\Cloud\Language\LanguageClient; use Google\Cloud\Storage\StorageObject; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group language @@ -34,7 +35,7 @@ class LanguageClientTest extends TestCase public function setUp() { - $this->client = new LanguageTestClient(); + $this->client = TestHelpers::stub(LanguageClient::class); $this->connection = $this->prophesize(ConnectionInterface::class); } @@ -49,7 +50,7 @@ public function testAnalyzeEntities($options, $expectedOptions) ->analyzeEntities($expectedOptions) ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $annotation = $this->client->analyzeEntities($content, $options); $this->assertInstanceOf(Annotation::class, $annotation); @@ -66,7 +67,7 @@ public function testAnalyzeSentiment($options, $expectedOptions) ->analyzeSentiment($expectedOptions) ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $annotation = $this->client->analyzeSentiment($content, $options); $this->assertInstanceOf(Annotation::class, $annotation); @@ -83,7 +84,7 @@ public function testAnalyzeEntitySentiment($options, $expectedOptions) ->analyzeEntitySentiment($expectedOptions) ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $annotation = $this->client->analyzeEntitySentiment($content, $options); $this->assertInstanceOf(Annotation::class, $annotation); } @@ -100,7 +101,7 @@ public function testAnalyzeSyntax($options, $expectedOptions) ->analyzeSyntax($expectedOptions) ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $annotation = $this->client->analyzeSyntax($content, $options); $this->assertInstanceOf(Annotation::class, $annotation); @@ -126,7 +127,7 @@ public function testClassifyText($options, $expectedOptions) 'categories' => $categories ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $annotation = $this->client->classifyText($content, $options); $this->assertInstanceOf(Annotation::class, $annotation); @@ -151,7 +152,7 @@ public function testAnnotateText($options, $expectedOptions) ->annotateText($expectedOptions) ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $annotation = $this->client->annotateText($content, $options); $this->assertInstanceOf(Annotation::class, $annotation); @@ -208,11 +209,3 @@ public function analyzeDataProvider() ]; } } - -class LanguageTestClient extends LanguageClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } -} diff --git a/Logging/tests/Snippet/LoggerTest.php b/Logging/tests/Snippet/LoggerTest.php index 0c0d131b7a98..49ace3ea085f 100644 --- a/Logging/tests/Snippet/LoggerTest.php +++ b/Logging/tests/Snippet/LoggerTest.php @@ -17,11 +17,12 @@ namespace Google\Cloud\Logging\Tests\Snippet; +use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Logging\Connection\ConnectionInterface; use Google\Cloud\Logging\Entry; use Google\Cloud\Logging\Logger; -use Google\Cloud\Core\Iterator\ItemIterator; use Prophecy\Argument; /** @@ -38,7 +39,7 @@ class LoggerTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->logger = \Google\Cloud\Core\Testing\TestHelpers::stub(Logger::class, [ + $this->logger = TestHelpers::stub(Logger::class, [ $this->connection->reveal(), self::NAME, self::PROJECT @@ -94,17 +95,17 @@ public function testEntriesWithFilter() $snippet->addLocal('logger', $this->logger); $this->connection->listEntries(Argument::that(function ($arg) { - if (!isset($arg['filter'])) return false; - if (strpos($arg['filter'], 'AND') === false) return false; + if (!isset($arg['filter']) || strpos($arg['filter'], 'AND') === false) { + return false; + } + return true; - })) - ->shouldBeCalled() - ->willReturn([ - 'entries' => [ - ['textPayload' => 'foo'], - ['textPayload' => 'bar'] - ] - ]); + }))->shouldBeCalled()->willReturn([ + 'entries' => [ + ['textPayload' => 'foo'], + ['textPayload' => 'bar'] + ] + ]); $this->logger->___setProperty('connection', $this->connection->reveal()); diff --git a/Logging/tests/Snippet/LoggingClientTest.php b/Logging/tests/Snippet/LoggingClientTest.php index cf6b6b74bef1..eb983bba2ecd 100644 --- a/Logging/tests/Snippet/LoggingClientTest.php +++ b/Logging/tests/Snippet/LoggingClientTest.php @@ -17,14 +17,15 @@ namespace Google\Cloud\Logging\Tests\Snippet; +use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Logging\Connection\ConnectionInterface; use Google\Cloud\Logging\Logger; use Google\Cloud\Logging\LoggingClient; use Google\Cloud\Logging\Metric; use Google\Cloud\Logging\PsrLogger; use Google\Cloud\Logging\Sink; -use Google\Cloud\Core\Iterator\ItemIterator; use Prophecy\Argument; /** @@ -38,7 +39,7 @@ class LoggingClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(LoggingClient::class); + $this->client = TestHelpers::stub(LoggingClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } diff --git a/Logging/tests/Snippet/MetricTest.php b/Logging/tests/Snippet/MetricTest.php index ff59f6f351b8..11620b70b214 100644 --- a/Logging/tests/Snippet/MetricTest.php +++ b/Logging/tests/Snippet/MetricTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Logging\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Logging\Connection\ConnectionInterface; use Google\Cloud\Logging\Metric; use Prophecy\Argument; @@ -36,7 +37,7 @@ class MetricTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->metric = \Google\Cloud\Core\Testing\TestHelpers::stub(Metric::class, [ + $this->metric = TestHelpers::stub(Metric::class, [ $this->connection->reveal(), self::METRIC, self::PROJECT diff --git a/Logging/tests/Snippet/PsrLoggerTest.php b/Logging/tests/Snippet/PsrLoggerTest.php index e1fbea510caa..5f5252271893 100644 --- a/Logging/tests/Snippet/PsrLoggerTest.php +++ b/Logging/tests/Snippet/PsrLoggerTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Logging\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Logging\Connection\ConnectionInterface; use Google\Cloud\Logging\Logger; use Google\Cloud\Logging\PsrLogger; @@ -34,12 +35,10 @@ class PsrLoggerTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $logger = new Logger( - $this->connection->reveal(), - 'my-log', - 'my-awesome-project' - ); - $this->psr = new PsrLoggerStub($logger); + + $this->psr = TestHelpers::stub(PsrLogger::class, [ + $this->refreshLogger($this->connection->reveal()) + ], ['logger']); } public function testClass() @@ -65,7 +64,10 @@ public function testEmergency() return $args['entries'][0]['severity'] === Logger::EMERGENCY; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -79,7 +81,10 @@ public function testAlert() return $args['entries'][0]['severity'] === Logger::ALERT; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -93,7 +98,10 @@ public function testCritical() return $args['entries'][0]['severity'] === Logger::CRITICAL; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -107,7 +115,10 @@ public function testError() return $args['entries'][0]['severity'] === Logger::ERROR; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -121,7 +132,10 @@ public function testWarning() return $args['entries'][0]['severity'] === Logger::WARNING; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -135,7 +149,10 @@ public function testNotice() return $args['entries'][0]['severity'] === Logger::NOTICE; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -149,7 +166,10 @@ public function testInfo() return $args['entries'][0]['severity'] === Logger::INFO; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -163,7 +183,10 @@ public function testDebug() return $args['entries'][0]['severity'] === Logger::DEBUG; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -177,7 +200,10 @@ public function testLog() return $args['entries'][0]['severity'] === Logger::ALERT; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -188,12 +214,21 @@ public function testLogPlaceholder() $snippet->addLocal('psrLogger', $this->psr); $this->connection->writeEntries(Argument::that(function ($args) { - if ($args['entries'][0]['severity'] !== Logger::ALERT) return false; - if ($args['entries'][0]['jsonPayload']['message'] !== 'alert: my alert message') return false; + if ($args['entries'][0]['severity'] !== Logger::ALERT) { + return false; + } + + if ($args['entries'][0]['jsonPayload']['message'] !== 'alert: my alert message') { + return false; + } + return true; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } @@ -204,22 +239,28 @@ public function testLogStackdriver() $snippet->addLocal('psrLogger', $this->psr); $this->connection->writeEntries(Argument::that(function ($args) { - if ($args['entries'][0]['severity'] !== Logger::ALERT) return false; - if ($args['entries'][0]['httpRequest']['requestMethod'] !== 'GET') return false; + if ($args['entries'][0]['severity'] !== Logger::ALERT) { + return false; + } + + if ($args['entries'][0]['httpRequest']['requestMethod'] !== 'GET') { + return false; + } + return true; }))->shouldBeCalled(); - $this->psr->setConnection($this->connection->reveal()); + $this->psr->___setProperty( + 'logger', + $this->refreshLogger($this->connection->reveal()) + ); $snippet->invoke(); } -} -class PsrLoggerStub extends PsrLogger -{ - public function setConnection($connection) + private function refreshLogger(ConnectionInterface $connection) { - $this->logger = new Logger( + return new Logger( $connection, 'my-log', 'my-awesome-project' diff --git a/Logging/tests/Snippet/SinkTest.php b/Logging/tests/Snippet/SinkTest.php index afe304377c46..8e56b6f46a69 100644 --- a/Logging/tests/Snippet/SinkTest.php +++ b/Logging/tests/Snippet/SinkTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Logging\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Logging\Connection\ConnectionInterface; use Google\Cloud\Logging\Sink; use Prophecy\Argument; @@ -36,7 +37,7 @@ class SinkTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->sink = \Google\Cloud\Core\Testing\TestHelpers::stub(Sink::class, [ + $this->sink = TestHelpers::stub(Sink::class, [ $this->connection->reveal(), self::SINK, self::PROJECT diff --git a/Logging/tests/System/LoggingTestCase.php b/Logging/tests/System/LoggingTestCase.php index eb6d840fce87..ceca5d138724 100644 --- a/Logging/tests/System/LoggingTestCase.php +++ b/Logging/tests/System/LoggingTestCase.php @@ -83,5 +83,3 @@ public static function setUpBeforeClass() self::$hasSetUp = true; } } - - diff --git a/Logging/tests/Unit/LoggerTest.php b/Logging/tests/Unit/LoggerTest.php index b28209979d8c..09732c5e79b7 100644 --- a/Logging/tests/Unit/LoggerTest.php +++ b/Logging/tests/Unit/LoggerTest.php @@ -18,10 +18,10 @@ namespace Google\Cloud\Logging\Tests\Unit; use Google\Cloud\Core\Timestamp; -use Google\Cloud\Logging\Logger; use Google\Cloud\Logging\Connection\ConnectionInterface; -use Prophecy\Argument; +use Google\Cloud\Logging\Logger; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group logging @@ -93,20 +93,16 @@ public function testGetsEntriesWithoutToken() public function testGetsEntriesWithToken() { $this->connection->listEntries(Argument::any()) - ->willReturn( - [ - 'nextPageToken' => 'token', - 'entries' => [ - ['textPayload' => 'someOtherPayload'] - ] - ], - [ - 'entries' => [ - ['textPayload' => $this->textPayload] - ] + ->willReturn([ + 'nextPageToken' => 'token', + 'entries' => [ + ['textPayload' => 'someOtherPayload'] + ] + ], [ + 'entries' => [ + ['textPayload' => $this->textPayload] ] - ) - ->shouldBeCalledTimes(2); + ])->shouldBeCalledTimes(2); $logger = $this->getLogger($this->connection); $entries = iterator_to_array($logger->entries()); @@ -333,6 +329,7 @@ private function getLogger($connection, array $resource = null, array $labels = } } +//@codingStandardsIgnoreStart class LoggerStub extends Logger { private $time; @@ -347,3 +344,4 @@ protected function microtime() return $this->time ?: microtime(true); } } +//@codingStandardsIgnoreEnd diff --git a/Logging/tests/Unit/LoggingClientTest.php b/Logging/tests/Unit/LoggingClientTest.php index b8ec86c54bfc..bceca6cfaaba 100644 --- a/Logging/tests/Unit/LoggingClientTest.php +++ b/Logging/tests/Unit/LoggingClientTest.php @@ -21,16 +21,17 @@ use Google\Cloud\Core\Batch\OpisClosureSerializer; use Google\Cloud\Core\Report\EmptyMetadataProvider; use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; +use Google\Cloud\Logging\Connection\ConnectionInterface; use Google\Cloud\Logging\Connection\Grpc; use Google\Cloud\Logging\Logger; use Google\Cloud\Logging\LoggingClient; use Google\Cloud\Logging\Metric; use Google\Cloud\Logging\PsrLogger; use Google\Cloud\Logging\Sink; -use Google\Cloud\Logging\Connection\ConnectionInterface; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; use PHPUnit_Framework_Assert; +use Prophecy\Argument; /** * @group logging @@ -51,15 +52,18 @@ public function setUp() { $this->formattedProjectId = "projects/$this->projectId"; $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = new LoggingTestClient(['projectId' => $this->projectId]); + $this->client = TestHelpers::stub(LoggingClient::class, [ + [ + 'projectId' => $this->projectId + ] + ]); } public function testUsesGrpcConnectionByDefault() { $this->checkAndSkipGrpcTests(); - $client = new LoggingTestClient(['projectId' => 'project']); - $this->assertInstanceOf(Grpc::class, $client->getConnection()); + $this->assertInstanceOf(Grpc::class, $this->client->___getProperty('connection')); } public function testPsrBatchLogger() @@ -77,10 +81,14 @@ public function testPsrBatchLogger() $p = $r->getProperty('batchEnabled'); $p->setAccessible(true); $this->assertTrue($p->getValue($psrBatchLogger)); + $psrBatchLogger = LoggingClient::psrBatchLogger( 'app', - ['clientConfig' => ['projectId' => 'my-project']]); + ['clientConfig' => ['projectId' => 'my-project']] + ); + $this->assertInstanceOf(PsrLogger::class, $psrBatchLogger); + $r = new \ReflectionObject($psrBatchLogger); $method = $r->getMethod('getUnwrappedClientConfig'); $method->setAccessible(true); @@ -105,7 +113,7 @@ public function testCreatesSink() 'destination' => $destination ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $sink = $this->client->createSink($this->sinkName, $destination); @@ -115,7 +123,7 @@ public function testCreatesSink() public function testGetsSink() { - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $this->assertInstanceOf(Sink::class, $this->client->sink($this->sinkName)); } @@ -125,7 +133,7 @@ public function testGetsSinksWithNoResults() ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $sinks = iterator_to_array($this->client->sinks()); $this->assertEmpty($sinks); @@ -141,7 +149,7 @@ public function testGetsSinksWithoutToken() ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $sinks = iterator_to_array($this->client->sinks()); $this->assertEquals($this->sinkName, $sinks[0]->name()); @@ -150,22 +158,18 @@ public function testGetsSinksWithoutToken() public function testGetsSinksWithToken() { $this->connection->listSinks(Argument::any()) - ->willReturn( - [ - 'nextPageToken' => 'token', - 'sinks' => [ - ['name' => 'someOtherSink'] - ] - ], - [ - 'sinks' => [ - ['name' => $this->sinkName] - ] + ->willReturn([ + 'nextPageToken' => 'token', + 'sinks' => [ + ['name' => 'someOtherSink'] + ] + ], [ + 'sinks' => [ + ['name' => $this->sinkName] ] - ) - ->shouldBeCalledTimes(2); + ])->shouldBeCalledTimes(2); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $sinks = iterator_to_array($this->client->sinks()); $this->assertEquals($this->sinkName, $sinks[1]->name()); @@ -184,7 +188,7 @@ public function testCreatesMetric() 'filter' => $filter ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $metric = $this->client->createMetric($this->metricName, $filter); @@ -194,7 +198,7 @@ public function testCreatesMetric() public function testGetsMetric() { - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $this->assertInstanceOf(Metric::class, $this->client->metric($this->metricName)); } @@ -204,7 +208,7 @@ public function testGetsMetricsWithNoResults() ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $metrics = iterator_to_array($this->client->metrics()); $this->assertEmpty($metrics); @@ -220,7 +224,7 @@ public function testGetsMetricsWithoutToken() ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $metrics = iterator_to_array($this->client->metrics()); $this->assertEquals($this->metricName, $metrics[0]->name()); @@ -229,22 +233,18 @@ public function testGetsMetricsWithoutToken() public function testGetsMetricsWithToken() { $this->connection->listMetrics(Argument::any()) - ->willReturn( - [ - 'nextPageToken' => 'token', - 'metrics' => [ - ['name' => 'someOtherMetric'] - ] - ], - [ - 'metrics' => [ - ['name' => $this->metricName] - ] + ->willReturn([ + 'nextPageToken' => 'token', + 'metrics' => [ + ['name' => 'someOtherMetric'] ] - ) - ->shouldBeCalledTimes(2); + ], [ + 'metrics' => [ + ['name' => $this->metricName] + ] + ])->shouldBeCalledTimes(2); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $metrics = iterator_to_array($this->client->metrics()); $this->assertEquals($this->metricName, $metrics[1]->name()); @@ -262,7 +262,7 @@ public function testGetsEntriesWithNoResults() ->willReturn([]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $entries = iterator_to_array($this->client->entries(['projectIds' => [$secondProjectId]])); $this->assertEmpty($entries); @@ -278,7 +278,7 @@ public function testGetsEntriesWithoutToken() ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $entries = iterator_to_array($this->client->entries()); $this->assertEquals($this->textPayload, $entries[0]->info()['textPayload']); @@ -287,22 +287,18 @@ public function testGetsEntriesWithoutToken() public function testGetsEntriesWithToken() { $this->connection->listEntries(Argument::any()) - ->willReturn( - [ - 'nextPageToken' => 'token', - 'entries' => [ - ['textPayload' => 'someOtherPayload'] - ] - ], - [ - 'entries' => [ - ['textPayload' => $this->textPayload] - ] + ->willReturn([ + 'nextPageToken' => 'token', + 'entries' => [ + ['textPayload' => 'someOtherPayload'] + ] + ], [ + 'entries' => [ + ['textPayload' => $this->textPayload] ] - ) - ->shouldBeCalledTimes(2); + ])->shouldBeCalledTimes(2); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $entries = iterator_to_array($this->client->entries()); $this->assertEquals($this->textPayload, $entries[1]->info()['textPayload']); @@ -310,7 +306,7 @@ public function testGetsEntriesWithToken() public function testGetsPsrLogger() { - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $this->assertInstanceOf(PsrLogger::class, $this->client->psrLogger('myLogger')); } @@ -333,7 +329,7 @@ public function testOptionsArePassedToPsrLogger() 'debugOutputResource' => fopen('php://temp', 'wb') ]; - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $psrLogger = $this->client->psrLogger('myLogger', $options); foreach ($options as $name => $value) { @@ -347,20 +343,7 @@ public function testOptionsArePassedToPsrLogger() public function testGetsLogger() { - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $this->assertInstanceOf(Logger::class, $this->client->logger('myLogger')); } } - -class LoggingTestClient extends LoggingClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } - - public function getConnection() - { - return $this->connection; - } -} diff --git a/Logging/tests/Unit/PsrLoggerBatchTest.php b/Logging/tests/Unit/PsrLoggerBatchTest.php index 04db5a0e12b8..437036598673 100644 --- a/Logging/tests/Unit/PsrLoggerBatchTest.php +++ b/Logging/tests/Unit/PsrLoggerBatchTest.php @@ -98,22 +98,24 @@ public function testTraceIdLabelOnGAEFlex( } else { $server = ['HTTP_X_CLOUD_TRACE_CONTEXT' => $traceId]; } + $this->runner->submitItem( - 'stackdriver-logging-my-log', Argument::any() - ) - ->will(function($args) { - self::$logName = $args[0]; - self::$entry = $args[1]; - }) - ->shouldBeCalledTimes(1); - $this->runner->registerJob( - Argument::any(), Argument::any(), Argument::any() - )->willReturn(true); + 'stackdriver-logging-my-log', + Argument::any() + )->will(function ($args) { + self::$logName = $args[0]; + self::$entry = $args[1]; + })->shouldBeCalledTimes(1); + + $this->runner->registerJob(Argument::any(), Argument::any(), Argument::any()) + ->willReturn(true); + $logger = new Logger( $this->prophesize(Rest::class)->reveal(), self::LOG_NAME, 'my-project' ); + $psrBatchLogger = new PsrLogger( $logger, null, @@ -123,13 +125,16 @@ public function testTraceIdLabelOnGAEFlex( 'metadataProvider' => new GAEFlexMetadataProvider($server) ] ); + $psrBatchLogger->info( 'test log', ['stackdriverOptions' => ['labels' => $labels]] ); + $this->assertEquals('stackdriver-logging-my-log', self::$logName); $info = self::$entry->info(); $this->assertEquals($expectedLabels, $info['labels']); + if (!empty($traceId)) { $this->assertEquals($traceId, $info['trace']); } @@ -141,21 +146,22 @@ public function testTraceIdLabelOnGAEFlex( public function testWritesEntryWithLevels($level) { $this->runner->submitItem( - 'stackdriver-logging-my-log', Argument::any() - ) - ->will(function($args) { - self::$logName = $args[0]; - self::$entry = $args[1]; - }) - ->shouldBeCalledTimes(1); - $this->runner->registerJob( - Argument::any(), Argument::any(), Argument::any() - )->willReturn(true); + 'stackdriver-logging-my-log', + Argument::any() + )->will(function ($args) { + self::$logName = $args[0]; + self::$entry = $args[1]; + })->shouldBeCalledTimes(1); + + $this->runner->registerJob(Argument::any(), Argument::any(), Argument::any()) + ->willReturn(true); + $logger = new Logger( $this->prophesize(Rest::class)->reveal(), self::LOG_NAME, 'my-project' ); + $psrBatchLogger = new PsrLogger( $logger, null, @@ -232,5 +238,4 @@ public function levelProvider() ['DEBUG'] ]; } - } diff --git a/Logging/tests/Unit/PsrLoggerCompatibilityTest.php b/Logging/tests/Unit/PsrLoggerCompatibilityTest.php index f23c2ca983d7..0dcf6697ca8d 100644 --- a/Logging/tests/Unit/PsrLoggerCompatibilityTest.php +++ b/Logging/tests/Unit/PsrLoggerCompatibilityTest.php @@ -46,12 +46,14 @@ public function getLogger() ? strtolower($map[$entry['severity']]) : $entry['severity']; - self::$logs[] = sprintf('%s %s', + self::$logs[] = sprintf( + '%s %s', $severity, $entry['jsonPayload']['message'] ); }); - $logger = new Logger($connection->reveal(), 'my-log', 'projectId');; + + $logger = new Logger($connection->reveal(), 'my-log', 'projectId'); return new PsrLogger($logger); } diff --git a/PubSub/tests/Snippet/MessageTest.php b/PubSub/tests/Snippet/MessageTest.php index 4a9697ab24dd..8bf5360c8631 100644 --- a/PubSub/tests/Snippet/MessageTest.php +++ b/PubSub/tests/Snippet/MessageTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\PubSub\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Message; +use Google\Cloud\PubSub\PubSubClient; use Google\Cloud\PubSub\Subscription; use Prophecy\Argument; @@ -65,24 +67,21 @@ public function testClass() 'receivedMessages' => [ [ 'message' => [ - 'data' => base64_encode('hello world') + 'data' => 'hello world' ] ] ] ]); + $client = TestHelpers::stub(PubSubClient::class, [], [ + 'connection', 'encode' + ]); + $client->___setProperty('connection', $connection->reveal()); + $client->___setProperty('encode', false); + $snippet = $this->snippetFromClass(Message::class); - $snippet->addLocal('connectionStub', $connection->reveal()); - $snippet->insertAfterLine(2, '$reflection = new \ReflectionClass($pubsub); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($pubsub, $connectionStub); - $property->setAccessible(false); - $property = $reflection->getProperty(\'encode\'); - $property->setAccessible(true); - $property->setValue($pubsub, \'false\'); - $property->setAccessible(false);' - ); + $snippet->replace('$pubsub = new PubSubClient();', ''); + $snippet->addLocal('pubsub', $client); $res = $snippet->invoke('messages'); $this->assertContainsOnlyInstancesOf(Message::class, $res->returnVal()); diff --git a/PubSub/tests/Snippet/PubSubClientTest.php b/PubSub/tests/Snippet/PubSubClientTest.php index e17f930b1e35..35a9dfa738b5 100644 --- a/PubSub/tests/Snippet/PubSubClientTest.php +++ b/PubSub/tests/Snippet/PubSubClientTest.php @@ -19,8 +19,9 @@ use Google\Cloud\Core\Duration; use Google\Cloud\Core\Iterator\ItemIterator; -use Google\Cloud\Core\Timestamp; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; +use Google\Cloud\Core\Timestamp; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Message; use Google\Cloud\PubSub\PubSubClient; @@ -44,7 +45,7 @@ class PubSubClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(PubSubClient::class, [['transport' => 'rest']]); + $this->client = TestHelpers::stub(PubSubClient::class, [['transport' => 'rest']]); } public function testClassExample() diff --git a/PubSub/tests/Snippet/SnapshotTest.php b/PubSub/tests/Snippet/SnapshotTest.php index 42e75eefac68..c0c0bbe7d7e5 100644 --- a/PubSub/tests/Snippet/SnapshotTest.php +++ b/PubSub/tests/Snippet/SnapshotTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\PubSub\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Snapshot; use Google\Cloud\PubSub\Subscription; @@ -38,7 +39,7 @@ class SnapshotTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->snapshot = \Google\Cloud\Core\Testing\TestHelpers::stub(Snapshot::class, [ + $this->snapshot = TestHelpers::stub(Snapshot::class, [ $this->connection->reveal(), self::PROJECT, self::SNAPSHOT, diff --git a/PubSub/tests/Snippet/SubscriptionTest.php b/PubSub/tests/Snippet/SubscriptionTest.php index e0c7c15a2cb8..ef98c3ec3bfd 100644 --- a/PubSub/tests/Snippet/SubscriptionTest.php +++ b/PubSub/tests/Snippet/SubscriptionTest.php @@ -17,8 +17,9 @@ namespace Google\Cloud\PubSub\Tests\Snippet; -use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\Core\Iam\Iam; +use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Message; use Google\Cloud\PubSub\PubSubClient; @@ -40,7 +41,7 @@ class SubscriptionTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->subscription = \Google\Cloud\Core\Testing\TestHelpers::stub(Subscription::class, [ + $this->subscription = TestHelpers::stub(Subscription::class, [ $this->connection->reveal(), 'foo', self::SUBSCRIPTION, @@ -48,7 +49,7 @@ public function setUp() false ]); - $this->pubsub = \Google\Cloud\Core\Testing\TestHelpers::stub(PubSubClient::class, [['transport' => 'rest']]); + $this->pubsub = TestHelpers::stub(PubSubClient::class, [['transport' => 'rest']]); $this->pubsub->___setProperty('connection', $this->connection->reveal()); } diff --git a/PubSub/tests/Snippet/TopicTest.php b/PubSub/tests/Snippet/TopicTest.php index c83bf5641544..da5b22b0e4f9 100644 --- a/PubSub/tests/Snippet/TopicTest.php +++ b/PubSub/tests/Snippet/TopicTest.php @@ -18,13 +18,14 @@ namespace Google\Cloud\PubSub\Tests\Snippet; use Google\Cloud\Core\Iam\Iam; +use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; -use Google\Cloud\PubSub\Connection\ConnectionInterface; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\BatchPublisher; +use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\PubSubClient; use Google\Cloud\PubSub\Subscription; use Google\Cloud\PubSub\Topic; -use Google\Cloud\Core\Iterator\ItemIterator; use Prophecy\Argument; /** @@ -42,8 +43,8 @@ class TopicTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->pubsub = \Google\Cloud\Core\Testing\TestHelpers::stub(PubSubClient::class); - $this->topic = \Google\Cloud\Core\Testing\TestHelpers::stub(Topic::class, [ + $this->pubsub = TestHelpers::stub(PubSubClient::class); + $this->topic = TestHelpers::stub(Topic::class, [ $this->connection->reveal(), 'my-awesome-project', self::TOPIC, diff --git a/PubSub/tests/System/PubSubTestCase.php b/PubSub/tests/System/PubSubTestCase.php index e846dee8d7bd..235ac2b7b097 100644 --- a/PubSub/tests/System/PubSubTestCase.php +++ b/PubSub/tests/System/PubSubTestCase.php @@ -57,5 +57,3 @@ public static function setUpBeforeClass() self::$hasSetUp = true; } } - - diff --git a/PubSub/tests/Unit/BatchPublisherTest.php b/PubSub/tests/Unit/BatchPublisherTest.php index 08f9ebb2c042..15618405dbb3 100644 --- a/PubSub/tests/Unit/BatchPublisherTest.php +++ b/PubSub/tests/Unit/BatchPublisherTest.php @@ -54,14 +54,15 @@ public function testPublish() public function testGetCallback() { - $callbackArray = (new TestBatchPublisher(self::TOPIC_NAME, ['clientConfig' => ['projectId' => 'example_project']])) - ->getCallbackArray(); + $publisher = new TestBatchPublisher(self::TOPIC_NAME, ['clientConfig' => ['projectId' => 'example_project']]); + $callbackArray = $publisher->getCallbackArray(); $this->assertInstanceOf(Topic::class, $callbackArray[0]); $this->assertEquals('publishBatch', $callbackArray[1]); } } +//@codingStandardsIgnoreStart class TestBatchPublisher extends BatchPublisher { public function getCallbackArray() @@ -69,3 +70,4 @@ public function getCallbackArray() return $this->getCallback(); } } +//@codingStandardsIgnoreEnd diff --git a/PubSub/tests/Unit/IncomingMessageTraitTest.php b/PubSub/tests/Unit/IncomingMessageTraitTest.php index cc6811f40338..20f8cc0a1fd7 100644 --- a/PubSub/tests/Unit/IncomingMessageTraitTest.php +++ b/PubSub/tests/Unit/IncomingMessageTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\PubSub\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\IncomingMessageTrait; use Google\Cloud\PubSub\Message; @@ -28,20 +29,31 @@ */ class IncomingMessageTraitTest extends TestCase { + const PROJECT = 'my-project'; + + private $connection; private $stub; public function setUp() { - $this->stub = new IncomingMessageTraitStub($this->prophesize(ConnectionInterface::class)->reveal()); + $this->connection = $this->prophesize(ConnectionInterface::class); + $this->stub = TestHelpers::impl(IncomingMessageTrait::class); } public function testMessageFactory() { - $message = $this->stub->call([ + $data = [ 'message' => [ 'data' => 'hello world' ] - ]); + ]; + + $message = $this->stub->call( + 'messageFactory', + [ + $data, $this->connection->reveal(), self::PROJECT, false + ] + ); $this->assertInstanceOf(Message::class, $message); $this->assertEquals('hello world', $message->data()); @@ -52,47 +64,51 @@ public function testMessageFactory() */ public function testInvalidMessage() { - $this->stub->call([]); + $this->stub->call( + 'messageFactory', + [ + [], $this->connection->reveal(), self::PROJECT, false + ] + ); } public function testDecodeMessage() { - $message = $this->stub->call([ - 'message' => [ - 'data' => base64_encode('hello world') + $message = $this->stub->call( + 'messageFactory', + [ + [ + 'message' => [ + 'data' => base64_encode('hello world') + ] + ], + $this->connection->reveal(), + self::PROJECT, + true ] - ], true); + ); $this->assertEquals('hello world', $message->data()); } public function testMessageWithSubscription() { - $message = $this->stub->call([ - 'message' => [ - 'data' => base64_encode('hello world') - ], - 'subscription' => 'projects/project-id/subscriptions/foo' - ], true); + $message = $this->stub->call( + 'messageFactory', + [ + [ + 'message' => [ + 'data' => base64_encode('hello world') + ], + 'subscription' => 'projects/project-id/subscriptions/foo' + ], + $this->connection->reveal(), + self::PROJECT, + true + ] + ); $this->assertInstanceOf(Subscription::class, $message->subscription()); $this->assertEquals('projects/project-id/subscriptions/foo', $message->subscription()->name()); } } - -class IncomingMessageTraitStub -{ - use IncomingMessageTrait; - - private $connection; - - public function __construct($connection) - { - $this->connection = $connection; - } - - public function call($message, $encode = false) - { - return $this->messageFactory($message, $this->connection, 'project-id', $encode); - } -} diff --git a/PubSub/tests/Unit/PubSubClientTest.php b/PubSub/tests/Unit/PubSubClientTest.php index 9ee23156ebd6..6d26fd778fb2 100644 --- a/PubSub/tests/Unit/PubSubClientTest.php +++ b/PubSub/tests/Unit/PubSubClientTest.php @@ -19,6 +19,8 @@ use Google\Cloud\Core\Duration; use Google\Cloud\Core\Iterator\ItemIterator; +use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Connection\Grpc; @@ -28,9 +30,8 @@ use Google\Cloud\PubSub\Snapshot; use Google\Cloud\PubSub\Subscription; use Google\Cloud\PubSub\Topic; -use Google\Cloud\Core\Testing\GrpcTestTrait; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group pubsub @@ -47,18 +48,22 @@ public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = new PubSubClientStub([ - 'projectId' => 'project', - 'transport' => 'rest' + $this->client = TestHelpers::stub(PubSubClient::class, [ + [ + 'projectId' => 'project', + 'transport' => 'rest' + ] ]); } public function testUsesGrpcConnectionByDefault() { $this->checkAndSkipGrpcTests(); - $client = new PubSubClientStub(['projectId' => 'project']); + $client = TestHelpers::stub(PubSubClient::class, [ + ['projectId' => 'project'] + ]); - $this->assertInstanceOf(Grpc::class, $client->getConnection()); + $this->assertInstanceOf(Grpc::class, $client->___getProperty('connection')); } public function testCreateTopic() @@ -73,7 +78,7 @@ public function testCreateTopic() // Set this to zero to make sure we're getting the cached result $this->connection->getTopic(Argument::any())->shouldNotBeCalled(); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $topic = $this->client->createTopic($topicName, [ 'foo' => 'bar' @@ -94,7 +99,7 @@ public function testTopic() 'name' => 'projects/project/topics/'. $topicName ])->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $topic = $this->client->topic($topicName); @@ -121,7 +126,7 @@ public function testTopics() 'topics' => $topicResult ])->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $topics = $this->client->topics([ 'foo' => 'bar' @@ -148,19 +153,21 @@ public function testTopicsPaged() ] ]; - $this->connection->listTopics(Argument::that(function ($options) { - if ($options['foo'] !== 'bar') return false; - if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { - return false; - } + $this->connection->listTopics(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::that(function ($options) { + if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { + return false; + } - return true; - }))->willReturn([ + return true; + }) + ))->willReturn([ 'topics' => $topicResult, 'nextPageToken' => 'foo' ])->shouldBeCalledTimes(2); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $topics = $this->client->topics([ 'foo' => 'bar' @@ -172,7 +179,9 @@ public function testTopicsPaged() foreach ($topics as $topic) { $i++; $arr[] = $topic; - if ($i == 6) break; + if ($i == 6) { + break; + } } $this->assertCount(6, $arr); @@ -187,7 +196,7 @@ public function testSubscribe() $this->connection->getSubscription()->shouldNotBeCalled(); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $subscription = $this->client->subscribe('subscription', 'topic', [ 'foo' => 'bar' @@ -199,9 +208,11 @@ public function testSubscribe() public function testSubscription() { - $this->connection->getSubscription(Argument::any())->shouldBeCalledTimes(1)->willReturn(['foo' => 'bar']); + $this->connection->getSubscription(Argument::any()) + ->shouldBeCalledTimes(1) + ->willReturn(['foo' => 'bar']); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $subscription = $this->client->subscription('subscription-name', 'topic-name'); @@ -232,7 +243,7 @@ public function testSubscriptions() 'subscriptions' => $subscriptionResult ])->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $subscriptions = $this->client->subscriptions([ 'foo' => 'bar' @@ -262,19 +273,21 @@ public function testSubscriptionsPaged() ] ]; - $this->connection->listSubscriptions(Argument::that(function ($options) { - if ($options['foo'] !== 'bar') return false; - if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { - return false; - } + $this->connection->listSubscriptions(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::that(function ($options) { + if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { + return false; + } - return true; - }))->willReturn([ + return true; + }) + ))->willReturn([ 'subscriptions' => $subscriptionResult, 'nextPageToken' => 'foo' ])->shouldBeCalledTimes(2); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $subscriptions = $this->client->subscriptions([ 'foo' => 'bar' @@ -286,7 +299,9 @@ public function testSubscriptionsPaged() foreach ($subscriptions as $subscription) { $i++; $arr[] = $subscription; - if ($i == 6) break; + if ($i == 6) { + break; + } } $this->assertCount(6, $arr); @@ -298,7 +313,7 @@ public function testCreateSnapshot() ->shouldBeCalled() ->willReturn([]); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $subscription = $this->client->subscription('bar'); @@ -331,7 +346,7 @@ public function testSnapshots() 'snapshots' => $snapshotResult ])->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $snapshots = $this->client->snapshots([ 'foo' => 'bar' @@ -358,19 +373,21 @@ public function testSnapshotsPaged() ] ]; - $this->connection->listSnapshots(Argument::that(function ($options) { - if ($options['foo'] !== 'bar') return false; - if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { - return false; - } + $this->connection->listSnapshots(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::that(function ($options) { + if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { + return false; + } - return true; - }))->willReturn([ + return true; + }) + ))->willReturn([ 'snapshots' => $snapshotResult, 'nextPageToken' => 'foo' ])->shouldBeCalledTimes(2); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $snapshots = $this->client->snapshots([ 'foo' => 'bar' @@ -382,7 +399,9 @@ public function testSnapshotsPaged() foreach ($snapshots as $snapshot) { $i++; $arr[] = $snapshot; - if ($i == 6) break; + if ($i == 6) { + break; + } } $this->assertCount(6, $arr); @@ -416,16 +435,3 @@ public function testDuration() $this->assertEquals($dur->get(), $val); } } - -class PubSubClientStub extends PubSubClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } - - public function getConnection() - { - return $this->connection; - } -} diff --git a/PubSub/tests/Unit/ResourceNameTraitTest.php b/PubSub/tests/Unit/ResourceNameTraitTest.php index 22b5cf804bd6..d99ddebc51ee 100644 --- a/PubSub/tests/Unit/ResourceNameTraitTest.php +++ b/PubSub/tests/Unit/ResourceNameTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\PubSub\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\ResourceNameTrait; use PHPUnit\Framework\TestCase; @@ -29,7 +30,7 @@ class ResourceNameTraitTest extends TestCase public function setUp() { - $this->trait = new ResourceNameTraitStub; + $this->trait = TestHelpers::impl(ResourceNameTrait::class); } public function testPluckProjectId() @@ -146,13 +147,3 @@ public function testIsFullyQualifiedNameInvalidType() $this->trait->call('isFullyQualifiedName', ['lame', 'foo']); } } - -class ResourceNameTraitStub -{ - use ResourceNameTrait; - - public function call($method, array $args) - { - return call_user_func_array([$this, $method], $args); - } -} diff --git a/PubSub/tests/Unit/SnapshotTest.php b/PubSub/tests/Unit/SnapshotTest.php index 7552ca34c398..a6eee55d8d33 100644 --- a/PubSub/tests/Unit/SnapshotTest.php +++ b/PubSub/tests/Unit/SnapshotTest.php @@ -17,12 +17,13 @@ namespace Google\Cloud\Tests\Unit\Pubsub; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Snapshot; use Google\Cloud\PubSub\Subscription; use Google\Cloud\PubSub\Topic; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group pubsub @@ -30,7 +31,7 @@ class SnapshotTest extends TestCase { const PROJECT = 'my-project'; - const NAME = 'snapshot'; + const SNAPSHOT_ID = 'snapshot'; private $connection; private $snapshot; @@ -38,50 +39,43 @@ class SnapshotTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->snapshot = new SnapshotStub( + $this->snapshot = TestHelpers::stub(Snapshot::class, [ $this->connection->reveal(), self::PROJECT, - self::NAME, + self::SNAPSHOT_ID, false - ); + ], ['connection', 'info']); } public function testConstructWithFullyQualifiedName() { - $snapshot = new SnapshotStub( + $snapshot = TestHelpers::stub(Snapshot::class, [ $this->connection->reveal(), self::PROJECT, - 'projects/'. self::PROJECT .'/snapshots/'. self::NAME, + 'projects/'. self::PROJECT .'/snapshots/'. self::SNAPSHOT_ID, false - ); + ]); $this->assertEquals($this->snapshot->name(), $snapshot->name()); } public function testName() { - $this->assertEquals('projects/'. self::PROJECT .'/snapshots/'. self::NAME, $this->snapshot->name()); + $this->assertEquals('projects/'. self::PROJECT .'/snapshots/'. self::SNAPSHOT_ID, $this->snapshot->name()); } public function testInfo() { - $snapshot = new SnapshotStub( - $this->connection->reveal(), - self::PROJECT, - 'projects/'. self::PROJECT .'/snapshots/'. self::NAME, - false, - [ - 'subscription' => 'foo', - 'topic' => 'bar', - ] - ); - - $this->assertEquals([ - 'name' => 'projects/'. self::PROJECT .'/snapshots/'. self::NAME, + $info = [ + 'name' => 'projects/'. self::PROJECT .'/snapshots/'. self::SNAPSHOT_ID, 'subscription' => 'foo', 'topic' => 'bar', 'expirationTime' => null - ], $snapshot->info()); + ]; + + $this->snapshot->___setProperty('info', $info); + + $this->assertEquals($info, $this->snapshot->info()); } public function testCreate() @@ -89,17 +83,15 @@ public function testCreate() $this->connection->createSnapshot(Argument::any()) ->shouldBeCalled(); - $snapshot = new SnapshotStub( - $this->connection->reveal(), - self::PROJECT, - 'projects/'. self::PROJECT .'/snapshots/'. self::NAME, - false, - [ - 'subscription' => 'foo', - ] - ); - - $snapshot->create(); + $info = [ + 'subscription' => 'foo', + ]; + + $this->snapshot->___setProperty('info', $info); + + $this->snapshot->___setProperty('connection', $this->connection->reveal()); + + $this->snapshot->create(); } /** @@ -113,10 +105,10 @@ public function testCreateWithoutSubscription() public function testDelete() { $this->connection->deleteSnapshot([ - 'snapshot' => 'projects/'. self::PROJECT .'/snapshots/'. self::NAME + 'snapshot' => 'projects/'. self::PROJECT .'/snapshots/'. self::SNAPSHOT_ID ]); - $this->snapshot->setConnection($this->connection->reveal()); + $this->snapshot->___setProperty('connection', $this->connection->reveal()); $this->snapshot->delete(); } @@ -128,17 +120,11 @@ public function testTopicNull() public function testTopic() { - $snapshot = new SnapshotStub( - $this->connection->reveal(), - self::PROJECT, - 'projects/'. self::PROJECT .'/snapshots/'. self::NAME, - false, - [ - 'topic' => 'foo', - ] - ); - - $this->assertInstanceOf(Topic::class, $snapshot->topic()); + $this->snapshot->___setProperty('info', [ + 'topic' => 'foo', + ]); + + $this->assertInstanceOf(Topic::class, $this->snapshot->topic()); } public function testSubscriptionNull() @@ -148,24 +134,10 @@ public function testSubscriptionNull() public function testSubscription() { - $snapshot = new SnapshotStub( - $this->connection->reveal(), - self::PROJECT, - 'projects/'. self::PROJECT .'/snapshots/'. self::NAME, - false, - [ - 'subscription' => 'foo', - ] - ); - - $this->assertInstanceOf(Subscription::class, $snapshot->subscription()); - } -} + $this->snapshot->___setProperty('info', [ + 'subscription' => 'foo', + ]); -class SnapshotStub extends Snapshot -{ - public function setConnection($c) - { - $this->connection = $c; + $this->assertInstanceOf(Subscription::class, $this->snapshot->subscription()); } } diff --git a/PubSub/tests/Unit/SubscriptionTest.php b/PubSub/tests/Unit/SubscriptionTest.php index 1ed4dd247bd2..83a932c4a4af 100644 --- a/PubSub/tests/Unit/SubscriptionTest.php +++ b/PubSub/tests/Unit/SubscriptionTest.php @@ -20,55 +20,60 @@ use Google\Cloud\Core\Exception\NotFoundException; use Google\Cloud\Core\Iam\Iam; use Google\Cloud\Core\Iterator\ItemIterator; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Message; use Google\Cloud\PubSub\Snapshot; use Google\Cloud\PubSub\Subscription; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group pubsub */ class SubscriptionTest extends TestCase { + const PROJECT = 'project-id'; + const SUBSCRIPTION = 'projects/project-id/subscriptions/subscription-name'; + const TOPIC = 'projects/project-id/topics/topic-name'; + private $subscription; private $connection; public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->subscription = new SubscriptionStub( + $this->subscription = TestHelpers::stub(Subscription::class, [ $this->connection->reveal(), 'project-id', 'subscription-name', 'topic-name', true - ); + ], ['connection', 'info']); } public function testName() { - $this->assertEquals($this->subscription->name(), 'projects/project-id/subscriptions/subscription-name'); + $this->assertEquals($this->subscription->name(), self::SUBSCRIPTION); } public function testCreate() { $this->connection->createSubscription(Argument::withEntry('foo', 'bar')) ->willReturn([ - 'name' => 'projects/project-id/subscriptions/subscription-name', - 'topic' => 'projects/project-id/topics/topic-name' + 'name' => self::SUBSCRIPTION, + 'topic' => self::TOPIC ])->shouldBeCalledTimes(1); $this->connection->getSubscription()->shouldNotBeCalled(); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $sub = $this->subscription->create([ 'foo' => 'bar' ]); - $this->assertEquals($sub['name'], 'projects/project-id/subscriptions/subscription-name'); - $this->assertEquals($sub['topic'], 'projects/project-id/topics/topic-name'); + $this->assertEquals($sub['name'], self::SUBSCRIPTION); + $this->assertEquals($sub['topic'], self::TOPIC); } /** @@ -101,7 +106,7 @@ public function testUpdate() ->shouldBeCalled() ->willReturn($argsWithName); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $res = $this->subscription->update($args); @@ -115,7 +120,7 @@ public function testDelete() ->willReturn(null) ->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $res = $this->subscription->delete([ 'foo' => 'bar' ]); @@ -126,11 +131,11 @@ public function testExists() { $this->connection->getSubscription(Argument::withEntry('foo', 'bar')) ->willReturn([ - 'subscription' => 'projects/project-id/subscriptions/subscription-name', - 'topic' => 'projects/project-id/topics/topic-name' + 'subscription' => self::SUBSCRIPTION, + 'topic' => self::TOPIC ])->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $this->assertTrue($this->subscription->exists([ 'foo' => 'bar' ])); } @@ -141,7 +146,7 @@ public function testExistsNotFound() ->willThrow(new NotFoundException('bad')) ->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $this->assertFalse($this->subscription->exists()); } @@ -149,15 +154,15 @@ public function testExistsNotFound() public function testInfo() { $sub = [ - 'subscription' => 'projects/project-id/subscriptions/subscription-name', - 'topic' => 'projects/project-id/topics/topic-name' + 'subscription' => self::SUBSCRIPTION, + 'topic' => self::TOPIC ]; $this->connection->getSubscription(Argument::withEntry('foo', 'bar')) ->willReturn($sub) ->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $res = $this->subscription->info([ 'foo' => 'bar' ]); $this->assertEquals($res, $sub); @@ -166,37 +171,31 @@ public function testInfo() public function testInfoNoRequest() { $sub = [ - 'subscription' => 'projects/project-id/subscriptions/subscription-name', - 'topic' => 'projects/project-id/topics/topic-name' + 'subscription' => self::SUBSCRIPTION, + 'topic' => self::TOPIC ]; $this->connection->getSubscription()->shouldNotBeCalled(); - $subscription = new Subscription( - $this->connection->reveal(), - 'project-id', - 'subscription-name', - 'topic-name', - true, - $sub - ); + $this->subscription->___setProperty('info', $sub); + $this->subscription->___setProperty('connection', $this->connection->reveal()); - $res = $subscription->info(); + $res = $this->subscription->info(); $this->assertEquals($res, $sub); } public function testReload() { $sub = [ - 'subscription' => 'projects/project-id/subscriptions/subscription-name', - 'topic' => 'projects/project-id/topics/topic-name' + 'subscription' => self::SUBSCRIPTION, + 'topic' => self::TOPIC ]; $this->connection->getSubscription(Argument::withEntry('foo', 'bar')) ->willReturn($sub) ->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $res = $this->subscription->reload([ 'foo' => 'bar' ]); $this->assertEquals($res, $sub); @@ -218,7 +217,7 @@ public function testPull() ->willReturn($messages) ->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $result = $this->subscription->pull([ 'foo' => 'bar' @@ -241,16 +240,13 @@ public function testPullWithCustomArgs() ] ]; - $this->connection->pull(Argument::that(function ($args) { - if ($args['foo'] !== 'bar') return false; - if ($args['returnImmediately'] !== true) return false; - if ($args['maxMessages'] !== 2) return false; - - return true; - }))->willReturn($messages) - ->shouldBeCalledTimes(1); + $this->connection->pull(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::withEntry('returnImmediately', true), + Argument::withEntry('maxMessages', 2) + ))->willReturn($messages)->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $result = $this->subscription->pull([ 'foo' => 'bar', @@ -267,14 +263,12 @@ public function testAcknowledge() { $ackId = 'foobar'; - $this->connection->acknowledge(Argument::that(function ($args) use ($ackId) { - if ($args['foo'] !== 'bar') return false; - if ($args['ackIds'] !== [$ackId]) return false; + $this->connection->acknowledge(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::withEntry('ackIds', [$ackId]) + ))->shouldBeCalledTimes(1); - return true; - }))->shouldBeCalledTimes(1); - - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $message = new Message([], ['ackId' => $ackId]); $this->subscription->acknowledge($message, ['foo' => 'bar']); @@ -292,14 +286,12 @@ public function testAcknowledgeBatch() $messages[] = new Message([], ['ackId' => $id]); } - $this->connection->acknowledge(Argument::that(function ($args) use ($ackIds) { - if ($args['foo'] !== 'bar') return false; - if ($args['ackIds'] !== $ackIds) return false; - - return true; - }))->shouldBeCalledTimes(1); + $this->connection->acknowledge(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::withEntry('ackIds', $ackIds) + ))->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $this->subscription->acknowledgeBatch($messages, ['foo' => 'bar']); } @@ -316,18 +308,17 @@ public function testModifyAckDeadline() { $ackId = 'foobar'; $message = new Message([], ['ackId' => $ackId]); + $seconds = 100; - $this->connection->modifyAckDeadline(Argument::that(function ($args) use ($ackId) { - if ($args['foo'] !== 'bar') return false; - if ($args['ackIds'] !== [$ackId]) return false; - if ($args['ackDeadlineSeconds'] !== 100) return false; - - return true; - }))->shouldBeCalledTimes(1); + $this->connection->modifyAckDeadline(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::withEntry('ackIds', [$ackId]), + Argument::withEntry('ackDeadlineSeconds', $seconds) + ))->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); - $this->subscription->modifyAckDeadline($message, 100, ['foo' => 'bar']); + $this->subscription->modifyAckDeadline($message, $seconds, ['foo' => 'bar']); } public function testModifyAckDeadlineBatch() @@ -344,15 +335,13 @@ public function testModifyAckDeadlineBatch() $seconds = 100; - $this->connection->modifyAckDeadline(Argument::that(function ($args) use ($ackIds, $seconds) { - if ($args['foo'] !== 'bar') return false; - if ($args['ackIds'] !== $ackIds) return false; - if ($args['ackDeadlineSeconds'] !== $seconds) return false; - - return true; - }))->shouldBeCalledTimes(1); + $this->connection->modifyAckDeadline(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::withEntry('ackIds', $ackIds), + Argument::withEntry('ackDeadlineSeconds', $seconds) + ))->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $this->subscription->modifyAckDeadlineBatch($messages, $seconds, ['foo' => 'bar']); } @@ -371,14 +360,12 @@ public function testModifyPushConfig() 'hello' => 'world' ]; - $this->connection->modifyPushConfig(Argument::that(function ($args) use ($config) { - if ($args['foo'] !== 'bar') return false; - if ($args['pushConfig'] !== $config) return false; - - return true; - }))->shouldBeCalledTimes(1); + $this->connection->modifyPushConfig(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::withEntry('pushConfig', $config) + ))->shouldBeCalledTimes(1); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $this->subscription->modifyPushConfig($config, ['foo' => 'bar']); } @@ -393,7 +380,7 @@ public function testSeekToTime() 'time' => $timestamp->formatAsString() ])->shouldBeCalled()->willReturn('foo'); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $res = $this->subscription->seekToTime($timestamp); $this->assertEquals('foo', $res); @@ -411,7 +398,7 @@ public function testSeekToSnapshot() 'snapshot' => $snapshot->name() ])->shouldBeCalled()->willReturn('foo'); - $this->subscription->setConnection($this->connection->reveal()); + $this->subscription->___setProperty('connection', $this->connection->reveal()); $res = $this->subscription->seekToSnapshot($snapshot); $this->assertEquals('foo', $res); @@ -422,11 +409,3 @@ public function testIam() $this->assertInstanceOf(Iam::class, $this->subscription->iam()); } } - -class SubscriptionStub extends Subscription -{ - public function setConnection($connection) - { - $this->connection = $connection; - } -} diff --git a/PubSub/tests/Unit/TopicTest.php b/PubSub/tests/Unit/TopicTest.php index f079122b2f52..a97caf77df01 100644 --- a/PubSub/tests/Unit/TopicTest.php +++ b/PubSub/tests/Unit/TopicTest.php @@ -20,12 +20,13 @@ use Google\Cloud\Core\Exception\NotFoundException; use Google\Cloud\Core\Iam\Iam; use Google\Cloud\Core\Iterator\ItemIterator; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\BatchPublisher; use Google\Cloud\PubSub\Connection\ConnectionInterface; use Google\Cloud\PubSub\Subscription; use Google\Cloud\PubSub\Topic; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group pubsub @@ -38,12 +39,12 @@ class TopicTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->topic = new TopicStub( + $this->topic = TestHelpers::stub(Topic::class, [ $this->connection->reveal(), 'project-name', 'topic-name', true - ); + ]); } public function testName() @@ -60,7 +61,7 @@ public function testCreate() $this->connection->getTopic()->shouldNotBeCalled(); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $res = $this->topic->create(['foo' => 'bar']); @@ -75,7 +76,7 @@ public function testDelete() $this->connection->deleteTopic(Argument::withEntry('foo', 'bar')) ->shouldBeCalled(); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $res = $this->topic->delete(['foo' => 'bar']); } @@ -87,7 +88,7 @@ public function testExists() 'name' => 'projects/project-name/topics/topic-name' ]); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $this->assertTrue($this->topic->exists(['foo' => 'bar'])); } @@ -97,7 +98,7 @@ public function testExistsReturnsFalse() $this->connection->getTopic(Argument::withEntry('foo', 'bar')) ->willThrow(new NotFoundException('uh oh')); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $this->assertFalse($this->topic->exists(['foo' => 'bar'])); } @@ -109,7 +110,7 @@ public function testInfo() 'name' => 'projects/project-name/topics/topic-name' ])->shouldBeCalledTimes(1); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $res = $this->topic->info(['foo' => 'bar']); $res2 = $this->topic->info(); @@ -125,7 +126,7 @@ public function testReload() 'name' => 'projects/project-name/topics/topic-name' ]); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $res = $this->topic->reload(['foo' => 'bar']); @@ -145,15 +146,16 @@ public function testPublish() 'message1id' ]; - $this->connection->publishMessage(Argument::that(function ($options) use ($message) { - if ($options['foo'] !== 'bar') return false; + $this->connection->publishMessage(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::that(function ($options) use ($message) { + $message['data'] = base64_encode($message['data']); - $message['data'] = base64_encode($message['data']); + return $options['messages'] === [$message]; + }) + ))->willReturn($ids); - return $options['messages'] === [$message]; - }))->willReturn($ids); - - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $res = $this->topic->publish($message, ['foo' => 'bar']); @@ -181,16 +183,17 @@ public function testPublishBatch() 'message2id' ]; - $this->connection->publishMessage(Argument::that(function ($options) use ($messages) { - if ($options['foo'] !== 'bar') return false; - - $messages[0]['data'] = base64_encode($messages[0]['data']); - $messages[1]['data'] = base64_encode($messages[1]['data']); + $this->connection->publishMessage(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::that(function ($options) use ($messages) { + $messages[0]['data'] = base64_encode($messages[0]['data']); + $messages[1]['data'] = base64_encode($messages[1]['data']); - return $options['messages'] === $messages; - }))->willReturn($ids); + return $options['messages'] === $messages; + }) + ))->willReturn($ids); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $res = $this->topic->publishBatch($messages, ['foo' => 'bar']); @@ -206,18 +209,16 @@ public function testPublishBatchUnencoded() ] ]; - $this->connection->publishMessage(Argument::that(function ($options) use ($message) { - if ($options['foo'] !== 'bar') return false; - - if ($options['messages'] !== [$message]) return false; - - // If the message was encoded, this will fail the test. - if ($options['messages'][0]['data'] !== $message['data']) return false; + $this->connection->publishMessage(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::withEntry('messages', [$message]), + Argument::that(function ($options) use ($message) { + // If the message was encoded, this will fail the test. + return $options['messages'][0]['data'] === $message['data']; + }) + )); - return true; - })); - - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $res = $this->topic->publishBatch([$message], ['foo' => 'bar', 'encode' => false]); } @@ -233,7 +234,7 @@ public function testPublishMalformedMessage() $this->connection->publishMessage(Argument::any()); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $this->topic->publishBatch([$message]); } @@ -257,7 +258,7 @@ public function testSubscribe() ->willReturn($subscriptionData) ->shouldBeCalledTimes(1); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $subscription = $this->topic->subscribe('subscription-name', ['foo' => 'bar']); @@ -284,7 +285,7 @@ public function testSubscriptions() 'subscriptions' => $subscriptionResult ])->shouldBeCalledTimes(1); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $subscriptions = $this->topic->subscriptions([ 'foo' => 'bar' @@ -307,19 +308,21 @@ public function testSubscriptionsPaged() 'projects/project-name/subscriptions/subscription-c', ]; - $this->connection->listSubscriptionsByTopic(Argument::that(function ($options) { - if ($options['foo'] !== 'bar') return false; - if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { - return false; - } + $this->connection->listSubscriptionsByTopic(Argument::allOf( + Argument::withEntry('foo', 'bar'), + Argument::that(function ($options) { + if (isset($options['pageToken']) && $options['pageToken'] !== 'foo') { + return false; + } - return true; - }))->willReturn([ + return true; + }) + ))->willReturn([ 'subscriptions' => $subscriptionResult, 'nextPageToken' => 'foo' ])->shouldBeCalledTimes(2); - $this->topic->setConnection($this->connection->reveal()); + $this->topic->___setProperty('connection', $this->connection->reveal()); $subscriptions = $this->topic->subscriptions([ 'foo' => 'bar' @@ -331,7 +334,9 @@ public function testSubscriptionsPaged() foreach ($subscriptions as $subscription) { $i++; $arr[] = $subscription; - if ($i == 6) break; + if ($i == 6) { + break; + } } $this->assertCount(6, $arr); @@ -342,11 +347,3 @@ public function testIam() $this->assertInstanceOf(Iam::class, $this->topic->iam()); } } - -class TopicStub extends Topic -{ - public function setConnection($connection) - { - $this->connection = $connection; - } -} diff --git a/Spanner/tests/Snippet/ArrayTypeTest.php b/Spanner/tests/Snippet/ArrayTypeTest.php index 98b9d981bd8f..58baf0f72242 100644 --- a/Spanner/tests/Snippet/ArrayTypeTest.php +++ b/Spanner/tests/Snippet/ArrayTypeTest.php @@ -21,6 +21,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\ArrayType; use Google\Cloud\Spanner\Connection\ConnectionInterface; @@ -64,7 +65,7 @@ public function setUp() ->willReturn(null); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->database = \Google\Cloud\Core\Testing\TestHelpers::stub(Database::class, [ + $this->database = TestHelpers::stub(Database::class, [ $this->connection->reveal(), $instance->reveal(), $this->prophesize(LongRunningConnectionInterface::class)->reveal(), diff --git a/Spanner/tests/Snippet/Batch/BatchClientTest.php b/Spanner/tests/Snippet/Batch/BatchClientTest.php index f17c0c897f63..176ea43814a3 100644 --- a/Spanner/tests/Snippet/Batch/BatchClientTest.php +++ b/Spanner/tests/Snippet/Batch/BatchClientTest.php @@ -39,13 +39,12 @@ class BatchClientTest extends SnippetTestCase { use GrpcTestTrait; + use SpannerOperationRefreshTrait; - const DATABASE = 'projects/example_project/instances/example_instance/databases/example_database'; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const DATABASE = 'projects/my-awesome-project/instances/my-instance/databases/my-database'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; const TRANSACTION = 'transaction-id'; - use SpannerOperationRefreshTrait; - private $connection; private $client; @@ -102,7 +101,7 @@ public function testPubSubExample() $pConnection = $this->prophesize(PubSubConnectionInterface::class); $pConnection->publishMessage(Argument::withEntry('messages', [$message1])) ->shouldBeCalled() - ->will(function() use ($message2) { + ->will(function () use ($message2) { $this->publishMessage(Argument::withEntry('messages', [$message2])) ->shouldBeCalled(); }); diff --git a/Spanner/tests/Snippet/Batch/BatchSnapshotTest.php b/Spanner/tests/Snippet/Batch/BatchSnapshotTest.php index aa10210d5f9c..02b95bdb162b 100644 --- a/Spanner/tests/Snippet/Batch/BatchSnapshotTest.php +++ b/Spanner/tests/Snippet/Batch/BatchSnapshotTest.php @@ -44,8 +44,8 @@ class BatchSnapshotTest extends SnippetTestCase use GrpcTestTrait; use SpannerOperationRefreshTrait; - const DATABASE = 'projects/example_project/instances/example_instance/databases/example_database'; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const DATABASE = 'projects/my-awesome-project/instances/my-instance/databases/my-database'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; const TRANSACTION = 'transaction-id'; private $connection; @@ -70,7 +70,10 @@ public function setUp() $this->snapshot = TestHelpers::stub(BatchSnapshot::class, [ new Operation($this->connection->reveal(), false), $this->session->reveal(), - ['id' => self::TRANSACTION, 'readTimestamp' => new Timestamp(\DateTime::createFromFormat('U', (string) $this->time))] + [ + 'id' => self::TRANSACTION, + 'readTimestamp' => new Timestamp(\DateTime::createFromFormat('U', (string) $this->time)) + ] ], ['operation', 'session']); } diff --git a/Spanner/tests/Snippet/Batch/QueryPartitionTest.php b/Spanner/tests/Snippet/Batch/QueryPartitionTest.php index 52c7d39cc287..46b948e429b7 100644 --- a/Spanner/tests/Snippet/Batch/QueryPartitionTest.php +++ b/Spanner/tests/Snippet/Batch/QueryPartitionTest.php @@ -36,8 +36,8 @@ class QueryPartitionTest extends SnippetTestCase use GrpcTestTrait; use PartitionSharedSnippetTestTrait; - const DATABASE = 'projects/example_project/instances/example_instance/databases/example_database'; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const DATABASE = 'projects/my-awesome-project/instances/my-instance/databases/my-database'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; const TRANSACTION = 'transaction-id'; private $className = QueryPartition::class; diff --git a/Spanner/tests/Snippet/Batch/ReadPartitionTest.php b/Spanner/tests/Snippet/Batch/ReadPartitionTest.php index b2e68c4d3ffb..8be9978d9dba 100644 --- a/Spanner/tests/Snippet/Batch/ReadPartitionTest.php +++ b/Spanner/tests/Snippet/Batch/ReadPartitionTest.php @@ -39,8 +39,8 @@ class ReadPartitionTest extends SnippetTestCase provideGetters as private getters; } - const DATABASE = 'projects/example_project/instances/example_instance/databases/example_database'; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const DATABASE = 'projects/my-awesome-project/instances/my-instance/databases/my-database'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; const TRANSACTION = 'transaction-id'; private $className = ReadPartition::class; diff --git a/Spanner/tests/Snippet/CommitTimestampTest.php b/Spanner/tests/Snippet/CommitTimestampTest.php index 3545c6ad2f4a..418b35d9930b 100644 --- a/Spanner/tests/Snippet/CommitTimestampTest.php +++ b/Spanner/tests/Snippet/CommitTimestampTest.php @@ -34,7 +34,7 @@ class CommitTimestampTest extends SnippetTestCase { use GrpcTestTrait; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; public function setUp() { diff --git a/Spanner/tests/Snippet/DatabaseTest.php b/Spanner/tests/Snippet/DatabaseTest.php index 341ef0aabab6..29a7803bec8f 100644 --- a/Spanner/tests/Snippet/DatabaseTest.php +++ b/Spanner/tests/Snippet/DatabaseTest.php @@ -24,6 +24,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Database\V1\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Connection\ConnectionInterface; @@ -72,7 +73,7 @@ public function setUp() ->willReturn(null); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->database = \Google\Cloud\Core\Testing\TestHelpers::stub(Database::class, [ + $this->database = TestHelpers::stub(Database::class, [ $this->connection->reveal(), $instance->reveal(), $this->prophesize(LongRunningConnectionInterface::class)->reveal(), @@ -421,8 +422,14 @@ public function testInsert() public function testInsertBatch() { $this->connection->commit(Argument::that(function ($args) { - if (!isset($args['mutations'][0]['insert'])) return false; - if (!isset($args['mutations'][1]['insert'])) return false; + if (!isset($args['mutations'][0]['insert'])) { + return false; + } + + if (!isset($args['mutations'][1]['insert'])) { + return false; + } + return true; }))->shouldBeCalled()->willReturn([ 'commitTimestamp' => (new Timestamp(new \DateTime))->formatAsString() @@ -454,8 +461,14 @@ public function testUpdate() public function testUpdateBatch() { $this->connection->commit(Argument::that(function ($args) { - if (!isset($args['mutations'][0]['update'])) return false; - if (!isset($args['mutations'][1]['update'])) return false; + if (!isset($args['mutations'][0]['update'])) { + return false; + } + + if (!isset($args['mutations'][1]['update'])) { + return false; + } + return true; }))->shouldBeCalled()->willReturn([ 'commitTimestamp' => (new Timestamp(new \DateTime))->formatAsString() @@ -487,8 +500,14 @@ public function testInsertOrUpdate() public function testInsertOrUpdateBatch() { $this->connection->commit(Argument::that(function ($args) { - if (!isset($args['mutations'][0]['insertOrUpdate'])) return false; - if (!isset($args['mutations'][1]['insertOrUpdate'])) return false; + if (!isset($args['mutations'][0]['insertOrUpdate'])) { + return false; + } + + if (!isset($args['mutations'][1]['insertOrUpdate'])) { + return false; + } + return true; }))->shouldBeCalled()->willReturn([ 'commitTimestamp' => (new Timestamp(new \DateTime))->formatAsString() @@ -520,8 +539,14 @@ public function testReplace() public function testReplaceBatch() { $this->connection->commit(Argument::that(function ($args) { - if (!isset($args['mutations'][0]['replace'])) return false; - if (!isset($args['mutations'][1]['replace'])) return false; + if (!isset($args['mutations'][0]['replace'])) { + return false; + } + + if (!isset($args['mutations'][1]['replace'])) { + return false; + } + return true; }))->shouldBeCalled()->willReturn([ 'commitTimestamp' => (new Timestamp(new \DateTime))->formatAsString() diff --git a/Spanner/tests/Snippet/InstanceConfigurationTest.php b/Spanner/tests/Snippet/InstanceConfigurationTest.php index 68bba77841a0..5cdd92570293 100644 --- a/Spanner/tests/Snippet/InstanceConfigurationTest.php +++ b/Spanner/tests/Snippet/InstanceConfigurationTest.php @@ -17,11 +17,12 @@ namespace Google\Cloud\Spanner\Tests\Snippet; +use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\InstanceConfiguration; -use Google\Cloud\Core\Testing\GrpcTestTrait; use Prophecy\Argument; /** @@ -43,7 +44,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->config = \Google\Cloud\Core\Testing\TestHelpers::stub(InstanceConfiguration::class, [ + $this->config = TestHelpers::stub(InstanceConfiguration::class, [ $this->connection->reveal(), self::PROJECT, self::CONFIG @@ -56,7 +57,10 @@ public function testClass() $res = $snippet->invoke('configuration'); $this->assertInstanceOf(InstanceConfiguration::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), $res->returnVal()->name()); + $this->assertEquals( + InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG), + $res->returnVal()->name() + ); } public function testName() diff --git a/Spanner/tests/Snippet/InstanceTest.php b/Spanner/tests/Snippet/InstanceTest.php index b10fd64abdaa..61e98a072172 100644 --- a/Spanner/tests/Snippet/InstanceTest.php +++ b/Spanner/tests/Snippet/InstanceTest.php @@ -21,14 +21,15 @@ use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\LongRunning\LongRunningConnectionInterface; use Google\Cloud\Core\LongRunning\LongRunningOperation; +use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Database\V1\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Database; use Google\Cloud\Spanner\Instance; use Google\Cloud\Spanner\InstanceConfiguration; -use Google\Cloud\Core\Testing\GrpcTestTrait; use Prophecy\Argument; /** @@ -51,7 +52,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->instance = \Google\Cloud\Core\Testing\TestHelpers::stub(Instance::class, [ + $this->instance = TestHelpers::stub(Instance::class, [ $this->connection->reveal(), $this->prophesize(LongRunningConnectionInterface::class)->reveal(), [], @@ -65,7 +66,10 @@ public function testClass() $snippet = $this->snippetFromClass(Instance::class); $res = $snippet->invoke('instance'); $this->assertInstanceOf(Instance::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->name()); + $this->assertEquals( + InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), + $res->returnVal()->name() + ); } /** diff --git a/Spanner/tests/Snippet/SnapshotTest.php b/Spanner/tests/Snippet/SnapshotTest.php index 65a6841db582..ec9254da738c 100644 --- a/Spanner/tests/Snippet/SnapshotTest.php +++ b/Spanner/tests/Snippet/SnapshotTest.php @@ -20,6 +20,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Database; use Google\Cloud\Spanner\KeySet; @@ -53,7 +54,7 @@ public function setUp() $operation = $this->prophesize(Operation::class); $session = $this->prophesize(Session::class); - $this->snapshot = \Google\Cloud\Core\Testing\TestHelpers::stub(Snapshot::class, [ + $this->snapshot = TestHelpers::stub(Snapshot::class, [ $operation->reveal(), $session->reveal(), [ diff --git a/Spanner/tests/Snippet/SpannerClientTest.php b/Spanner/tests/Snippet/SpannerClientTest.php index f59eaa058c38..d31254d61d2a 100644 --- a/Spanner/tests/Snippet/SpannerClientTest.php +++ b/Spanner/tests/Snippet/SpannerClientTest.php @@ -22,6 +22,7 @@ use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Batch\BatchClient; use Google\Cloud\Spanner\Bytes; @@ -57,7 +58,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(SpannerClient::class); + $this->client = TestHelpers::stub(SpannerClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } @@ -115,7 +116,10 @@ public function testInstanceConfiguration() $res = $snippet->invoke('configuration'); $this->assertInstanceOf(InstanceConfiguration::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::instanceConfigName(self::PROJECT, $configName), $res->returnVal()->name()); + $this->assertEquals( + InstanceAdminClient::instanceConfigName(self::PROJECT, $configName), + $res->returnVal()->name() + ); } /** @@ -147,7 +151,10 @@ public function testInstance() $res = $snippet->invoke('instance'); $this->assertInstanceOf(Instance::class, $res->returnVal()); - $this->assertEquals(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->name()); + $this->assertEquals( + InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), + $res->returnVal()->name() + ); } /** @@ -172,7 +179,10 @@ public function testInstances() $res = $snippet->invoke('instances'); $this->assertInstanceOf(ItemIterator::class, $res->returnVal()); $this->assertInstanceOf(Instance::class, $res->returnVal()->current()); - $this->assertEquals(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), $res->returnVal()->current()->name()); + $this->assertEquals( + InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE), + $res->returnVal()->current()->name() + ); } public function testConnect() diff --git a/Spanner/tests/Snippet/StructTypeTest.php b/Spanner/tests/Snippet/StructTypeTest.php index 490782d512b3..2379e5ac36f4 100644 --- a/Spanner/tests/Snippet/StructTypeTest.php +++ b/Spanner/tests/Snippet/StructTypeTest.php @@ -21,6 +21,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\ArrayType; use Google\Cloud\Spanner\Connection\ConnectionInterface; @@ -64,7 +65,7 @@ public function setUp() ->willReturn(null); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->database = \Google\Cloud\Core\Testing\TestHelpers::stub(Database::class, [ + $this->database = TestHelpers::stub(Database::class, [ $this->connection->reveal(), $instance->reveal(), $this->prophesize(LongRunningConnectionInterface::class)->reveal(), diff --git a/Spanner/tests/Snippet/StructValueTest.php b/Spanner/tests/Snippet/StructValueTest.php index 168f818c490c..4a41a18344e9 100644 --- a/Spanner/tests/Snippet/StructValueTest.php +++ b/Spanner/tests/Snippet/StructValueTest.php @@ -21,6 +21,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Database; @@ -63,7 +64,7 @@ public function setUp() ->willReturn(null); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->database = \Google\Cloud\Core\Testing\TestHelpers::stub(Database::class, [ + $this->database = TestHelpers::stub(Database::class, [ $this->connection->reveal(), $instance->reveal(), $this->prophesize(LongRunningConnectionInterface::class)->reveal(), diff --git a/Spanner/tests/Snippet/TransactionTest.php b/Spanner/tests/Snippet/TransactionTest.php index a0205915b59e..5d326eaf4d9f 100644 --- a/Spanner/tests/Snippet/TransactionTest.php +++ b/Spanner/tests/Snippet/TransactionTest.php @@ -20,6 +20,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Database; use Google\Cloud\Spanner\KeySet; @@ -52,7 +53,7 @@ public function setUp() $operation = $this->prophesize(Operation::class); $session = $this->prophesize(Session::class); - $this->transaction = \Google\Cloud\Core\Testing\TestHelpers::stub(Transaction::class, [ + $this->transaction = TestHelpers::stub(Transaction::class, [ $operation->reveal(), $session->reveal(), self::TRANSACTION diff --git a/Spanner/tests/Snippet/TransactionalReadMethodsTest.php b/Spanner/tests/Snippet/TransactionalReadMethodsTest.php index d952119121fa..79a299e5840f 100644 --- a/Spanner/tests/Snippet/TransactionalReadMethodsTest.php +++ b/Spanner/tests/Snippet/TransactionalReadMethodsTest.php @@ -54,7 +54,7 @@ class TransactionalReadMethodsTest extends SnippetTestCase const DATABASE = 'my-database'; const INSTANCE = 'my-instance'; const TRANSACTION = 'my-transaction'; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; private $connection; private $session; @@ -134,9 +134,17 @@ public function testExecuteWithParameterType($localName, $client, $snippet) $this->checkAndSkipGrpcTests(); $this->connection->executeStreamingSql(Argument::that(function ($arg) { - if (!isset($arg['params'])) return false; - if (!isset($arg['paramTypes'])) return false; - if ($arg['paramTypes']['timestamp']['code'] !== Database::TYPE_TIMESTAMP) return false; + if (!isset($arg['params'])) { + return false; + } + + if (!isset($arg['paramTypes'])) { + return false; + } + + if ($arg['paramTypes']['timestamp']['code'] !== Database::TYPE_TIMESTAMP) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->resultGenerator([ @@ -181,10 +189,21 @@ public function testExecuteWithEmptyArray($localName, $client, $snippet) $this->checkAndSkipGrpcTests(); $this->connection->executeStreamingSql(Argument::that(function ($arg) { - if (!isset($arg['params'])) return false; - if (!isset($arg['paramTypes'])) return false; - if ($arg['paramTypes']['emptyArrayOfIntegers']['code'] !== Database::TYPE_ARRAY) return false; - if ($arg['paramTypes']['emptyArrayOfIntegers']['arrayElementType']['code'] !== Database::TYPE_INT64) return false; + if (!isset($arg['params'])) { + return false; + } + + if (!isset($arg['paramTypes'])) { + return false; + } + + if ($arg['paramTypes']['emptyArrayOfIntegers']['code'] !== Database::TYPE_ARRAY) { + return false; + } + + if ($arg['paramTypes']['emptyArrayOfIntegers']['arrayElementType']['code'] !== Database::TYPE_INT64) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->resultGenerator([ @@ -456,7 +475,10 @@ private function setupBatch() return \Google\Cloud\Core\Testing\TestHelpers::stub(BatchSnapshot::class, [ new Operation($this->connection->reveal(), false), $this->session->reveal(), - ['id' => self::TRANSACTION, 'readTimestamp' => new Timestamp(\DateTime::createFromFormat('U', (string) time()))] + [ + 'id' => self::TRANSACTION, + 'readTimestamp' => new Timestamp(\DateTime::createFromFormat('U', (string) time())) + ] ], ['operation', 'session']); } diff --git a/Spanner/tests/System/AdminTest.php b/Spanner/tests/System/AdminTest.php index 5d559b66ab9c..923dee1fff8d 100644 --- a/Spanner/tests/System/AdminTest.php +++ b/Spanner/tests/System/AdminTest.php @@ -76,7 +76,7 @@ public function testDatabase() $db = $op->pollUntilComplete(); $this->assertInstanceOf(Database::class, $db); - self::$deletionQueue->add(function() use ($db) { + self::$deletionQueue->add(function () use ($db) { $db->drop(); }); diff --git a/Spanner/tests/System/LargeReadTest.php b/Spanner/tests/System/LargeReadTest.php index cd9211748e05..f40e7174fedc 100644 --- a/Spanner/tests/System/LargeReadTest.php +++ b/Spanner/tests/System/LargeReadTest.php @@ -29,7 +29,12 @@ class LargeReadTest extends SpannerTestCase private static $tableName; private static $row = []; - private static $data = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; + //@codingStandardsIgnoreStart + private static $data = [ + 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' + ]; + //@codingStandardsIgnoreEnd + private static $str = ''; const NUM = 40000; @@ -135,7 +140,7 @@ private static function randomBytes(&$str) private static function randomArrayOfStrings() { $res = []; - for ($i=0; $i <= rand(1,4); $i++) { + for ($i=0; $i <= rand(1, 4); $i++) { $res[] = self::randomString(); } @@ -145,7 +150,7 @@ private static function randomArrayOfStrings() private static function randomArrayOfBytes(&$str) { $res = []; - for ($i=0; $i <= rand(1,4); $i++) { + for ($i=0; $i <= rand(1, 4); $i++) { $res[] = self::randomBytes($str); } diff --git a/Spanner/tests/System/OperationsTest.php b/Spanner/tests/System/OperationsTest.php index 29cc0d08cff0..061c761bcf00 100644 --- a/Spanner/tests/System/OperationsTest.php +++ b/Spanner/tests/System/OperationsTest.php @@ -33,8 +33,8 @@ class OperationsTest extends SpannerTestCase public static function setUpBeforeClass() { - self::$id1 = rand(1000,9999); - self::$id2 = rand(1,999); + self::$id1 = rand(1000, 9999); + self::$id2 = rand(1, 999); self::$name1 = uniqid(self::TESTING_PREFIX); self::$name2 = uniqid(self::TESTING_PREFIX); diff --git a/Spanner/tests/System/QueryTest.php b/Spanner/tests/System/QueryTest.php index 90e087ff05ae..0113c07f9ff5 100644 --- a/Spanner/tests/System/QueryTest.php +++ b/Spanner/tests/System/QueryTest.php @@ -382,7 +382,9 @@ public function testBindDateParameterNull() public function testBindArrayOfType($value, $result = null, $resultType = null, callable $filter = null) { if (!$filter) { - $filter = function ($val) { return $val; }; + $filter = function ($val) { + return $val; + }; } $db = self::$database; @@ -615,7 +617,11 @@ function (array $res) { // timestamp (covers 52) [ - [new Timestamp(new \DateTime('2010-01-01')), new Timestamp(new \DateTime('2011-01-01')), new Timestamp(new \DateTime('2012-01-01'))], + [ + new Timestamp(new \DateTime('2010-01-01')), + new Timestamp(new \DateTime('2011-01-01')), + new Timestamp(new \DateTime('2012-01-01')) + ], ['2010-01-01', '2011-01-01', '2012-01-01'], Timestamp::class, function (array $res) { @@ -629,7 +635,11 @@ function (array $res) { // date (covers 55) [ - [new Date(new \DateTime('2010-01-01')), new Date(new \DateTime('2011-01-01')), new Date(new \DateTime('2012-01-01'))], + [ + new Date(new \DateTime('2010-01-01')), + new Date(new \DateTime('2011-01-01')), + new Date(new \DateTime('2012-01-01')) + ], ['2010-01-01', '2011-01-01', '2012-01-01'], Date::class, function (array $res) { diff --git a/Spanner/tests/System/ReadTest.php b/Spanner/tests/System/ReadTest.php index 7521ce7721c7..78eb60f49734 100644 --- a/Spanner/tests/System/ReadTest.php +++ b/Spanner/tests/System/ReadTest.php @@ -339,7 +339,7 @@ public function testReadWithLimit() { $db = self::$database; - $res = function($limit) use ($db) { + $res = function ($limit) use ($db) { $keyset = new KeySet(['all' => true]); return $db->read(self::$rangeTableName, $keyset, array_keys(self::$dataset[0]), [ 'limit' => $limit @@ -360,7 +360,7 @@ public function testReadOverIndexWithLimit() { $db = self::$database; - $res = function($limit) use ($db) { + $res = function ($limit) use ($db) { $keyset = new KeySet(['all' => true]); return $db->read(self::$rangeTableName, $keyset, array_keys(self::$dataset[0]), [ 'limit' => $limit, diff --git a/Spanner/tests/System/SpannerTestCase.php b/Spanner/tests/System/SpannerTestCase.php index e7f0aa2fe7d0..7e2ffae3e6f8 100644 --- a/Spanner/tests/System/SpannerTestCase.php +++ b/Spanner/tests/System/SpannerTestCase.php @@ -56,7 +56,7 @@ public static function setUpBeforeClass() $db = self::getDatabaseInstance(self::$dbName); - self::$deletionQueue->add(function() use ($db) { + self::$deletionQueue->add(function () use ($db) { $db->drop(); }); diff --git a/Spanner/tests/System/TransactionTest.php b/Spanner/tests/System/TransactionTest.php index 82619313a382..f191f570cd67 100644 --- a/Spanner/tests/System/TransactionTest.php +++ b/Spanner/tests/System/TransactionTest.php @@ -41,7 +41,7 @@ public static function setUpBeforeClass() self::$tableName = uniqid(self::TABLE_NAME); self::$row = [ - 'id' => rand(1000,9999), + 'id' => rand(1000, 9999), 'name' => uniqid(self::TESTING_PREFIX), 'birthday' => new Date(new \DateTime('2000-01-01')) ]; @@ -61,7 +61,7 @@ public function testRunTransaction() $db = self::$database; $db->runTransaction(function ($t) { - $id = rand(1,346464); + $id = rand(1, 346464); $t->insert(self::TEST_TABLE_NAME, [ 'id' => $id, 'name' => uniqid(self::TESTING_PREFIX), diff --git a/Spanner/tests/System/WriteTest.php b/Spanner/tests/System/WriteTest.php index 89db5415ed71..fbd6a060948f 100644 --- a/Spanner/tests/System/WriteTest.php +++ b/Spanner/tests/System/WriteTest.php @@ -353,7 +353,9 @@ public function testWriteAndReadBackFancyArrayComplexValue($id, $field, $value) $row2 = $exec->rows()->current(); foreach ($row2[$field] as $item) { - if (is_null($item)) continue; + if (is_null($item)) { + continue; + } $this->assertInstanceOf(get_class($value[0]), $item); } @@ -421,11 +423,11 @@ public function randomBytesProvider() } return [ - [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100,9999))))], - [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100,9999))))], - [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100,9999))))], - [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100,9999))))], - [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100,9999))))], + [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100, 9999))))], + [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100, 9999))))], + [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100, 9999))))], + [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100, 9999))))], + [$this->randId(), new Bytes(base64_encode(random_bytes(rand(100, 9999))))], ]; } diff --git a/Spanner/tests/System/bootstrap.php b/Spanner/tests/System/bootstrap.php index 21832e464469..23bf06e5451a 100644 --- a/Spanner/tests/System/bootstrap.php +++ b/Spanner/tests/System/bootstrap.php @@ -6,4 +6,5 @@ 'GOOGLE_CLOUD_PHP_TESTS_KEY_PATH', 'GOOGLE_CLOUD_PHP_TESTS_WHITELIST_KEY_PATH' ]); + TestHelpers::generatedSystemTestBootstrap(); diff --git a/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithExecute.php b/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithExecute.php index f377cb29bd3c..08f1a6b48d52 100644 --- a/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithExecute.php +++ b/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithExecute.php @@ -14,7 +14,7 @@ $db1 = SpannerTestCase::getDatabaseInstance($dbName); $db2 = SpannerTestCase::getDatabaseInstance($dbName); -$callable = function(Database $db, $tableName, $id) use ($tmpFile) { +$callable = function (Database $db, $tableName, $id) use ($tmpFile) { $iterations = 0; $db->runTransaction(function ($transaction) use ($id, $tableName, &$iterations) { $iterations++; diff --git a/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithRead.php b/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithRead.php index 5d995fe4838d..9a7ab1983e8b 100644 --- a/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithRead.php +++ b/Spanner/tests/System/pcntl/ConcurrentTransactionsIncrementValueWithRead.php @@ -18,7 +18,7 @@ $keyset = new KeySet(['keys' => [$id]]); $columns = ['id','number']; -$callable = function(Database $db, KeySet $keyset, array $columns, $tableName) use ($tmpFile) { +$callable = function (Database $db, KeySet $keyset, array $columns, $tableName) use ($tmpFile) { $iterations = 0; $db->runTransaction(function ($transaction) use ($keyset, $columns, $tableName, &$iterations) { $iterations++; diff --git a/Spanner/tests/System/pcntl/forked-process-test.php b/Spanner/tests/System/pcntl/forked-process-test.php index 5fa6506affc4..fdd3324b2c4c 100644 --- a/Spanner/tests/System/pcntl/forked-process-test.php +++ b/Spanner/tests/System/pcntl/forked-process-test.php @@ -24,7 +24,9 @@ function setupIterationTracker($tmpFile) { $pid = getmypid(); register_shutdown_function(function () use ($tmpFile, $pid) { - if ($pid !== getmypid()) return; + if ($pid !== getmypid()) { + return; + } $h = fopen($tmpFile, 'r+'); flock($h, LOCK_UN); diff --git a/Spanner/tests/Unit/Batch/BatchClientTest.php b/Spanner/tests/Unit/Batch/BatchClientTest.php index df0a731fa04e..8e5179498099 100644 --- a/Spanner/tests/Unit/Batch/BatchClientTest.php +++ b/Spanner/tests/Unit/Batch/BatchClientTest.php @@ -41,8 +41,8 @@ class BatchClientTest extends TestCase use SpannerOperationRefreshTrait; use TimeTrait; - const DATABASE = 'projects/example_project/instances/example_instance/databases/example_database'; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const DATABASE = 'projects/my-awesome-project/instances/my-instance/databases/my-database'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; const TRANSACTION = 'transaction-id'; private $connection; @@ -68,20 +68,21 @@ public function testSnapshot() ->willReturn([ 'name' => self::SESSION ]); - $this->connection->beginTransaction(Argument::that(function(array $args) { - if ($args['singleUse'] !== false) return false; - if ($args['transactionOptions']['readOnly']['returnReadTimestamp'] !== true) return false; - if ($args['session'] !== self::SESSION) return false; - - $db = explode('/', self::DATABASE); - if ($args['database'] !== array_pop($db)) return false; - - return true; - }))->shouldBeCalled() - ->willReturn([ - 'id' => self::TRANSACTION, - 'readTimestamp' => \DateTime::createFromFormat('U', (string) $time)->format(Timestamp::FORMAT) - ]); + $this->connection->beginTransaction(Argument::allOf( + Argument::withEntry('singleUse', false), + Argument::withEntry('session', self::SESSION), + Argument::that(function (array $args) { + if ($args['transactionOptions']['readOnly']['returnReadTimestamp'] !== true) { + return false; + } + + $db = explode('/', self::DATABASE); + return $args['database'] === array_pop($db); + }) + ))->shouldBeCalled()->willReturn([ + 'id' => self::TRANSACTION, + 'readTimestamp' => \DateTime::createFromFormat('U', (string) $time)->format(Timestamp::FORMAT) + ]); $this->refreshOperation($this->client, $this->connection->reveal()); diff --git a/Spanner/tests/Unit/Batch/BatchSnapshotTest.php b/Spanner/tests/Unit/Batch/BatchSnapshotTest.php index dfa1e7469ec2..5483836bd046 100644 --- a/Spanner/tests/Unit/Batch/BatchSnapshotTest.php +++ b/Spanner/tests/Unit/Batch/BatchSnapshotTest.php @@ -43,8 +43,8 @@ class BatchSnapshotTest extends TestCase { use SpannerOperationRefreshTrait; - const DATABASE = 'projects/example_project/instances/example_instance/databases/example_database'; - const SESSION = 'projects/example_project/instances/example_instance/databases/example_database/sessions/session-id'; + const DATABASE = 'projects/my-awesome-project/instances/my-instance/databases/my-database'; + const SESSION = 'projects/my-awesome-project/instances/my-instance/databases/my-database/sessions/session-id'; const TRANSACTION = 'transaction-id'; private $session; @@ -190,7 +190,6 @@ public function testExecuteQueryPartition() Argument::withEntry('session', self::SESSION), Argument::withEntry('database', array_pop($db)), Argument::withEntry('transaction', ['id' => self::TRANSACTION]), - Argument::withEntry('sql', $sql), Argument::withEntry('params', $opts['parameters']), Argument::withEntry('paramTypes', ['foo' => ['code' => 6]]) @@ -222,7 +221,6 @@ public function testExecuteReadPartition() Argument::withEntry('session', self::SESSION), Argument::withEntry('database', array_pop($db)), Argument::withEntry('transaction', ['id' => self::TRANSACTION]), - Argument::withEntry('table', $table), Argument::withEntry('columns', $columns), Argument::withEntry('keySet', $keySet->keySetObject()), @@ -283,9 +281,11 @@ private function resultGenerator() } } +//@codingStandardsIgnoreStart class DummyPartition implements PartitionInterface { public function __toString() {} public function serialize() {} public static function hydrate(array $data) {} } +//@codingStandardsIgnoreEnd diff --git a/Spanner/tests/Unit/Connection/GrpcTest.php b/Spanner/tests/Unit/Connection/GrpcTest.php index 191be1c9047d..566501771909 100644 --- a/Spanner/tests/Unit/Connection/GrpcTest.php +++ b/Spanner/tests/Unit/Connection/GrpcTest.php @@ -191,35 +191,33 @@ public function methodProvider() $columns = ['id', 'name']; $keySetArgs = []; $keySet = $serializer->decodeMessage(new KeySet, $keySetArgs); - $keySetSingular = $serializer->decodeMessage( - new KeySet, [ - 'keys' => [ - [ - 'values' => [ - [ - 'number_value' => 1 - ] + $keySetSingular = $serializer->decodeMessage(new KeySet, [ + 'keys' => [ + [ + 'values' => [ + [ + 'number_value' => 1 ] - ], - ] + ] + ], ] - ); - $keySetComposite = $serializer->decodeMessage( - new KeySet, [ - 'keys' => [ - [ - 'values' => [ - [ - 'number_value' => 1 - ], - [ - 'number_value' => 1 - ] + ]); + + $keySetComposite = $serializer->decodeMessage(new KeySet, [ + 'keys' => [ + [ + 'values' => [ + [ + 'number_value' => 1 + ], + [ + 'number_value' => 1 ] ] ] ] - ); + ]); + $readWriteTransactionArgs = ['readWrite' => []]; $readWriteTransactionOptions = new TransactionOptions; $rw = new TransactionOptions_ReadWrite(); @@ -268,140 +266,269 @@ public function methodProvider() return [ [ 'listInstanceConfigs', - ['projectId' => self::PROJECT], - [self::PROJECT, ['headers' => ['google-cloud-resource-prefix' => [self::PROJECT]]]] - ], - [ + [ + 'projectId' => self::PROJECT + ], [ + self::PROJECT, + [ + 'headers' => $this->header(self::PROJECT) + ] + ] + ], [ 'getInstanceConfig', - ['name' => $configName, 'projectId' => self::PROJECT], - [$configName, ['headers' => ['google-cloud-resource-prefix' => [self::PROJECT]]]] - ], - [ + [ + 'name' => $configName, + 'projectId' => self::PROJECT + ], [ + $configName, + [ + 'headers' => $this->header(self::PROJECT) + ] + ] + ], [ 'listInstances', - ['projectId' => self::PROJECT], - [self::PROJECT, ['headers' => ['google-cloud-resource-prefix' => [self::PROJECT]]]] - ], - [ + [ + 'projectId' => self::PROJECT + ], [ + self::PROJECT, + [ + 'headers' => $this->header(self::PROJECT) + ] + ] + ], [ 'getInstance', - ['name' => $instanceName, 'projectId' => self::PROJECT], - [$instanceName, ['headers' => ['google-cloud-resource-prefix' => [self::PROJECT]]]] - ], - [ + [ + 'name' => $instanceName, + 'projectId' => self::PROJECT + ], [ + $instanceName, + [ + 'headers' => $this->header(self::PROJECT) + ] + ] + ], [ 'createInstance', - ['projectId' => self::PROJECT, 'instanceId' => $instanceName] + $instanceArgs, - [self::PROJECT, $instanceName, $instance, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]], + [ + 'projectId' => self::PROJECT, + 'instanceId' => $instanceName + ] + $instanceArgs, [ + self::PROJECT, + $instanceName, + $instance, + [ + 'headers' => $this->header($instanceName) + ] + ], $lro, null - ], - [ + ], [ 'updateInstance', $instanceArgs, - [$instance, $fieldMask, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]], + [ + $instance, + $fieldMask, + [ + 'headers' => $this->header($instanceName) + ] + ], $lro, null - ], - [ + ], [ 'updateInstance', $instanceArgsPartial, - [$instancePartial, $fieldMaskPartial, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]], + [ + $instancePartial, + $fieldMaskPartial, + [ + 'headers' => $this->header($instanceName) + ] + ], $lroPartial, null - ], - [ + ], [ 'deleteInstance', - ['name' => $instanceName], - [$instanceName, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]] - ], - [ + [ + 'name' => $instanceName + ], [ + $instanceName, [ + 'headers' => $this->header($instanceName) + ] + ] + ], [ 'setInstanceIamPolicy', - ['resource' => $instanceName, 'policy' => $policy], - [$instanceName, $policy, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]] - ], - [ + [ + 'resource' => $instanceName, + 'policy' => $policy + ], [ + $instanceName, + $policy, + [ + 'headers' => $this->header($instanceName) + ] + ] + ], [ 'getInstanceIamPolicy', - ['resource' => $instanceName], - [$instanceName, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]] - ], - [ + [ + 'resource' => $instanceName + ], [ + $instanceName, + [ + 'headers' => $this->header($instanceName) + ] + ] + ], [ 'testInstanceIamPermissions', - ['resource' => $instanceName, 'permissions' => $permissions], - [$instanceName, $permissions, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]] - ], - [ + [ + 'resource' => $instanceName, + 'permissions' => $permissions + ], [ + $instanceName, + $permissions, [ + 'headers' => $this->header($instanceName) + ] + ] + ], [ 'listDatabases', - ['instance' => $instanceName], - [$instanceName, ['headers' => ['google-cloud-resource-prefix' => [$instanceName]]]] - ], - [ + [ + 'instance' => $instanceName + ], [ + $instanceName, + [ + 'headers' => $this->header($instanceName) + ] + ] + ], [ 'createDatabase', - ['instance' => $instanceName, 'createStatement' => $createStmt, 'extraStatements' => []], - [$instanceName, $createStmt, ['extraStatements' => [], 'headers' => ['google-cloud-resource-prefix' => [$instanceName]]]], + [ + 'instance' => $instanceName, + 'createStatement' => $createStmt, + 'extraStatements' => [] + ], [ + $instanceName, + $createStmt, + [ + 'extraStatements' => [], + 'headers' => $this->header($instanceName) + ] + ], $lro, null - ], - [ + ], [ 'updateDatabaseDdl', - ['name' => $databaseName, 'statements' => []], - [$databaseName, [], ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]], + [ + 'name' => $databaseName, + 'statements' => [] + ], [ + $databaseName, + [], + [ + 'headers' => $this->header($databaseName) + ] + ], $lro, null - ], - [ + ], [ 'dropDatabase', - ['name' => $databaseName], - [$databaseName, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'name' => $databaseName + ], [ + $databaseName, [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'getDatabaseDDL', - ['name' => $databaseName], - [$databaseName, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'name' => $databaseName + ], [ + $databaseName, + [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'setDatabaseIamPolicy', - ['resource' => $databaseName, 'policy' => $policy], - [$databaseName, $policy, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'resource' => $databaseName, + 'policy' => $policy + ], [ + $databaseName, + $policy, + [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'getDatabaseIamPolicy', - ['resource' => $databaseName], - [$databaseName, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'resource' => $databaseName + ], [ + $databaseName, + [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'testDatabaseIamPermissions', - ['resource' => $databaseName, 'permissions' => $permissions], - [$databaseName, $permissions, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'resource' => $databaseName, + 'permissions' => $permissions + ], [ + $databaseName, + $permissions, + [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'createSession', - ['database' => $databaseName], - [$databaseName, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'database' => $databaseName + ], [ + $databaseName, + [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'getSession', - ['name' => $sessionName, 'database' => $databaseName], - [$sessionName, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'name' => $sessionName, + 'database' => $databaseName + ], [ + $sessionName, + [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'deleteSession', - ['name' => $sessionName, 'database' => $databaseName], - [$sessionName, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + [ + 'name' => $sessionName, + 'database' => $databaseName + ], [ + $sessionName, + [ + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'executeStreamingSql', [ 'session' => $sessionName, 'sql' => $sql, 'transactionId' => $transactionName, 'database' => $databaseName - ] + $mapped, - [$sessionName, $sql, [ - 'transaction' => $transactionSelector, - 'params' => $expectedParams, - 'paramTypes' => $expectedParamTypes, - 'headers' => ['google-cloud-resource-prefix' => [$databaseName]] - ]] - ], - [ + ] + $mapped, [ + $sessionName, + $sql, [ + 'transaction' => $transactionSelector, + 'params' => $expectedParams, + 'paramTypes' => $expectedParamTypes, + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'streamingRead', [ 'keySet' => [], @@ -410,10 +537,17 @@ public function methodProvider() 'table' => $tableName, 'columns' => $columns, 'database' => $databaseName, - ], - [$sessionName, $tableName, $columns, $keySet, ['transaction' => $transactionSelector, 'headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + ], [ + $sessionName, + $tableName, + $columns, + $keySet, + [ + 'transaction' => $transactionSelector, + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'streamingRead', [ 'keySet' => ['keys' => [1]], @@ -422,10 +556,17 @@ public function methodProvider() 'table' => $tableName, 'columns' => $columns, 'database' => $databaseName, - ], - [$sessionName, $tableName, $columns, $keySetSingular, ['transaction' => $transactionSelector, 'headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + ], [ + $sessionName, + $tableName, + $columns, + $keySetSingular, + [ + 'transaction' => $transactionSelector, + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'streamingRead', [ 'keySet' => ['keys' => [[1,1]]], @@ -434,8 +575,16 @@ public function methodProvider() 'table' => $tableName, 'columns' => $columns, 'database' => $databaseName, - ], - [$sessionName, $tableName, $columns, $keySetComposite, ['transaction' => $transactionSelector, 'headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] + ], [ + $sessionName, + $tableName, + $columns, + $keySetComposite, + [ + 'transaction' => $transactionSelector, + 'headers' => $this->header($databaseName) + ] + ] ], // test read write [ @@ -444,8 +593,13 @@ public function methodProvider() 'session' => $sessionName, 'transactionOptions' => $readWriteTransactionArgs, 'database' => $databaseName - ], - [$sessionName, $readWriteTransactionOptions, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] + ], [ + $sessionName, + $readWriteTransactionOptions, + [ + 'headers' => $this->header($databaseName) + ] + ] ], // test read only [ @@ -454,8 +608,13 @@ public function methodProvider() 'session' => $sessionName, 'transactionOptions' => $readOnlyTransactionArgs, 'database' => $databaseName - ], - [$sessionName, $readOnlyTransactionOptions, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] + ], [ + $sessionName, + $readOnlyTransactionOptions, + [ + 'headers' => $this->header($databaseName) + ] + ] ], // test insert // [ @@ -471,17 +630,27 @@ public function methodProvider() 'mutations' => [], 'singleUseTransaction' => true, 'database' => $databaseName - ], - [$sessionName, [], ['singleUseTransaction' => $readWriteTransactionOptions, 'headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] - ], - [ + ], [ + $sessionName, + [], + [ + 'singleUseTransaction' => $readWriteTransactionOptions, + 'headers' => $this->header($databaseName) + ] + ] + ], [ 'rollback', [ 'session' => $sessionName, 'transactionId' => $transactionName, 'database' => $databaseName - ], - [$sessionName, $transactionName, ['headers' => ['google-cloud-resource-prefix' => [$databaseName]]]] + ], [ + $sessionName, + $transactionName, + [ + 'headers' => $this->header($databaseName) + ] + ] ], // ['getOperation'], // ['cancelOperation'], @@ -489,4 +658,11 @@ public function methodProvider() // ['listOperations'] ]; } + + private function header($val) + { + return [ + 'google-cloud-resource-prefix' => [$val] + ]; + } } diff --git a/Spanner/tests/Unit/Connection/IamDatabaseTest.php b/Spanner/tests/Unit/Connection/IamDatabaseTest.php index 994194143630..deb8286c6982 100644 --- a/Spanner/tests/Unit/Connection/IamDatabaseTest.php +++ b/Spanner/tests/Unit/Connection/IamDatabaseTest.php @@ -17,10 +17,11 @@ namespace Google\Cloud\Spanner\Tests\Unit\Connection; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Connection\IamDatabase; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group spanneradmin @@ -36,7 +37,7 @@ public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->iam = \Google\Cloud\Core\Testing\TestHelpers::stub(IamDatabase::class, [$this->connection->reveal()]); + $this->iam = TestHelpers::stub(IamDatabase::class, [$this->connection->reveal()]); } /** diff --git a/Spanner/tests/Unit/Connection/IamInstanceTest.php b/Spanner/tests/Unit/Connection/IamInstanceTest.php index 730fa0a0d635..d4836d15e908 100644 --- a/Spanner/tests/Unit/Connection/IamInstanceTest.php +++ b/Spanner/tests/Unit/Connection/IamInstanceTest.php @@ -17,10 +17,11 @@ namespace Google\Cloud\Spanner\Tests\Unit\Connection; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Connection\IamInstance; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group spanneradmin @@ -36,7 +37,7 @@ public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->iam = \Google\Cloud\Core\Testing\TestHelpers::stub(IamInstance::class, [$this->connection->reveal()]); + $this->iam = TestHelpers::stub(IamInstance::class, [$this->connection->reveal()]); } /** diff --git a/Spanner/tests/Unit/Connection/LongRunningConnectionTest.php b/Spanner/tests/Unit/Connection/LongRunningConnectionTest.php index c99c56989639..ce02d6e8eb6c 100644 --- a/Spanner/tests/Unit/Connection/LongRunningConnectionTest.php +++ b/Spanner/tests/Unit/Connection/LongRunningConnectionTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Spanner\Tests\Unit\Connection; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Connection\LongRunningConnection; use PHPUnit\Framework\TestCase; @@ -33,7 +34,7 @@ class LongRunningConnectionTest extends TestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->lro = \Google\Cloud\Core\Testing\TestHelpers::stub(LongRunningConnection::class, [ + $this->lro = TestHelpers::stub(LongRunningConnection::class, [ $this->connection->reveal() ]); } diff --git a/Spanner/tests/Unit/DatabaseTest.php b/Spanner/tests/Unit/DatabaseTest.php index 590b1078f1c0..46c2f51cc064 100644 --- a/Spanner/tests/Unit/DatabaseTest.php +++ b/Spanner/tests/Unit/DatabaseTest.php @@ -24,6 +24,7 @@ use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Database\V1\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Connection\ConnectionInterface; @@ -101,12 +102,15 @@ public function setUp() 'connection', 'operation' ]; - $this->database = \Google\Cloud\Core\Testing\TestHelpers::stub(Database::class, $args, $props); + $this->database = TestHelpers::stub(Database::class, $args, $props); } public function testName() { - $this->assertEquals($this->database->name(), DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE)); + $this->assertEquals( + DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE), + $this->database->name() + ); } public function testInfo() @@ -151,10 +155,9 @@ public function testReload() public function testExists() { $this->connection->getDatabase(Argument::withEntry( - 'name', DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE) - )) - ->shouldBeCalled() - ->willReturn([]); + 'name', + DatabaseAdminClient::databaseName(self::PROJECT, self::INSTANCE, self::DATABASE) + ))->shouldBeCalled()->willReturn([]); $this->database->___setProperty('connection', $this->connection->reveal()); @@ -363,7 +366,7 @@ public function testRunTransactionNoCommit() $this->refreshOperation($this->database, $this->connection->reveal()); - $this->database->runTransaction(function (Transaction $t) {}); + $this->database->runTransaction($this->noop()); } /** @@ -381,7 +384,7 @@ public function testRunTransactionNestedTransaction() $this->refreshOperation($this->database, $this->connection->reveal()); $this->database->runTransaction(function ($t) { - $this->database->runTransaction(function ($t) {}); + $this->database->runTransaction($this->noop()); }); } @@ -403,7 +406,7 @@ public function testRunTransactionRetry() $it = 0; $this->connection->commit(Argument::any()) ->shouldBeCalledTimes(3) - ->will(function() use (&$it, $abort) { + ->will(function () use (&$it, $abort) { $it++; if ($it <= 2) { throw $abort; @@ -414,7 +417,7 @@ public function testRunTransactionRetry() $this->refreshOperation($this->database, $this->connection->reveal()); - $this->database->runTransaction(function($t) use ($it) { + $this->database->runTransaction(function ($t) use ($it) { if ($it > 0) { $this->assertTrue($t->isRetry()); } else { @@ -446,8 +449,9 @@ public function testRunTransactionAborted() $it = 0; $this->connection->commit(Argument::any()) ->shouldBeCalled() - ->will(function() use (&$it, $abort) { + ->will(function () use (&$it, $abort) { $it++; + if ($it <= Database::MAX_RETRIES+1) { throw $abort; } @@ -457,7 +461,9 @@ public function testRunTransactionAborted() $this->refreshOperation($this->database, $this->connection->reveal()); - $this->database->runTransaction(function($t){$t->commit();}); + $this->database->runTransaction(function ($t) { + $t->commit(); + }); } public function testTransaction() @@ -497,9 +503,17 @@ public function testInsert() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][OPERATION::OP_INSERT]['table'] !== $table) return false; - if ($arg['mutations'][0][OPERATION::OP_INSERT]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][OPERATION::OP_INSERT]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][OPERATION::OP_INSERT]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][OPERATION::OP_INSERT]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][OPERATION::OP_INSERT]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -517,9 +531,17 @@ public function testInsertBatch() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][OPERATION::OP_INSERT]['table'] !== $table) return false; - if ($arg['mutations'][0][OPERATION::OP_INSERT]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][OPERATION::OP_INSERT]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][OPERATION::OP_INSERT]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][OPERATION::OP_INSERT]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][OPERATION::OP_INSERT]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -537,9 +559,17 @@ public function testUpdate() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][Operation::OP_UPDATE]['table'] !== $table) return false; - if ($arg['mutations'][0][Operation::OP_UPDATE]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][Operation::OP_UPDATE]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][Operation::OP_UPDATE]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_UPDATE]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_UPDATE]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -557,9 +587,17 @@ public function testUpdateBatch() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][Operation::OP_UPDATE]['table'] !== $table) return false; - if ($arg['mutations'][0][Operation::OP_UPDATE]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][Operation::OP_UPDATE]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][Operation::OP_UPDATE]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_UPDATE]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_UPDATE]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -577,9 +615,17 @@ public function testInsertOrUpdate() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['table'] !== $table) return false; - if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -597,9 +643,17 @@ public function testInsertOrUpdateBatch() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['table'] !== $table) return false; - if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_INSERT_OR_UPDATE]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -617,9 +671,17 @@ public function testReplace() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][Operation::OP_REPLACE]['table'] !== $table) return false; - if ($arg['mutations'][0][Operation::OP_REPLACE]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][Operation::OP_REPLACE]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][Operation::OP_REPLACE]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_REPLACE]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_REPLACE]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -637,9 +699,17 @@ public function testReplaceBatch() $row = ['col' => 'val']; $this->connection->commit(Argument::that(function ($arg) use ($table, $row) { - if ($arg['mutations'][0][Operation::OP_REPLACE]['table'] !== $table) return false; - if ($arg['mutations'][0][Operation::OP_REPLACE]['columns'][0] !== array_keys($row)[0]) return false; - if ($arg['mutations'][0][Operation::OP_REPLACE]['values'][0] !== current($row)) return false; + if ($arg['mutations'][0][Operation::OP_REPLACE]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_REPLACE]['columns'][0] !== array_keys($row)[0]) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_REPLACE]['values'][0] !== current($row)) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -657,9 +727,17 @@ public function testDelete() $keys = [10, 'bar']; $this->connection->commit(Argument::that(function ($arg) use ($table, $keys) { - if ($arg['mutations'][0][Operation::OP_DELETE]['table'] !== $table) return false; - if ($arg['mutations'][0][Operation::OP_DELETE]['keySet']['keys'][0] !== (string) $keys[0]) return false; - if ($arg['mutations'][0][Operation::OP_DELETE]['keySet']['keys'][1] !== $keys[1]) return false; + if ($arg['mutations'][0][Operation::OP_DELETE]['table'] !== $table) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_DELETE]['keySet']['keys'][0] !== (string) $keys[0]) { + return false; + } + + if ($arg['mutations'][0][Operation::OP_DELETE]['keySet']['keys'][1] !== $keys[1]) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->commitResponse()); @@ -693,9 +771,17 @@ public function testRead() $opts = ['foo' => 'bar']; $this->connection->streamingRead(Argument::that(function ($arg) use ($table, $opts) { - if ($arg['table'] !== $table) return false; - if ($arg['keySet']['all'] !== true) return false; - if ($arg['columns'] !== ['ID']) return false; + if ($arg['table'] !== $table) { + return false; + } + + if ($arg['keySet']['all'] !== true) { + return false; + } + + if ($arg['columns'] !== ['ID']) { + return false; + } return true; }))->shouldBeCalled()->willReturn($this->resultGenerator()); @@ -743,4 +829,11 @@ private function assertTimestampIsCorrect($res) $this->assertEquals($ts->format('Y-m-d\TH:i:s\Z'), $res->get()->format('Y-m-d\TH:i:s\Z')); } + + private function noop() + { + return function () { + return; + }; + } } diff --git a/Spanner/tests/Unit/DateTest.php b/Spanner/tests/Unit/DateTest.php index 692a1667ff03..0c8ede028c4a 100644 --- a/Spanner/tests/Unit/DateTest.php +++ b/Spanner/tests/Unit/DateTest.php @@ -41,7 +41,7 @@ public function setUp() public function testCreateFromValues() { - $date = Date::createFromValues(1989,10,11); + $date = Date::createFromValues(1989, 10, 11); $this->assertEquals($date->formatAsString(), $this->date->formatAsString()); } diff --git a/Spanner/tests/Unit/Fixtures.php b/Spanner/tests/Unit/Fixtures.php index c1a04beb5030..1fb59a241038 100644 --- a/Spanner/tests/Unit/Fixtures.php +++ b/Spanner/tests/Unit/Fixtures.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Spanner\Tests\Unit; +//@codingStandardsIgnoreStart class Fixtures { public static function STREAMING_READ_ACCEPTANCE_FIXTURE() @@ -29,3 +30,4 @@ public static function INSTANCE_FIXTURE() return __DIR__ . '/fixtures/instance.json'; } } +//@codingStandardsIgnoreEnd diff --git a/Spanner/tests/Unit/InstanceConfigurationTest.php b/Spanner/tests/Unit/InstanceConfigurationTest.php index 27533b1e4bfd..765418de6f20 100644 --- a/Spanner/tests/Unit/InstanceConfigurationTest.php +++ b/Spanner/tests/Unit/InstanceConfigurationTest.php @@ -18,12 +18,13 @@ namespace Google\Cloud\Spanner\Tests\UnitAdmin; use Google\Cloud\Core\Exception\NotFoundException; +use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; -use Google\Cloud\Spanner\InstanceConfiguration; use Google\Cloud\Spanner\Connection\ConnectionInterface; -use Google\Cloud\Core\Testing\GrpcTestTrait; -use Prophecy\Argument; +use Google\Cloud\Spanner\InstanceConfiguration; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group spanneradmin @@ -44,7 +45,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->configuration = \Google\Cloud\Core\Testing\TestHelpers::stub(InstanceConfiguration::class, [ + $this->configuration = TestHelpers::stub(InstanceConfiguration::class, [ $this->connection->reveal(), self::PROJECT_ID, self::NAME @@ -53,7 +54,10 @@ public function setUp() public function testName() { - $this->assertEquals(self::NAME, InstanceAdminClient::parseName($this->configuration->name())['instance_config']); + $this->assertEquals( + InstanceAdminClient::parseName($this->configuration->name())['instance_config'], + self::NAME + ); } public function testInfo() @@ -62,7 +66,7 @@ public function testInfo() $this->configuration->___setProperty('connection', $this->connection->reveal()); $info = ['foo' => 'bar']; - $config = \Google\Cloud\Core\Testing\TestHelpers::stub(InstanceConfiguration::class, [ + $config = TestHelpers::stub(InstanceConfiguration::class, [ $this->connection->reveal(), self::PROJECT_ID, self::NAME, diff --git a/Spanner/tests/Unit/InstanceTest.php b/Spanner/tests/Unit/InstanceTest.php index 07c893c2b51d..25e9e0553f98 100644 --- a/Spanner/tests/Unit/InstanceTest.php +++ b/Spanner/tests/Unit/InstanceTest.php @@ -22,6 +22,8 @@ use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\LongRunning\LongRunningConnectionInterface; use Google\Cloud\Core\LongRunning\LongRunningOperation; +use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Database\V1\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Configuration; @@ -29,9 +31,8 @@ use Google\Cloud\Spanner\Database; use Google\Cloud\Spanner\Instance; use Google\Cloud\Spanner\Session\SessionPoolInterface; -use Google\Cloud\Core\Testing\GrpcTestTrait; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group spanner @@ -52,7 +53,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->instance = \Google\Cloud\Core\Testing\TestHelpers::stub(Instance::class, [ + $this->instance = TestHelpers::stub(Instance::class, [ $this->connection->reveal(), $this->prophesize(LongRunningConnectionInterface::class)->reveal(), [], diff --git a/Spanner/tests/Unit/OperationTest.php b/Spanner/tests/Unit/OperationTest.php index 033869828a5d..ac7cc7068a90 100644 --- a/Spanner/tests/Unit/OperationTest.php +++ b/Spanner/tests/Unit/OperationTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Spanner\Tests\Unit; use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Batch\QueryPartition; use Google\Cloud\Spanner\Batch\ReadPartition; use Google\Cloud\Spanner\Connection\ConnectionInterface; @@ -57,7 +58,7 @@ public function setUp() $this->connection = $this->prophesize(ConnectionInterface::class); - $this->operation = \Google\Cloud\Core\Testing\TestHelpers::stub(Operation::class, [ + $this->operation = TestHelpers::stub(Operation::class, [ $this->connection->reveal(), false ]); @@ -110,12 +111,12 @@ public function testCommit() ]) ]; - $this->connection->commit(Argument::that(function ($arg) use ($mutations) { - if ($arg['mutations'] !== $mutations) return false; - if ($arg['transactionId'] !== 'foo') return false; - - return true; - }))->shouldBeCalled()->willReturn(['commitTimestamp' => self::TIMESTAMP]); + $this->connection->commit(Argument::allOf( + Argument::withEntry('mutations', $mutations), + Argument::withEntry('transactionId', 'foo') + ))->shouldBeCalled()->willReturn([ + 'commitTimestamp' => self::TIMESTAMP + ]); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -134,13 +135,15 @@ public function testCommitWithExistingTransaction() ]) ]; - $this->connection->commit(Argument::that(function ($arg) use ($mutations) { - if ($arg['mutations'] !== $mutations) return false; - if (isset($arg['singleUseTransaction'])) return false; - if ($arg['transactionId'] !== self::TRANSACTION) return false; - - return true; - }))->shouldBeCalled()->willReturn(['commitTimestamp' => self::TIMESTAMP]); + $this->connection->commit(Argument::allOf( + Argument::withEntry('mutations', $mutations), + Argument::withEntry('transactionId', self::TRANSACTION), + Argument::that(function ($arg) { + return !isset($arg['singleUseTransaction']); + }) + ))->shouldBeCalled()->willReturn([ + 'commitTimestamp' => self::TIMESTAMP + ]); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -153,12 +156,10 @@ public function testCommitWithExistingTransaction() public function testRollback() { - $this->connection->rollback(Argument::that(function ($arg) { - if ($arg['transactionId'] !== self::TRANSACTION) return false; - if ($arg['session'] !== self::SESSION) return false; - - return true; - }))->shouldBeCalled(); + $this->connection->rollback(Argument::allOf( + Argument::withEntry('transactionId', self::TRANSACTION), + Argument::withEntry('session', self::SESSION) + ))->shouldBeCalled(); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -170,14 +171,14 @@ public function testExecute() $sql = 'SELECT * FROM Posts WHERE ID = @id'; $params = ['id' => 10]; - $this->connection->executeStreamingSql(Argument::that(function ($arg) use ($sql, $params) { - if ($arg['sql'] !== $sql) return false; - if ($arg['session'] !== self::SESSION) return false; - if ($arg['params'] !== ['id' => '10']) return false; - if ($arg['paramTypes']['id']['code'] !== Database::TYPE_INT64) return false; - - return true; - }))->shouldBeCalled()->willReturn($this->executeAndReadResponse()); + $this->connection->executeStreamingSql(Argument::allOf( + Argument::withEntry('sql', $sql), + Argument::withEntry('session', self::SESSION), + Argument::withEntry('params', ['id' => '10']), + Argument::that(function ($arg) use ($sql, $params) { + return $arg['paramTypes']['id']['code'] === Database::TYPE_INT64; + }) + ))->shouldBeCalled()->willReturn($this->executeAndReadResponse()); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -192,14 +193,12 @@ public function testExecute() public function testRead() { - $this->connection->streamingRead(Argument::that(function ($arg) { - if ($arg['table'] !== 'Posts') return false; - if ($arg['session'] !== self::SESSION) return false; - if ($arg['keySet']['all'] !== true) return false; - if ($arg['columns'] !== ['foo']) return false; - - return true; - }))->shouldBeCalled()->willReturn($this->executeAndReadResponse()); + $this->connection->streamingRead(Argument::allOf( + Argument::withEntry('table', 'Posts'), + Argument::withEntry('session', self::SESSION), + Argument::withEntry('keySet', ['all' => true]), + Argument::withEntry('columns', ['foo']) + ))->shouldBeCalled()->willReturn($this->executeAndReadResponse()); $this->operation->___setProperty('connection', $this->connection->reveal()); @@ -211,14 +210,12 @@ public function testRead() public function testReadWithTransaction() { - $this->connection->streamingRead(Argument::that(function ($arg) { - if ($arg['table'] !== 'Posts') return false; - if ($arg['session'] !== self::SESSION) return false; - if ($arg['keySet']['all'] !== true) return false; - if ($arg['columns'] !== ['foo']) return false; - - return true; - }))->shouldBeCalled()->willReturn($this->executeAndReadResponse([ + $this->connection->streamingRead(Argument::allOf( + Argument::withEntry('table', 'Posts'), + Argument::withEntry('session', self::SESSION), + Argument::withEntry('keySet', ['all' => true]), + Argument::withEntry('columns', ['foo']) + ))->shouldBeCalled()->willReturn($this->executeAndReadResponse([ 'transaction' => ['id' => self::TRANSACTION] ])); @@ -235,14 +232,12 @@ public function testReadWithTransaction() public function testReadWithSnapshot() { - $this->connection->streamingRead(Argument::that(function ($arg) { - if ($arg['table'] !== 'Posts') return false; - if ($arg['session'] !== self::SESSION) return false; - if ($arg['keySet']['all'] !== true) return false; - if ($arg['columns'] !== ['foo']) return false; - - return true; - }))->shouldBeCalled()->willReturn($this->executeAndReadResponse([ + $this->connection->streamingRead(Argument::allOf( + Argument::withEntry('table', 'Posts'), + Argument::withEntry('session', self::SESSION), + Argument::withEntry('keySet', ['all' => true]), + Argument::withEntry('columns', ['foo']) + ))->shouldBeCalled()->willReturn($this->executeAndReadResponse([ 'transaction' => ['id' => self::TRANSACTION] ])); @@ -320,15 +315,18 @@ public function testPartitionQuery() $partitionToken1 = 'token1'; $partitionToken2 = 'token2'; - $this->connection->partitionQuery(Argument::that(function ($arg) use ($sql, $params, $transactionId) { - if ($arg['sql'] !== $sql) return false; - if ($arg['session'] !== self::SESSION) return false; - if ($arg['params'] !== ['id' => '10']) return false; - if ($arg['paramTypes']['id']['code'] !== Database::TYPE_INT64) return false; - if ($arg['transactionId'] !== $transactionId) return false; - - return true; - }))->shouldBeCalled()->willReturn([ + $this->connection->partitionQuery(Argument::allOf( + Argument::withEntry('sql', $sql), + Argument::withEntry('session', self::SESSION), + Argument::withEntry('params', ['id' => '10']), + Argument::that(function ($arg) use ($transactionId) { + if ($arg['paramTypes']['id']['code'] !== Database::TYPE_INT64) { + return false; + } + + return $arg['transactionId'] === $transactionId; + }) + ))->shouldBeCalled()->willReturn([ 'partitions' => [ [ 'partitionToken' => $partitionToken1 @@ -359,14 +357,12 @@ public function testPartitionRead() $partitionToken1 = 'token1'; $partitionToken2 = 'token2'; - $this->connection->partitionRead(Argument::that(function ($arg) { - if ($arg['table'] !== 'Posts') return false; - if ($arg['session'] !== self::SESSION) return false; - if ($arg['keySet']['all'] !== true) return false; - if ($arg['columns'] !== ['foo']) return false; - - return true; - }))->shouldBeCalled()->willReturn([ + $this->connection->partitionRead(Argument::allOf( + Argument::withEntry('table', 'Posts'), + Argument::withEntry('session', self::SESSION), + Argument::withEntry('keySet', ['all' => true]), + Argument::withEntry('columns', ['foo']) + ))->shouldBeCalled()->willReturn([ 'partitions' => [ [ 'partitionToken' => $partitionToken1 @@ -378,9 +374,16 @@ public function testPartitionRead() $this->operation->___setProperty('connection', $this->connection->reveal()); - $res = $this->operation->partitionRead($this->session, $transactionId, 'Posts', new KeySet(['all' => true]), ['foo'], [ - 'parameters' => $params - ]); + $res = $this->operation->partitionRead( + $this->session, + $transactionId, + 'Posts', + new KeySet(['all' => true]), + ['foo'], + [ + 'parameters' => $params + ] + ); $this->assertContainsOnlyInstancesOf(ReadPartition::class, $res); $this->assertCount(2, $res); diff --git a/Spanner/tests/Unit/ResultTest.php b/Spanner/tests/Unit/ResultTest.php index 58f47ee732ae..03d358808ad7 100644 --- a/Spanner/tests/Unit/ResultTest.php +++ b/Spanner/tests/Unit/ResultTest.php @@ -99,9 +99,9 @@ function () use ($chunks, &$timesCalled) { } yield $chunk; } - } ); + iterator_to_array($result->rows()); $this->assertEquals(2, $timesCalled); } @@ -132,9 +132,9 @@ function () use ($chunks) { } yield $chunk; } - } ); + iterator_to_array($result->rows()); } diff --git a/Spanner/tests/Unit/Session/CacheSessionPoolTest.php b/Spanner/tests/Unit/Session/CacheSessionPoolTest.php index ad927050b2cb..f94cdd7ed654 100644 --- a/Spanner/tests/Unit/Session/CacheSessionPoolTest.php +++ b/Spanner/tests/Unit/Session/CacheSessionPoolTest.php @@ -720,6 +720,7 @@ private function getCacheItemPool(array $cacheData = null) } } +//@codingStandardsIgnoreStart class CacheSessionPoolStub extends CacheSessionPool { private $time; @@ -735,3 +736,4 @@ protected function time() return $this->time ?: parent::time(); } } +//@codingStandardsIgnoreEnd diff --git a/Spanner/tests/Unit/SpannerClientTest.php b/Spanner/tests/Unit/SpannerClientTest.php index 971b5c6a2bb3..8dd5c89e05b9 100644 --- a/Spanner/tests/Unit/SpannerClientTest.php +++ b/Spanner/tests/Unit/SpannerClientTest.php @@ -21,6 +21,7 @@ use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\LongRunning\LongRunningOperation; use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Admin\Database\V1\DatabaseAdminClient; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Batch\BatchClient; @@ -58,7 +59,7 @@ public function setUp() $this->checkAndSkipGrpcTests(); $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(SpannerClient::class, [ + $this->client = TestHelpers::stub(SpannerClient::class, [ ['projectId' => self::PROJECT] ]); } @@ -72,10 +73,15 @@ public function testBatch() $prop = $ref->getProperty('databaseName'); $prop->setAccessible(true); - $this->assertEquals(sprintf( - 'projects/%s/instances/%s/databases/%s', - self::PROJECT, 'foo', 'bar' - ), $prop->getValue($batch)); + $this->assertEquals( + sprintf( + 'projects/%s/instances/%s/databases/%s', + self::PROJECT, + 'foo', + 'bar' + ), + $prop->getValue($batch) + ); } /** @@ -166,7 +172,10 @@ public function testInstanceConfiguration() public function testCreateInstance() { $this->connection->createInstance(Argument::that(function ($arg) { - if ($arg['name'] !== InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)) return false; + if ($arg['name'] !== InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)) { + return false; + } + return $arg['config'] === InstanceAdminClient::instanceConfigName(self::PROJECT, self::CONFIG); })) ->shouldBeCalled() diff --git a/Spanner/tests/Unit/TransactionConfigurationTraitTest.php b/Spanner/tests/Unit/TransactionConfigurationTraitTest.php index 9b2f6d3d5b9e..75eae0be76f7 100644 --- a/Spanner/tests/Unit/TransactionConfigurationTraitTest.php +++ b/Spanner/tests/Unit/TransactionConfigurationTraitTest.php @@ -195,6 +195,7 @@ public function timestamps() } } +//@codingStandardsIgnoreStart class TransactionConfigurationTraitImplementation { use TransactionConfigurationTrait; @@ -214,3 +215,4 @@ public function proxyConfigureSnapshotOptions(array &$options) return $this->configureSnapshotOptions($options); } } +//@codingStandardsIgnoreEnd diff --git a/Spanner/tests/Unit/TransactionTest.php b/Spanner/tests/Unit/TransactionTest.php index bbb720e36af1..46131c4e377a 100644 --- a/Spanner/tests/Unit/TransactionTest.php +++ b/Spanner/tests/Unit/TransactionTest.php @@ -19,6 +19,7 @@ use Google\Cloud\Core\Testing\GrpcTestTrait; use Google\Cloud\Core\Testing\SpannerOperationRefreshTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Spanner\Connection\ConnectionInterface; use Google\Cloud\Spanner\Database; use Google\Cloud\Spanner\Instance; @@ -82,10 +83,10 @@ public function setUp() 'operation', 'readTimestamp', 'state' ]; - $this->transaction = \Google\Cloud\Core\Testing\TestHelpers::stub(Transaction::class, $args, $props); + $this->transaction = TestHelpers::stub(Transaction::class, $args, $props); unset($args[2]); - $this->singleUseTransaction = \Google\Cloud\Core\Testing\TestHelpers::stub(Transaction::class, $args, $props); + $this->singleUseTransaction = TestHelpers::stub(Transaction::class, $args, $props); } public function testInsert() @@ -190,10 +191,10 @@ public function testExecute() { $sql = 'SELECT * FROM Table'; - $this->connection->executeStreamingSql(Argument::that(function ($arg) use ($sql) { - if ($arg['transaction']['id'] !== self::TRANSACTION) return false; - return $arg['sql'] === $sql; - }))->shouldBeCalled()->willReturn($this->resultGenerator()); + $this->connection->executeStreamingSql(Argument::allOf( + Argument::withEntry('transaction', ['id' => self::TRANSACTION]), + Argument::withEntry('sql', $sql) + ))->shouldBeCalled()->willReturn($this->resultGenerator()); $this->refreshOperation($this->transaction, $this->connection->reveal()); @@ -208,12 +209,12 @@ public function testRead() $table = 'Table'; $opts = ['foo' => 'bar']; - $this->connection->streamingRead(Argument::that(function ($arg) use ($table, $opts) { - if ($arg['transaction']['id'] !== self::TRANSACTION) return false; - if ($arg['table'] !== $table) return false; - if ($arg['keySet']['all'] !== true) return false; - return $arg['columns'] === ['ID']; - }))->shouldBeCalled()->willReturn($this->resultGenerator()); + $this->connection->streamingRead(Argument::allOf( + Argument::withEntry('transaction', ['id' => self::TRANSACTION]), + Argument::withEntry('table', $table), + Argument::withEntry('keySet', ['all' => true]), + Argument::withEntry('columns', ['ID']) + ))->shouldBeCalled()->willReturn($this->resultGenerator()); $this->refreshOperation($this->transaction, $this->connection->reveal()); @@ -301,7 +302,7 @@ public function testIsRetryTrue() true ]; - $transaction = \Google\Cloud\Core\Testing\TestHelpers::stub(Transaction::class, $args); + $transaction = TestHelpers::stub(Transaction::class, $args); $this->assertTrue($transaction->isRetry()); } diff --git a/Spanner/tests/Unit/TransactionTypeTest.php b/Spanner/tests/Unit/TransactionTypeTest.php index 568f1f4af562..2a42a381dd5c 100644 --- a/Spanner/tests/Unit/TransactionTypeTest.php +++ b/Spanner/tests/Unit/TransactionTypeTest.php @@ -19,6 +19,7 @@ use Google\Cloud\Core\LongRunning\LongRunningConnectionInterface; use Google\Cloud\Core\Testing\GrpcTestTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\TimeTrait; use Google\Cloud\Spanner\Admin\Instance\V1\InstanceAdminClient; use Google\Cloud\Spanner\Connection\ConnectionInterface; @@ -87,7 +88,7 @@ public function testDatabaseRunTransactionPreAllocate() $database = $this->database($this->connection->reveal()); - $database->runTransaction(function($t){ + $database->runTransaction(function ($t) { $this->assertEquals($t->id(), self::TRANSACTION); $t->commit(); @@ -105,7 +106,7 @@ public function testDatabaseRunTransactionSingleUse() $database = $this->database($this->connection->reveal()); - $database->runTransaction(function($t){ + $database->runTransaction(function ($t) { $this->assertNull($t->id()); $t->commit(); @@ -775,7 +776,7 @@ private function database(ConnectionInterface $connection) $instance = $this->prophesize(Instance::class); $instance->name()->willReturn(InstanceAdminClient::instanceName(self::PROJECT, self::INSTANCE)); - $database = \Google\Cloud\Core\Testing\TestHelpers::stub(Database::class, [ + $database = TestHelpers::stub(Database::class, [ $connection, $instance->reveal(), $this->prophesize(LongRunningConnectionInterface::class)->reveal(), diff --git a/Spanner/tests/Unit/ValueMapperTest.php b/Spanner/tests/Unit/ValueMapperTest.php index c82520bb3b01..fdcb2e85944c 100644 --- a/Spanner/tests/Unit/ValueMapperTest.php +++ b/Spanner/tests/Unit/ValueMapperTest.php @@ -371,8 +371,10 @@ public function testFormatParamsForExecuteSqlStruct() } /** + * @codingStandardsIgnoreStart * @expectedException InvalidArgumentException * @expectedExceptionMessage Struct parameter types must be declared explicitly, and must be an instance of Google\Cloud\Spanner\StructType. + * @codingStandardsIgnoreEnd */ public function testFormatParamsForExecuteSqlStructInvalidDefinition() { @@ -390,8 +392,10 @@ public function testFormatParamsForExecuteSqlStructInvalidDefinition() } /** + * @codingStandardsIgnoreStart * @expectedException InvalidArgumentException * @expectedExceptionMessage Struct value must be an array an instance of `Google\Cloud\Spanner\StructValue` or null. + * @codingStandardsIgnoreEnd */ public function testFormatParamsForExecuteSqlInvalidStructValue() { diff --git a/Speech/tests/Snippet/OperationTest.php b/Speech/tests/Snippet/OperationTest.php index 4b814ec8f316..ef24bfd00a2d 100644 --- a/Speech/tests/Snippet/OperationTest.php +++ b/Speech/tests/Snippet/OperationTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Speech\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Speech\Connection\ConnectionInterface; use Google\Cloud\Speech\Operation; use Google\Cloud\Speech\Result; @@ -48,7 +49,7 @@ public function setUp() ]; $this->connection = $this->prophesize(ConnectionInterface::class); - $this->operation = \Google\Cloud\Core\Testing\TestHelpers::stub(Operation::class, [ + $this->operation = TestHelpers::stub(Operation::class, [ $this->connection->reveal(), $this->opData['name'], $this->opData @@ -59,20 +60,22 @@ public function testClass() { $snippet = $this->snippetFromClass(Operation::class); - $connectionStub = $this->prophesize(ConnectionInterface::class); - - $connectionStub->longRunningRecognize(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->longRunningRecognize(Argument::any()) ->willReturn(['name' => 'foo']); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); - $snippet->insertAfterLine(4, '$reflection = new \ReflectionClass($speech); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($speech, $connectionStub); - $property->setAccessible(false);' - ); $snippet->replace("__DIR__ . '/audio.flac'", '"php://temp"'); + $snippet->replace( + '$speech = new SpeechClient([' . PHP_EOL .' \'languageCode\' => \'en-US\'' . PHP_EOL .']);', + '' + ); + + $speech = TestHelpers::stub(SpeechClient::class, [ + ['languageCode' => 'en-US'] + ]); + $speech->___setProperty('connection', $connection->reveal()); + $snippet->addLocal('speech', $speech); $res = $snippet->invoke('operation'); } diff --git a/Speech/tests/Snippet/ResultTest.php b/Speech/tests/Snippet/ResultTest.php index 8b55f0262c3c..c9b737e334d2 100644 --- a/Speech/tests/Snippet/ResultTest.php +++ b/Speech/tests/Snippet/ResultTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Speech\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Speech\Connection\ConnectionInterface; use Google\Cloud\Speech\Result; +use Google\Cloud\Speech\SpeechClient; use Prophecy\Argument; /** @@ -49,18 +51,22 @@ public function setUp() public function testClass() { $snippet = $this->snippetFromClass(Result::class); - $connectionStub = $this->prophesize(ConnectionInterface::class); - $connectionStub->recognize(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->recognize(Argument::any()) ->willReturn(['name' => 'foo']); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); - $snippet->insertAfterLine(4, '$reflection = new \ReflectionClass($speech); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($speech, $connectionStub); - $property->setAccessible(false);' - ); $snippet->replace("__DIR__ . '/audio.flac'", '"php://temp"'); + $snippet->replace( + '$speech = new SpeechClient([' . PHP_EOL .' \'languageCode\' => \'en-US\'' . PHP_EOL .']);', + '' + ); + + $speech = TestHelpers::stub(SpeechClient::class, [ + ['languageCode' => 'en-US'] + ]); + $speech->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('speech', $speech); $res = $snippet->invoke('result'); } diff --git a/Speech/tests/Snippet/SpeechClientTest.php b/Speech/tests/Snippet/SpeechClientTest.php index 2d18e0221ab8..d61a6f7501ca 100644 --- a/Speech/tests/Snippet/SpeechClientTest.php +++ b/Speech/tests/Snippet/SpeechClientTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Speech\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Speech\Connection\ConnectionInterface; use Google\Cloud\Speech\Operation; use Google\Cloud\Speech\SpeechClient; @@ -36,7 +37,7 @@ public function setUp() { $this->testFile = "'" . __DIR__ . '/fixtures/demo.flac' . "'"; $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(SpeechClient::class, [ + $this->client = TestHelpers::stub(SpeechClient::class, [ ['languageCode' => 'en-US'] ]); $this->client->___setProperty('connection', $this->connection->reveal()); diff --git a/Speech/tests/Unit/HttpStreamWrapper.php b/Speech/tests/Unit/HttpStreamWrapper.php new file mode 100644 index 000000000000..23da6b498ff1 --- /dev/null +++ b/Speech/tests/Unit/HttpStreamWrapper.php @@ -0,0 +1,56 @@ +position += strlen($this->bodyData); + if ($this->position > strlen($this->bodyData)) { + return false; + } + + return $this->bodyData; + } + + public function stream_eof() + { + return $this->position >= strlen($this->bodyData); + } + + public function stream_stat() + { + return [ + 'wrapper_data' => ['test'] + ]; + } + + public function stream_tell() + { + return $this->position; + } +} diff --git a/Speech/tests/Unit/SpeechClientTest.php b/Speech/tests/Unit/SpeechClientTest.php index ab9ec85e8d0e..d861df895481 100644 --- a/Speech/tests/Unit/SpeechClientTest.php +++ b/Speech/tests/Unit/SpeechClientTest.php @@ -17,28 +17,29 @@ namespace Google\Cloud\Speech\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Speech\Connection\ConnectionInterface; use Google\Cloud\Speech\Operation; use Google\Cloud\Speech\Result; use Google\Cloud\Speech\SpeechClient; use Google\Cloud\Storage\StorageObject; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group speech */ class SpeechClientTest extends TestCase { - CONST GCS_URI = 'gs://bucket/object'; + const GCS_URI = 'gs://bucket/object'; private $client; private $connection; public function setUp() { - $this->client = new SpeechTestClient([ - 'languageCode' => 'en-US' + $this->client = TestHelpers::stub(SpeechClient::class, [ + ['languageCode' => 'en-US'] ]); $this->connection = $this->prophesize(ConnectionInterface::class); } @@ -48,7 +49,7 @@ public function setUp() */ public function testThrowsExceptionWithoutLanguageCode() { - $client = new SpeechTestClient(); + $client = TestHelpers::stub(SpeechClient::class); $client->recognize(self::GCS_URI); } @@ -74,7 +75,7 @@ public function testRecognize($audio, array $options, array $expectedOptions) ] ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $results = $this->client->recognize($audio, $options); $this->assertContainsOnlyInstancesOf(Result::class, $results); @@ -90,7 +91,7 @@ public function testBeginRecognizeOperation($audio, array $options, array $expec ->longRunningRecognize($expectedOptions) ->willReturn(['name' => '1234abc']) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $operation = $this->client->beginRecognizeOperation($audio, $options); $this->assertInstanceOf(Operation::class, $operation); @@ -237,43 +238,3 @@ public function audioProvider() ]; } } - -class SpeechTestClient extends SpeechClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } -} - -class HttpStreamWrapper { - public $position = 0; - public $bodyData = 'abcd'; - - public function stream_open($path, $mode, $options, &$opened_path) { - return true; - } - - public function stream_read($count) { - $this->position += strlen($this->bodyData); - if ($this->position > strlen($this->bodyData)) { - return false; - } - - return $this->bodyData; - } - - public function stream_eof() { - return $this->position >= strlen($this->bodyData); - } - - public function stream_stat() { - return [ - 'wrapper_data' => ['test'] - ]; - } - - public function stream_tell() { - return $this->position; - } -} diff --git a/Speech/tests/Unit/SpeechHelpersTraitTest.php b/Speech/tests/Unit/SpeechHelpersTraitTest.php index 26cc55ccfaa8..894af26a3bc4 100644 --- a/Speech/tests/Unit/SpeechHelpersTraitTest.php +++ b/Speech/tests/Unit/SpeechHelpersTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Tests\Unit\Speech; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Speech\SpeechHelpersTrait; use PHPUnit\Framework\TestCase; @@ -25,13 +26,13 @@ */ class SpeechHelpersTraitTest extends TestCase { - CONST GCS_URI = 'gs://bucket/object'; + const GCS_URI = 'gs://bucket/object'; private $implementation; public function setUp() { - $this->implementation = \Google\Cloud\Core\Testing\TestHelpers::impl(SpeechHelpersTrait::class); + $this->implementation = TestHelpers::impl(SpeechHelpersTrait::class); } /** @@ -66,10 +67,9 @@ public function createAudioStreamDataProvider() private function createResource($data) { - $resource = fopen('php://memory','r+'); + $resource = fopen('php://memory', 'r+'); fwrite($resource, $data); rewind($resource); return $resource; } } - diff --git a/Storage/tests/Snippet/AclTest.php b/Storage/tests/Snippet/AclTest.php index 9c4e42950e3d..5d5b90ce67ea 100644 --- a/Storage/tests/Snippet/AclTest.php +++ b/Storage/tests/Snippet/AclTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Storage\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Storage\Acl; use Google\Cloud\Storage\Connection\ConnectionInterface; use Prophecy\Argument; @@ -33,7 +34,7 @@ class AclTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->acl = \Google\Cloud\Core\Testing\TestHelpers::stub(Acl::class, [ + $this->acl = TestHelpers::stub(Acl::class, [ $this->connection->reveal(), 'bucketAccessControls', [] diff --git a/Storage/tests/Snippet/BucketTest.php b/Storage/tests/Snippet/BucketTest.php index caffdd89c26c..9831eec16899 100644 --- a/Storage/tests/Snippet/BucketTest.php +++ b/Storage/tests/Snippet/BucketTest.php @@ -20,10 +20,11 @@ use Google\Cloud\Core\Exception\GoogleException; use Google\Cloud\Core\Iam\Iam; use Google\Cloud\Core\Iterator\ItemIterator; +use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Upload\MultipartUploader; use Google\Cloud\Core\Upload\ResumableUploader; use Google\Cloud\Core\Upload\StreamableUploader; -use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; use Google\Cloud\PubSub\PubSubClient; use Google\Cloud\PubSub\Topic; use Google\Cloud\Storage\Acl; @@ -51,7 +52,7 @@ public function setUp() $this->connection = $this->prophesize(Rest::class); $this->connection->projectId() ->willReturn(self::PROJECT_ID); - $this->bucket = \Google\Cloud\Core\Testing\TestHelpers::stub(Bucket::class, [ + $this->bucket = TestHelpers::stub(Bucket::class, [ $this->connection->reveal(), self::BUCKET, [] @@ -392,14 +393,13 @@ public function testUpdate() $snippet = $this->snippetFromMethod(Bucket::class, 'update'); $snippet->addLocal('bucket', $this->bucket); - $this->connection->patchBucket(Argument::that(function($arg) { - if ($arg['logging']['logBucket'] !== 'myBucket') return false; - if ($arg['logging']['logObjectPrefix'] !== 'prefix') return false; + $this->connection->patchBucket(Argument::that(function ($arg) { + if ($arg['logging']['logBucket'] !== 'myBucket') { + return false; + } - return true; - })) - ->shouldBeCalled() - ->willReturn('foo'); + return $arg['logging']['logObjectPrefix'] === 'prefix'; + }))->shouldBeCalled()->willReturn('foo'); $this->bucket->___setProperty('connection', $this->connection->reveal()); diff --git a/Storage/tests/Snippet/NotificationTest.php b/Storage/tests/Snippet/NotificationTest.php index 63c81d2dee25..add13b1be30c 100644 --- a/Storage/tests/Snippet/NotificationTest.php +++ b/Storage/tests/Snippet/NotificationTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Storage\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\PubSub\PubSubClient; use Google\Cloud\PubSub\Topic; use Google\Cloud\Storage\Acl; @@ -40,7 +41,7 @@ class NotificationTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(Rest::class); - $this->notification = \Google\Cloud\Core\Testing\TestHelpers::stub(Notification::class, [ + $this->notification = TestHelpers::stub(Notification::class, [ $this->connection->reveal(), self::NOTIFICATION_ID, self::BUCKET diff --git a/Storage/tests/Snippet/StorageObjectTest.php b/Storage/tests/Snippet/StorageObjectTest.php index 55bee7bacf45..82f3bc1988dc 100644 --- a/Storage/tests/Snippet/StorageObjectTest.php +++ b/Storage/tests/Snippet/StorageObjectTest.php @@ -18,14 +18,15 @@ namespace Google\Cloud\Storage\Tests\Snippet; use Google\Cloud\Core\RequestWrapper; -use Google\Cloud\Core\Timestamp; +use Google\Cloud\Core\Testing\KeyPairGenerateTrait; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; +use Google\Cloud\Core\Timestamp; use Google\Cloud\Storage\Acl; use Google\Cloud\Storage\Bucket; use Google\Cloud\Storage\Connection\Rest; use Google\Cloud\Storage\StorageClient; use Google\Cloud\Storage\StorageObject; -use Google\Cloud\Core\Testing\KeyPairGenerateTrait; use GuzzleHttp\Psr7\Response; use Prophecy\Argument; use Psr\Http\Message\RequestInterface; @@ -47,7 +48,7 @@ class StorageObjectTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(Rest::class); - $this->object = \Google\Cloud\Core\Testing\TestHelpers::stub(StorageObject::class, [ + $this->object = TestHelpers::stub(StorageObject::class, [ $this->connection->reveal(), self::OBJECT, self::BUCKET diff --git a/Storage/tests/System/KmsTest.php b/Storage/tests/System/KmsTest.php index 56956af918d5..14d059dc690c 100644 --- a/Storage/tests/System/KmsTest.php +++ b/Storage/tests/System/KmsTest.php @@ -242,11 +242,14 @@ private static function getCryptoKeyName( $name = null; try { + $uri = 'https://cloudkms.googleapis.com/v1/projects/%s/'. + 'locations/us-west1/keyRings/%s/cryptoKeys?cryptoKeyId=%s'; + $response = $wrapper->send( new Request( 'POST', sprintf( - 'https://cloudkms.googleapis.com/v1/projects/%s/locations/us-west1/keyRings/%s/cryptoKeys?cryptoKeyId=%s', + $uri, $projectId, $keyRingId, $cryptoKeyId @@ -279,11 +282,13 @@ private static function getCryptoKeyName( ] ]; + $uri = 'https://cloudkms.googleapis.com/v1/projects/%s/locations/'. + 'us-west1/keyRings/%s/cryptoKeys/%s:setIamPolicy'; $wrapper->send( new Request( 'POST', sprintf( - 'https://cloudkms.googleapis.com/v1/projects/%s/locations/us-west1/keyRings/%s/cryptoKeys/%s:setIamPolicy', + $uri, $projectId, $keyRingId, $cryptoKeyId diff --git a/Storage/tests/System/RequesterPaysTest.php b/Storage/tests/System/RequesterPaysTest.php index 9211e7567b48..cfb865a218d2 100644 --- a/Storage/tests/System/RequesterPaysTest.php +++ b/Storage/tests/System/RequesterPaysTest.php @@ -120,7 +120,7 @@ public static function setupBeforeClass() public function testBucketSettings() { // run an http request to call the object's public link and see what we get. - $getBody = function($bucket, $object) { + $getBody = function ($bucket, $object) { $guzzle = new Client; try { diff --git a/Storage/tests/System/StreamWrapper/ReadTest.php b/Storage/tests/System/StreamWrapper/ReadTest.php index f68559bf8746..ebb60fc5bbd2 100644 --- a/Storage/tests/System/StreamWrapper/ReadTest.php +++ b/Storage/tests/System/StreamWrapper/ReadTest.php @@ -59,5 +59,4 @@ public function testEof() $this->assertTrue(feof($fd)); $this->assertTrue(fclose($fd)); } - } diff --git a/Storage/tests/System/StreamWrapper/RenameTest.php b/Storage/tests/System/StreamWrapper/RenameTest.php index 77704ee777e8..97c6b527b775 100644 --- a/Storage/tests/System/StreamWrapper/RenameTest.php +++ b/Storage/tests/System/StreamWrapper/RenameTest.php @@ -50,5 +50,4 @@ public function testRenameDirectory() $this->assertTrue(rename($oldFolder, $newFolder)); $this->assertFileExists($newFile); } - } diff --git a/Storage/tests/System/StreamWrapper/StreamWrapperTestCase.php b/Storage/tests/System/StreamWrapper/StreamWrapperTestCase.php index 72a4c4080c1a..80c031efd566 100644 --- a/Storage/tests/System/StreamWrapper/StreamWrapperTestCase.php +++ b/Storage/tests/System/StreamWrapper/StreamWrapperTestCase.php @@ -43,5 +43,4 @@ protected static function generateUrl($file) $bucketName = self::$bucket->name(); return "gs://$bucketName/$file"; } - } diff --git a/Storage/tests/System/StreamWrapper/UrlStatTest.php b/Storage/tests/System/StreamWrapper/UrlStatTest.php index 257a94f99579..4170d7295d96 100644 --- a/Storage/tests/System/StreamWrapper/UrlStatTest.php +++ b/Storage/tests/System/StreamWrapper/UrlStatTest.php @@ -103,5 +103,4 @@ public function testIsDir() $this->assertTrue(is_dir(self::$dirUrl)); $this->assertFalse(is_dir(self::$fileUrl)); } - } diff --git a/Storage/tests/System/StreamWrapper/WriteTest.php b/Storage/tests/System/StreamWrapper/WriteTest.php index 73354af70b03..be2ee40b5b9b 100644 --- a/Storage/tests/System/StreamWrapper/WriteTest.php +++ b/Storage/tests/System/StreamWrapper/WriteTest.php @@ -63,7 +63,7 @@ public function testStreamingWrite() $this->assertFileNotExists($this->fileUrl); $fp = fopen($this->fileUrl, 'w'); - for($i = 0; $i < 20000; $i++) { + for ($i = 0; $i < 20000; $i++) { fwrite($fp, "Line Number: $i\n"); } fclose($fp); diff --git a/Storage/tests/System/UploadObjectsTest.php b/Storage/tests/System/UploadObjectsTest.php index eeec6c1dcd68..c5bc4388bc12 100644 --- a/Storage/tests/System/UploadObjectsTest.php +++ b/Storage/tests/System/UploadObjectsTest.php @@ -101,8 +101,10 @@ public function testUploadsObjectWithProgressTracking() $this->testFileSize = filesize($path); $options = [ - 'resumable' => true, // It's required to be in resumable upload if we want to track the progress with callback method. - 'chunkSize' => 1 * 1024 * 1024, //1MB; The upload progress will be done in chunks. The size must be in multiples of 262144 bytes. + // It's required to be in resumable upload if we want to track the progress with callback method. + 'resumable' => true, + // 1MB; The upload progress will be done in chunks. The size must be in multiples of 262144 bytes. + 'chunkSize' => 1 * 1024 * 1024, 'uploadProgressCallback' => array($this, 'onStoredFileChunk') ]; diff --git a/Storage/tests/Unit/BucketTest.php b/Storage/tests/Unit/BucketTest.php index 7e8e8a0c347b..fcc671dbaf16 100644 --- a/Storage/tests/Unit/BucketTest.php +++ b/Storage/tests/Unit/BucketTest.php @@ -182,8 +182,8 @@ public function testGetsObjectsWithoutToken() public function testGetsObjectsWithToken() { - $this->connection->listObjects(Argument::any())->willReturn( - [ + $this->connection->listObjects(Argument::any()) + ->willReturn([ 'nextPageToken' => 'token', 'items' => [ [ @@ -191,16 +191,14 @@ public function testGetsObjectsWithToken() 'generation' => 'abc' ] ] - ], - [ + ], [ 'items' => [ [ 'name' => 'file2.txt', 'generation' => 'def' ] ] - ] - ); + ]); $bucket = $this->getBucket(); $objects = iterator_to_array($bucket->objects()); diff --git a/Storage/tests/Unit/Connection/RestTest.php b/Storage/tests/Unit/Connection/RestTest.php index 4894c98b31b1..718161d70b76 100644 --- a/Storage/tests/Unit/Connection/RestTest.php +++ b/Storage/tests/Unit/Connection/RestTest.php @@ -151,9 +151,12 @@ function ($args) use (&$actualRequest, $response) { $actualUri = (string) $actualRequest->getUri(); + $expectedUri = 'https://www.googleapis.com/storage/v1/b/bigbucket/o/myfile.txt?' . + 'generation=100&alt=media&userProject=myProject'; + $this->assertEquals($this->successBody, $actualBody); $this->assertEquals( - 'https://www.googleapis.com/storage/v1/b/bigbucket/o/myfile.txt?generation=100&alt=media&userProject=myProject', + $expectedUri, $actualUri ); } diff --git a/Storage/tests/Unit/EncryptionTraitTest.php b/Storage/tests/Unit/EncryptionTraitTest.php index ef3b6e9e7551..a7764fe6ae62 100644 --- a/Storage/tests/Unit/EncryptionTraitTest.php +++ b/Storage/tests/Unit/EncryptionTraitTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Storage\Tests\Unit; use Google\Cloud\Core\Testing\KeyPairGenerateTrait; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Storage\EncryptionTrait; use PHPUnit\Framework\TestCase; @@ -28,11 +29,11 @@ class EncryptionTraitTest extends TestCase { use KeyPairGenerateTrait; - private $implementation; + private $impl; public function setUp() { - $this->implementation = \Google\Cloud\Core\Testing\TestHelpers::impl(EncryptionTrait::class); + $this->impl = TestHelpers::impl(EncryptionTrait::class); } public function testSignString() @@ -41,7 +42,7 @@ public function testSignString() list($pkey, $pub) = $this->getKeyPair(); - $res = $this->implementation->call('signString', [$pkey, $testString]); + $res = $this->impl->call('signString', [$pkey, $testString]); $this->assertTrue($this->verifySignature($pkey, $testString, urlencode(base64_encode($res)))); } @@ -52,7 +53,7 @@ public function testSignStringWithOpenSsl() list($pkey, $pub) = $this->getKeyPair(); - $res = $this->implementation->call('signString', [$pkey, $testString, true]); + $res = $this->impl->call('signString', [$pkey, $testString, true]); $this->assertTrue($this->verifySignature($pkey, $testString, urlencode(base64_encode($res)))); } @@ -64,7 +65,7 @@ public function testFormatEncryptionHeaders($expectedOptions, $options) { $this->assertEquals( $expectedOptions, - $this->implementation->formatEncryptionHeaders($options) + $this->impl->formatEncryptionHeaders($options) ); } diff --git a/Storage/tests/Unit/RequesterPaysTest.php b/Storage/tests/Unit/RequesterPaysTest.php index d24956508d49..16d9cbd4b377 100644 --- a/Storage/tests/Unit/RequesterPaysTest.php +++ b/Storage/tests/Unit/RequesterPaysTest.php @@ -17,13 +17,14 @@ namespace Google\Cloud\Storage\Tests\Unit; -use Prophecy\Argument; use Google\Cloud\Core\RequestWrapper; -use Psr\Http\Message\RequestInterface; -use Google\Cloud\Storage\StorageClient; -use Google\Cloud\Storage\Connection\Rest; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Upload\AbstractUploader; +use Google\Cloud\Storage\Connection\Rest; +use Google\Cloud\Storage\StorageClient; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; +use Psr\Http\Message\RequestInterface; /** * @group storage @@ -43,7 +44,7 @@ class RequesterPaysTest extends TestCase public function setUp() { $this->connection = new Rest(['projectId' => self::PROJECT]); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub( + $this->client = TestHelpers::stub( StorageClient::class, [['projectId' => self::PROJECT]] ); @@ -327,7 +328,10 @@ public function testUserProjectListBucketsDisableUserProject() ]); $this->client->___setProperty('connection', $connection->reveal()); - $bucket = $this->client->buckets(['userProject' => self::USER_PROJECT, 'bucketUserProject' => false])->current(); + $bucket = $this->client->buckets([ + 'userProject' => self::USER_PROJECT, + 'bucketUserProject' => false + ])->current(); $bucket->objects()->current(); } @@ -402,7 +406,7 @@ private function checkRequest(callable $invoke) // if no exception, something is wrong. $this->assertTrue(false); - } catch(\Exception $e) { + } catch (\Exception $e) { parse_str($e->getMessage(), $query); $this->assertEquals(self::USER_PROJECT, $query['userProject']); } @@ -424,6 +428,7 @@ private function notification(StorageClient $client) } } +//@codingStandardsIgnoreStart class RequestWrapperStub extends RequestWrapper { public function send(RequestInterface $request, array $options = []) @@ -432,3 +437,4 @@ public function send(RequestInterface $request, array $options = []) throw new \Exception($request->getUri()->getQuery()); } } +//@codingStandardsIgnoreEnd diff --git a/Storage/tests/Unit/StorageClientTest.php b/Storage/tests/Unit/StorageClientTest.php index 1cec11431d9c..b4149bfd00b6 100644 --- a/Storage/tests/Unit/StorageClientTest.php +++ b/Storage/tests/Unit/StorageClientTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Storage\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Core\Timestamp; use Google\Cloud\Core\Upload\SignedUrlUploader; use Google\Cloud\Storage\Bucket; @@ -24,8 +25,8 @@ use Google\Cloud\Storage\StorageClient; use Google\Cloud\Storage\StreamWrapper; use GuzzleHttp\Psr7; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group storage @@ -38,7 +39,7 @@ class StorageClientTest extends TestCase public function setUp() { $this->connection = $this->prophesize(Rest::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(StorageClient::class, [['projectId' => self::PROJECT]]); + $this->client = TestHelpers::stub(StorageClient::class, [['projectId' => self::PROJECT]]); } public function testGetBucket() @@ -87,19 +88,18 @@ public function testGetsBucketsWithoutToken() public function testGetsBucketsWithToken() { - $this->connection->listBuckets(Argument::any())->willReturn( - [ + $this->connection->listBuckets(Argument::any()) + ->willReturn([ 'nextPageToken' => 'token', 'items' => [ ['name' => 'bucket1'] ] - ], - [ + ], [ 'items' => [ ['name' => 'bucket2'] ] - ] - ); + ]); + $this->connection->projectId() ->willReturn(self::PROJECT); @@ -176,6 +176,7 @@ public function testGetServiceAccount() } } +//@codingStandardsIgnoreStart class StorageClientStub extends StorageClient { protected function onGce($httpHandler) @@ -183,3 +184,4 @@ protected function onGce($httpHandler) return false; } } +//@codingStandardsIgnoreEnd diff --git a/Storage/tests/Unit/StorageObjectTest.php b/Storage/tests/Unit/StorageObjectTest.php index aa5a5e28125c..e6b46e06be33 100644 --- a/Storage/tests/Unit/StorageObjectTest.php +++ b/Storage/tests/Unit/StorageObjectTest.php @@ -41,6 +41,8 @@ class StorageObjectTest extends TestCase use KeyPairGenerateTrait; const TIMESTAMP = '2025-01-01'; + const BUCKET = 'bucket'; + const OBJECT = 'object.txt'; /** @var Rest|ObjectProphecy */ public $connection; @@ -60,15 +62,15 @@ public function setUp() public function testGetAcl() { - $object = new StorageObject($this->connection->reveal(), 'object.txt', 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $this->assertInstanceOf(Acl::class, $object->acl()); } public function testDoesExistTrue() { - $this->connection->getObject(Argument::any())->willReturn(['name' => 'object.txt']); - $object = new StorageObject($this->connection->reveal(), 'object.txt', 'bucket'); + $this->connection->getObject(Argument::any())->willReturn(['name' => self::OBJECT]); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $this->assertTrue($object->exists()); } @@ -76,21 +78,21 @@ public function testDoesExistTrue() public function testDoesExistFalse() { $this->connection->getObject(Argument::any())->willThrow(new NotFoundException(null)); - $object = new StorageObject($this->connection->reveal(), 'object.txt', 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $this->assertFalse($object->exists()); } public function testDelete() { - $object = new StorageObject($this->connection->reveal(), 'object.txt', 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $this->assertNull($object->delete()); } public function testUpdatesData() { - $object = 'object.txt'; + $object = self::OBJECT; $data = ['contentType' => 'image/jpg']; $this->connection->patchObject(Argument::any())->willReturn(['name' => $object] + $data); $object = new StorageObject( @@ -108,7 +110,7 @@ public function testUpdatesData() public function testUpdatesDataAndUnsetsAclWithPredefinedAclApplied() { - $object = 'object.txt'; + $object = self::OBJECT; $bucket = 'bucket'; $predefinedAcl = ['predefinedAcl' => 'private']; $this->connection->patchObject($predefinedAcl + [ @@ -131,7 +133,7 @@ public function testCopyObjectWithDefaultName() { $sourceBucket = 'bucket'; $destinationBucket = 'bucket2'; - $objectName = 'object.txt'; + $objectName = self::OBJECT; $acl = 'private'; $key = base64_encode('abcd'); $hash = base64_encode('1234'); @@ -169,7 +171,7 @@ public function testCopyObjectWithDefaultName() public function testCopyObjectWithNewName() { $sourceBucket = 'bucket'; - $sourceObject = 'object.txt'; + $sourceObject = self::OBJECT; $bucketConnection = $this->prophesize(Rest::class)->reveal(); $destinationBucketName = 'bucket2'; $destinationBucket = new Bucket($bucketConnection, $destinationBucketName, []); @@ -203,7 +205,7 @@ public function testCopyObjectWithNewName() */ public function testCopyObjectThrowsExceptionWithInvalidType() { - $object = new StorageObject($this->connection->reveal(), 'object.txt.', 'bucket'); + $object = new StorageObject($this->connection->reveal(), 'object.txt.', self::BUCKET); $copiedObject = $object->copy($object); } @@ -211,7 +213,7 @@ public function testRewriteObjectWithDefaultName() { $sourceBucket = 'bucket'; $destinationBucket = 'bucket2'; - $objectName = 'object.txt'; + $objectName = self::OBJECT; $acl = 'private'; $key = base64_encode('abcd'); $hash = base64_encode('1234'); @@ -258,7 +260,7 @@ public function testRewriteObjectWithDefaultName() public function testRewriteObjectWithNewName() { $sourceBucket = 'bucket'; - $sourceObject = 'object.txt'; + $sourceObject = self::OBJECT; $bucketConnection = $this->prophesize(Rest::class)->reveal(); $destinationBucketName = 'bucket2'; $destinationBucket = new Bucket($bucketConnection, $destinationBucketName, []); @@ -309,14 +311,14 @@ public function testRewriteObjectWithNewName() */ public function testRewriteObjectThrowsExceptionWithInvalidType() { - $object = new StorageObject($this->connection->reveal(), 'object.txt.', 'bucket'); + $object = new StorageObject($this->connection->reveal(), 'object.txt.', self::BUCKET); $copiedObject = $object->rewrite($object); } public function testRenamesObject() { $sourceBucket = 'bucket'; - $objectName = 'object.txt'; + $objectName = self::OBJECT; $newObjectName = 'new-name.txt'; $acl = 'private'; $key = base64_encode('abcd'); @@ -360,7 +362,7 @@ public function testDownloadsAsString() $key = base64_encode('abcd'); $hash = base64_encode('1234'); $bucket = 'bucket'; - $object = 'object.txt'; + $object = self::OBJECT; $stream = Psr7\stream_for($string = 'abcdefg'); $this->connection->downloadObject([ 'bucket' => $bucket, @@ -389,7 +391,7 @@ public function testDownloadsToFile() $key = base64_encode('abcd'); $hash = base64_encode('1234'); $bucket = 'bucket'; - $object = 'object.txt'; + $object = self::OBJECT; $stream = Psr7\stream_for($string = 'abcdefg'); $this->connection->downloadObject([ 'bucket' => $bucket, @@ -406,18 +408,17 @@ public function testDownloadsToFile() $object = new StorageObject($this->connection->reveal(), $object, $bucket); - $this->assertEquals($string, $object->downloadToFile('php://temp', [ - 'encryptionKey' => $key, - 'encryptionKeySHA256' => $hash - ]) - ->getContents() - ); + $contents = $object->downloadToFile('php://temp', [ + 'encryptionKey' => $key, + 'encryptionKeySHA256' => $hash + ])->getContents(); + $this->assertEquals($string, $contents); } public function testGetBodyWithoutExtraOptions() { $bucket = 'bucket'; - $object = 'object.txt'; + $object = self::OBJECT; $stream = Psr7\stream_for($string = 'abcdefg'); $this->connection->downloadObject([ 'bucket' => $bucket, @@ -438,7 +439,7 @@ public function testGetBodyWithExtraOptions() $key = base64_encode('abcd'); $hash = base64_encode('1234'); $bucket = 'bucket'; - $object = 'object.txt'; + $object = self::OBJECT; $stream = Psr7\stream_for($string = 'abcdefg'); $this->connection->downloadObject([ 'bucket' => $bucket, @@ -467,12 +468,12 @@ public function testGetBodyWithExtraOptions() public function testGetsInfo() { $objectInfo = [ - 'name' => 'object.txt', + 'name' => self::OBJECT, 'bucket' => 'bucket', 'etag' => 'ABC', 'kind' => 'storage#object' ]; - $object = new StorageObject($this->connection->reveal(), 'object.txt', 'bucket', null, $objectInfo); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, 'bucket', null, $objectInfo); $this->assertEquals($objectInfo, $object->info()); } @@ -482,9 +483,9 @@ public function testGetsInfoWithReload() $key = base64_encode('abcd'); $hash = base64_encode('1234'); $bucket = 'bucket'; - $object = 'object.txt'; + $object = self::OBJECT; $objectInfo = [ - 'name' => 'object.txt', + 'name' => self::OBJECT, 'bucket' => 'bucket', 'etag' => 'ABC', 'kind' => 'storage#object' @@ -512,30 +513,30 @@ public function testGetsInfoWithReload() public function testGetsName() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); - $this->assertEquals($name, $object->name()); + $this->assertEquals(self::OBJECT, $object->name()); } public function testGetsIdentity() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); - $this->assertEquals($name, $object->identity()['object']); - $this->assertEquals($bucketName, $object->identity()['bucket']); + $this->assertEquals(self::OBJECT, $object->identity()['object']); + $this->assertEquals(self::BUCKET, $object->identity()['bucket']); } public function testGetsGcsUri() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); - $expectedUri = sprintf('gs://%s/%s', $bucketName, $name); + $expectedUri = sprintf('gs://%s/%s', self::BUCKET, self::OBJECT); $this->assertEquals($expectedUri, $object->gcsUri()); } public function testSignedUrl() { - $object = new StorageObjectSignatureStub($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket', 'foo'); + $object = new StorageObjectSignatureStub($this->connection->reveal(), self::OBJECT, 'bucket', 'foo'); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $seconds = $ts->get()->format('U'); @@ -580,7 +581,7 @@ public function testSignedUrl() public function testSignedUrlWithSaveAsName() { - $object = new StorageObjectSignatureStub($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObjectSignatureStub($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $seconds = $ts->get()->format('U'); @@ -616,7 +617,7 @@ public function testSignedUrlConnectionKeyfile() $conn = $this->prophesize(Rest::class); $conn->requestWrapper()->willReturn($rw->reveal()); - $object = new StorageObjectSignatureStub($conn->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObjectSignatureStub($conn->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $seconds = $ts->get()->format('U'); @@ -642,7 +643,13 @@ public function testSignedUrlConnectionKeyfile() public function testSignedUrlWithSpace() { - $object = new StorageObjectSignatureStub($this->connection->reveal(), $name = 'object object.txt', $bucketName = 'bucket', 'foo'); + $name = 'object object.txt'; + $object = new StorageObjectSignatureStub( + $this->connection->reveal(), + $name, + self::BUCKET, + 'foo' + ); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $seconds = $ts->get()->format('U'); @@ -669,7 +676,7 @@ public function testSignedUrlWithSpace() $seconds, 'foo:bar,bar', 'bat:baz', - sprintf('/%s/%s', $bucketName, rawurlencode($name)) + sprintf('/%s/%s', self::BUCKET, rawurlencode($name)) ]); $parts = explode('?', $url); @@ -694,7 +701,12 @@ public function testSignedUrlWithSpace() public function testSignedUploadUrl() { - $object = new StorageObjectSignatureStub($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket', 'foo'); + $object = new StorageObjectSignatureStub( + $this->connection->reveal(), + self::OBJECT, + 'bucket', + 'foo' + ); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $seconds = $ts->get()->format('U'); @@ -735,11 +747,10 @@ public function testSignedUploadUrl() public function testSignedUploadUrlNestedName() { $objectName = 'folder1/folder2/object.txt'; - $bucketName = 'bucket'; $object = new StorageObjectSignatureStub( $this->connection->reveal(), $objectName, - $bucketName, + self::BUCKET, 'foo' ); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); @@ -767,7 +778,7 @@ public function testSignedUploadUrlNestedName() 'foo:bar,bar', 'bat:baz', 'x-goog-resumable:start', - "/$bucketName/$objectName" + sprintf('/%s/%s', self::BUCKET, $objectName) ]); $query = explode('?', $url)[1]; @@ -790,7 +801,7 @@ public function testBeginSignedUploadSession() $sessionUri = 'http://example.com'; $rw->send(Argument::type(RequestInterface::class), Argument::type('array')) - ->will(function($args) use ($sessionUri, $test) { + ->will(function ($args) use ($sessionUri, $test) { $res = $test->prophesize(ResponseInterface::class); $res->getHeaderLine('Location') @@ -802,7 +813,12 @@ public function testBeginSignedUploadSession() $this->connection->requestWrapper() ->willReturn($rw->reveal()); - $object = new StorageObjectSignatureStub($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket', 'foo'); + $object = new StorageObjectSignatureStub( + $this->connection->reveal(), + self::OBJECT, + 'bucket', + 'foo' + ); $uri = $object->beginSignedUploadSession([ 'keyFile' => $this->kf, @@ -816,7 +832,7 @@ public function testBeginSignedUploadSession() */ public function testSignedUrlInvalidExpiration() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime('yesterday')); $object->signedUrl($ts); } @@ -826,7 +842,7 @@ public function testSignedUrlInvalidExpiration() */ public function testSignedUrlInvalidMethod() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $object->signedUrl($ts, [ 'method' => 'FOO' @@ -838,7 +854,7 @@ public function testSignedUrlInvalidMethod() */ public function testSignedUrlInvalidMethodMissingAllowPostOption() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $object->signedUrl($ts, [ 'method' => 'POST' @@ -850,7 +866,7 @@ public function testSignedUrlInvalidMethodMissingAllowPostOption() */ public function testSignedUrlInvalidKeyFilePath() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $url = $object->signedUrl($ts, [ @@ -863,7 +879,7 @@ public function testSignedUrlInvalidKeyFilePath() */ public function testSignedUrlInvalidKeyFilePathData() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $url = $object->signedUrl($ts, [ @@ -876,7 +892,7 @@ public function testSignedUrlInvalidKeyFilePathData() */ public function testSignedUrlInvalidKeyFileMissingPrivateKey() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $url = $object->signedUrl($ts, [ @@ -889,7 +905,7 @@ public function testSignedUrlInvalidKeyFileMissingPrivateKey() */ public function testSignedUrlInvalidKeyFileMissingClientEmail() { - $object = new StorageObject($this->connection->reveal(), $name = 'object.txt', $bucketName = 'bucket'); + $object = new StorageObject($this->connection->reveal(), self::OBJECT, self::BUCKET); $ts = new Timestamp(new \DateTime(self::TIMESTAMP)); $url = $object->signedUrl($ts, [ @@ -902,7 +918,15 @@ public function testRequesterPays() $this->connection->getObject(Argument::withEntry('userProject', 'foo')) ->willReturn([]); - $object = new StorageObject($this->connection->reveal(), 'object', 'bucket', null, ['requesterProjectId' => 'foo']); + $object = new StorageObject( + $this->connection->reveal(), + 'object', + 'bucket', + null, + [ + 'requesterProjectId' => 'foo' + ] + ); $object->reload(); } @@ -915,6 +939,7 @@ private function getSignatureFromSplitUrl(array $pieces) } } +//@codingStandardsIgnoreStart class StorageObjectSignatureStub extends StorageObject { const SIGNATURE = 'foo'; @@ -931,3 +956,4 @@ public function ___signatureIsCorrect($signature) return base64_decode(urldecode($signature)) === self::SIGNATURE; } } +//@codingStandardsIgnoreEnd diff --git a/Storage/tests/Unit/StreamWrapperTest.php b/Storage/tests/Unit/StreamWrapperTest.php index ecdf16909a3c..431fe0413fdf 100644 --- a/Storage/tests/Unit/StreamWrapperTest.php +++ b/Storage/tests/Unit/StreamWrapperTest.php @@ -262,7 +262,8 @@ public function testMkdirPrivate() */ public function testMkdirOnBadDirectory() { - $this->bucket->upload('', ['name' => 'foo/bar/', 'predefinedAcl' => 'publicRead'])->willThrow(NotFoundException::class); + $this->bucket->upload('', ['name' => 'foo/bar/', 'predefinedAcl' => 'publicRead']) + ->willThrow(NotFoundException::class); $this->assertFalse(mkdir('gs://my_bucket/foo/bar')); } @@ -275,8 +276,8 @@ public function testMkDirCreatesBucket() $this->bucket->name()->willReturn('my_bucket'); $this->client->createBucket('my_bucket', [ 'predefinedAcl' => 'publicRead', - 'predefinedDefaultObjectAcl' => 'publicRead'] - )->willReturn($this->bucket); + 'predefinedDefaultObjectAcl' => 'publicRead' + ])->willReturn($this->bucket); $this->bucket->upload('', ['name' => 'foo/bar/', 'predefinedAcl' => 'publicRead'])->shouldBeCalled(); $this->assertTrue(mkdir('gs://my_bucket/foo/bar', 0777, STREAM_MKDIR_RECURSIVE)); @@ -408,17 +409,17 @@ private function mockDirectoryListing($path, $filesToReturn) { $test = $this; $this->bucket->objects( - Argument::that(function($options) use ($path) { + Argument::that(function ($options) use ($path) { return $options['prefix'] == $path; }) - )->will(function() use ($test, $filesToReturn) { + )->will(function () use ($test, $filesToReturn) { return $test->fileListGenerator($filesToReturn); }); } private function fileListGenerator($fileToReturn) { - foreach($fileToReturn as $file) { + foreach ($fileToReturn as $file) { $obj = $this->prophesize(StorageObject::class); $obj->name()->willReturn($file); yield $obj->reveal(); diff --git a/Storage/tests/Unit/WriteStreamTest.php b/Storage/tests/Unit/WriteStreamTest.php index d0243d55c234..4def35e84497 100644 --- a/Storage/tests/Unit/WriteStreamTest.php +++ b/Storage/tests/Unit/WriteStreamTest.php @@ -35,7 +35,7 @@ public function testUploadsWhenWriteOverflowsBuffer() $stream = new WriteStream($uploader->reveal(), ['chunkSize' => 10]); // We should see 2 calls to upload with size of 10. - $upload = $uploader->upload(10)->will(function($args) use ($stream) { + $upload = $uploader->upload(10)->will(function ($args) use ($stream) { if (count($args) > 0) { $size = $args[0]; $stream->read(10); diff --git a/TextToSpeech/tests/System/bootstrap.php b/TextToSpeech/tests/System/bootstrap.php index 2d9fa79f0239..30d98dd46349 100644 --- a/TextToSpeech/tests/System/bootstrap.php +++ b/TextToSpeech/tests/System/bootstrap.php @@ -8,4 +8,3 @@ TestHelpers::requireKeyfile('GOOGLE_CLOUD_PHP_TESTS_KEY_PATH'); TestHelpers::generatedSystemTestBootstrap(); - diff --git a/Trace/tests/Snippet/TraceClientTest.php b/Trace/tests/Snippet/TraceClientTest.php index 6b006c662063..03ce7e9b77e9 100644 --- a/Trace/tests/Snippet/TraceClientTest.php +++ b/Trace/tests/Snippet/TraceClientTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Trace\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Trace\Connection\ConnectionInterface; use Google\Cloud\Trace\Trace; use Google\Cloud\Trace\TraceClient; @@ -34,7 +35,7 @@ class TraceClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(TraceClient::class); + $this->client = TestHelpers::stub(TraceClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } diff --git a/Trace/tests/Unit/AttributeTraitTest.php b/Trace/tests/Unit/AttributeTraitTest.php index ad42ebd1189b..64d006a09d36 100644 --- a/Trace/tests/Unit/AttributeTraitTest.php +++ b/Trace/tests/Unit/AttributeTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Trace\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Trace\Attributes; use Google\Cloud\Trace\AttributeTrait; use PHPUnit\Framework\TestCase; @@ -24,40 +25,30 @@ /** * @group trace */ -class AttributesTraitTest extends TestCase +class AttributeTraitTest extends TestCase { public function testDefaultsAttributesToNull() { - $obj = new TestTraitClass(); - $this->assertNull($obj->attributes()); + $obj = TestHelpers::impl(AttributeTrait::class); + $this->assertNull($obj->___getProperty('attributes')); } public function testAddAttribute() { - $obj = new TestTraitClass(); + $obj = TestHelpers::impl(AttributeTrait::class); $obj->addAttribute('foo', 'bar'); - $attributes = $obj->attributes(); + $attributes = $obj->___getProperty('attributes'); $this->assertInstanceOf(Attributes::class, $attributes); $this->assertEquals('bar', $attributes['foo']); } public function testAddAttributes() { - $obj = new TestTraitClass(); + $obj = TestHelpers::impl(AttributeTrait::class); $obj->addAttributes(['foo' => 'bar', 'asdf' => 'qwer']); - $attributes = $obj->attributes(); + $attributes = $obj->___getProperty('attributes'); $this->assertInstanceOf(Attributes::class, $attributes); $this->assertEquals('bar', $attributes['foo']); $this->assertEquals('qwer', $attributes['asdf']); } } - -class TestTraitClass -{ - use AttributeTrait; - - public function attributes() - { - return $this->attributes; - } -} diff --git a/Trace/tests/Unit/Connection/GrpcTest.php b/Trace/tests/Unit/Connection/GrpcTest.php index 2eb16e36bac0..a02aaad630a2 100644 --- a/Trace/tests/Unit/Connection/GrpcTest.php +++ b/Trace/tests/Unit/Connection/GrpcTest.php @@ -114,4 +114,4 @@ public function methodProvider() ] ]; } -} \ No newline at end of file +} diff --git a/Trace/tests/Unit/TimestampTraitTest.php b/Trace/tests/Unit/TimestampTraitTest.php index bed050e803f6..98494820fd42 100644 --- a/Trace/tests/Unit/TimestampTraitTest.php +++ b/Trace/tests/Unit/TimestampTraitTest.php @@ -51,6 +51,7 @@ public function timestampCases() } } +//@codingStandardsIgnoreStart class TestTimestampClass { use TimestampTrait; @@ -67,3 +68,4 @@ public function time() return $this->time; } } +//@codingStandardsIgnoreEnd diff --git a/Trace/tests/Unit/TraceClientTest.php b/Trace/tests/Unit/TraceClientTest.php index d367ce735806..baccfacafd25 100644 --- a/Trace/tests/Unit/TraceClientTest.php +++ b/Trace/tests/Unit/TraceClientTest.php @@ -17,11 +17,12 @@ namespace Google\Cloud\Trace\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Trace\Connection\ConnectionInterface; use Google\Cloud\Trace\Trace; use Google\Cloud\Trace\TraceClient; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group trace @@ -33,7 +34,9 @@ class TraceClientTest extends TestCase public function setUp() { - $this->client = new TraceTestClient(['projectId' => 'project']); + $this->client = TestHelpers::stub(TraceClient::class, [ + ['projectId' => 'project'] + ]); $this->connection = $this->prophesize(ConnectionInterface::class); } @@ -50,9 +53,12 @@ public function testInsertTrace() ] ] ]); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); - $trace = new Trace('project', '1', [ + $trace = new Trace( + 'project', + '1', + [ ['name' => 'main'] ] ); @@ -72,21 +78,15 @@ public function testInsertMultipleTraces() ] ] ]); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); - $trace = new Trace('project', '1', [ + $trace = new Trace( + 'project', + '1', + [ ['name' => 'main'] ] ); $this->assertTrue($this->client->insertBatch([$trace])); } - -} - -class TraceTestClient extends TraceClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } } diff --git a/Trace/tests/Unit/TraceTest.php b/Trace/tests/Unit/TraceTest.php index 7895729f06f5..72a195bff611 100644 --- a/Trace/tests/Unit/TraceTest.php +++ b/Trace/tests/Unit/TraceTest.php @@ -51,7 +51,7 @@ public function testLoadFromArray() ); $this->assertEquals('1234abcd', $trace->traceId()); $this->assertCount(1, $trace->spans()); - foreach($trace->spans() as $span) { + foreach ($trace->spans() as $span) { $this->assertInstanceOf(Span::class, $span); } } diff --git a/Translate/tests/Snippet/TranslateClientTest.php b/Translate/tests/Snippet/TranslateClientTest.php index 72417f26065f..adbb1681252d 100644 --- a/Translate/tests/Snippet/TranslateClientTest.php +++ b/Translate/tests/Snippet/TranslateClientTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Translate\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Translate\Connection\ConnectionInterface; use Google\Cloud\Translate\TranslateClient; use Prophecy\Argument; @@ -33,7 +34,7 @@ class TranslateClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(TranslateClient::class); + $this->client = TestHelpers::stub(TranslateClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } diff --git a/Translate/tests/Unit/TranslateClientTest.php b/Translate/tests/Unit/TranslateClientTest.php index cb573d382ee6..14c7aed47980 100644 --- a/Translate/tests/Unit/TranslateClientTest.php +++ b/Translate/tests/Unit/TranslateClientTest.php @@ -17,10 +17,11 @@ namespace Google\Cloud\Translate\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Translate\Connection\ConnectionInterface; use Google\Cloud\Translate\TranslateClient; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group translate @@ -33,19 +34,21 @@ class TranslateClientTest extends TestCase public function setUp() { - $this->client = new TranslateTestClient(['key' => $this->key]); + $this->client = TestHelpers::stub(TranslateClient::class, [ + ['key' => $this->key] + ]); $this->connection = $this->prophesize(ConnectionInterface::class); } public function testWithNoKey() { - $client = new TranslateTestClient(); + $client = TestHelpers::stub(TranslateClient::class); - $this->connection->listTranslations(Argument::that(function($args) { + $this->connection->listTranslations(Argument::that(function ($args) { return !isset($args['key']); }))->shouldBeCalled()->willReturn([]); - $client->setConnection($this->connection->reveal()); + $client->___setProperty('connection', $this->connection->reveal()); $client->translate('foo'); } @@ -53,18 +56,18 @@ public function testWithNoKey() public function testTranslateModel() { $this->connection->listTranslations(Argument::that(function ($args) { - if (isset($args['model'])) return false; + if (isset($args['model'])) { + return false; + } })); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $this->client->translate('foo bar'); - $this->connection->listTranslations(Argument::that(function ($args) { - if ($args['model'] !== 'base') return false; - })); + $this->connection->listTranslations(Argument::withEntry('model', 'base')); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $this->client->translate('foo bar', ['model' => 'base']); } @@ -77,20 +80,18 @@ public function testTranslate() 'format' => 'text', 'model' => 'base' ]; - $this->connection - ->listTranslations($options + [ - 'q' => [$expected['input']], - 'key' => $this->key - ]) - ->willReturn([ - 'data' => [ - 'translations' => [ - $this->getTranslateApiData($expected['text']) - ] + $this->connection->listTranslations($options + [ + 'q' => [$expected['input']], + 'key' => $this->key + ])->willReturn([ + 'data' => [ + 'translations' => [ + $this->getTranslateApiData($expected['text']) ] - ]) - ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + ] + ])->shouldBeCalledTimes(1); + + $this->client->___setProperty('connection', $this->connection->reveal()); $translation = $this->client->translate($expected['input'], $options); $this->assertEquals($expected, $translation); @@ -119,7 +120,7 @@ public function testTranslateWithNmtModel() ] ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $translation = $this->client->translate($expected['input'], $options); $this->assertEquals($expected, $translation); @@ -147,8 +148,10 @@ public function testTranslateBatch() ] ]) ->shouldBeCalledTimes(1); - $client = new TranslateTestClient(['key' => $this->key, 'target' => $target]); - $client->setConnection($this->connection->reveal()); + $client = TestHelpers::stub(TranslateClient::class, [ + ['key' => $this->key, 'target' => $target] + ]); + $client->___setProperty('connection', $this->connection->reveal()); $translations = $client->translateBatch($stringsToTranslate, ['model' => 'base']); $this->assertEquals($expected1, $translations[0]); @@ -157,33 +160,33 @@ public function testTranslateBatch() public function testTranslateBatchWithNotZeroIndexedInput() { - $expected1 = $this->getTranslateExpectedData('translate', 'translated', 'en'); - $expected2 = $this->getTranslateExpectedData('translate2', 'translated2', 'en'); - $stringsToTranslate = [1 => $expected1['input'], 2 => $expected2['input']]; - - $target = 'de'; - $this->connection - ->listTranslations([ - 'target' => $target, - 'q' => $stringsToTranslate, - 'key' => $this->key, - 'model' => 'base' - ]) - ->willReturn([ - 'data' => [ + $expected1 = $this->getTranslateExpectedData('translate', 'translated', 'en'); + $expected2 = $this->getTranslateExpectedData('translate2', 'translated2', 'en'); + $stringsToTranslate = [1 => $expected1['input'], 2 => $expected2['input']]; + + $target = 'de'; + $this->connection->listTranslations([ + 'target' => $target, + 'q' => $stringsToTranslate, + 'key' => $this->key, + 'model' => 'base' + ])->willReturn([ + 'data' => [ 'translations' => [ - $this->getTranslateApiData($expected1['text'], $expected1['source']), - $this->getTranslateApiData($expected2['text'], $expected2['source']) + $this->getTranslateApiData($expected1['text'], $expected1['source']), + $this->getTranslateApiData($expected2['text'], $expected2['source']) ] - ] - ]) - ->shouldBeCalledTimes(1); - $client = new TranslateTestClient(['key' => $this->key, 'target' => $target]); - $client->setConnection($this->connection->reveal()); - $translations = $client->translateBatch($stringsToTranslate, ['model' => 'base']); - - $this->assertEquals($expected1, $translations[0]); - $this->assertEquals($expected2, $translations[1]); + ] + ])->shouldBeCalledTimes(1); + + $client = TestHelpers::stub(TranslateClient::class, [ + ['key' => $this->key, 'target' => $target] + ]); + $client->___setProperty('connection', $this->connection->reveal()); + $translations = $client->translateBatch($stringsToTranslate, ['model' => 'base']); + + $this->assertEquals($expected1, $translations[0]); + $this->assertEquals($expected2, $translations[1]); } public function testDetectLanguage() @@ -203,7 +206,7 @@ public function testDetectLanguage() ] ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $detection = $this->client->detectLanguage($expected['input'], $options); $this->assertEquals($expected, $detection); @@ -228,7 +231,7 @@ public function testDetectLanguageBatch() ] ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $detections = $this->client->detectLanguageBatch($stringsToDetect); $this->assertEquals($expected1, $detections[0]); @@ -255,7 +258,7 @@ public function testLocalizedLanguages() ] ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $languages = $this->client->localizedLanguages(['target' => $target]); $this->assertEquals($expected, $languages[0]); @@ -277,7 +280,7 @@ public function testLanguages() ] ]) ->shouldBeCalledTimes(1); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $languages = $this->client->languages(); $this->assertEquals($expectedLanguage, $languages[0]); @@ -330,11 +333,3 @@ private function getLanguageApiData($languageCode, $name = null) ]); } } - -class TranslateTestClient extends TranslateClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } -} diff --git a/Vision/tests/Snippet/Annotation/AbstractFeatureTest.php b/Vision/tests/Snippet/Annotation/AbstractFeatureTest.php index 54c398b84b4e..52cbe20f901b 100644 --- a/Vision/tests/Snippet/Annotation/AbstractFeatureTest.php +++ b/Vision/tests/Snippet/Annotation/AbstractFeatureTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\AbstractFeature; /** @@ -27,8 +28,8 @@ class AbstractFeatureTest extends SnippetTestCase { public function testInfo() { - $stub = new AbstractFeatureImplementation; - $stub->setInfo('hello world'); + $stub = TestHelpers::stub(AbstractFeature::class, [], ['info']); + $stub->___setProperty('info', 'hello world'); $snippet = $this->snippetFromMethod(AbstractFeature::class, 'info'); $snippet->addLocal('imageProperties', $stub); @@ -37,8 +38,3 @@ public function testInfo() $this->assertEquals('hello world', $res->returnVal()); } } - -class AbstractFeatureImplementation extends AbstractFeature -{ - public function setInfo($info) { $this->info = $info; } -} diff --git a/Vision/tests/Snippet/Annotation/CropHintTest.php b/Vision/tests/Snippet/Annotation/CropHintTest.php index 5bfb518d0dc2..20dd858c1e77 100644 --- a/Vision/tests/Snippet/Annotation/CropHintTest.php +++ b/Vision/tests/Snippet/Annotation/CropHintTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\CropHint; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -43,9 +45,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(CropHint::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -56,17 +59,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(CropHint::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('hint'); diff --git a/Vision/tests/Snippet/Annotation/DocumentTest.php b/Vision/tests/Snippet/Annotation/DocumentTest.php index d41edcea4b1c..2413450c2540 100644 --- a/Vision/tests/Snippet/Annotation/DocumentTest.php +++ b/Vision/tests/Snippet/Annotation/DocumentTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Document; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -41,9 +43,9 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); - - $connectionStub->annotate(Argument::any()) + $snippet = $this->snippetFromClass(Document::class); + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -52,17 +54,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(Document::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/the-constitution.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('document'); diff --git a/Vision/tests/Snippet/Annotation/EntityTest.php b/Vision/tests/Snippet/Annotation/EntityTest.php index 129d68ea5eef..0d88525e7479 100644 --- a/Vision/tests/Snippet/Annotation/EntityTest.php +++ b/Vision/tests/Snippet/Annotation/EntityTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Entity; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -49,9 +51,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(Entity::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -60,17 +63,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(Entity::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('text'); diff --git a/Vision/tests/Snippet/Annotation/Face/LandmarksTest.php b/Vision/tests/Snippet/Annotation/Face/LandmarksTest.php index 5e15e7702fd8..39b0e5fed76e 100644 --- a/Vision/tests/Snippet/Annotation/Face/LandmarksTest.php +++ b/Vision/tests/Snippet/Annotation/Face/LandmarksTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation\Face; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Face\Landmarks; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -81,9 +83,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(Landmarks::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -96,17 +99,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(Landmarks::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('landmarks'); diff --git a/Vision/tests/Snippet/Annotation/FaceTest.php b/Vision/tests/Snippet/Annotation/FaceTest.php index 2d57c6f54808..380519db1fe4 100644 --- a/Vision/tests/Snippet/Annotation/FaceTest.php +++ b/Vision/tests/Snippet/Annotation/FaceTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Face; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -55,9 +57,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(Face::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -72,18 +75,22 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(Face::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); + + $res = $snippet->invoke('face'); + $this->assertInstanceOf(Face::class, $res->returnVal()); } public function testInfo() diff --git a/Vision/tests/Snippet/Annotation/ImagePropertiesTest.php b/Vision/tests/Snippet/Annotation/ImagePropertiesTest.php index f1ede5b6585a..687c213d8d63 100644 --- a/Vision/tests/Snippet/Annotation/ImagePropertiesTest.php +++ b/Vision/tests/Snippet/Annotation/ImagePropertiesTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\ImageProperties; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -38,9 +40,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(ImageProperties::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -51,17 +54,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(ImageProperties::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('imageProperties'); diff --git a/Vision/tests/Snippet/Annotation/SafeSearchTest.php b/Vision/tests/Snippet/Annotation/SafeSearchTest.php index 69b2b4eb67e8..35f8233b964b 100644 --- a/Vision/tests/Snippet/Annotation/SafeSearchTest.php +++ b/Vision/tests/Snippet/Annotation/SafeSearchTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\SafeSearch; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -44,9 +46,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(SafeSearch::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -57,17 +60,19 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(SafeSearch::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('safeSearch'); diff --git a/Vision/tests/Snippet/Annotation/Web/WebEntityTest.php b/Vision/tests/Snippet/Annotation/Web/WebEntityTest.php index 01c8841f8c91..e02f14348c00 100644 --- a/Vision/tests/Snippet/Annotation/Web/WebEntityTest.php +++ b/Vision/tests/Snippet/Annotation/Web/WebEntityTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation\Web; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Web\WebEntity; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -42,9 +44,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(WebEntity::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -57,17 +60,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(WebEntity::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/eiffel-tower.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('firstEntity'); diff --git a/Vision/tests/Snippet/Annotation/Web/WebImageTest.php b/Vision/tests/Snippet/Annotation/Web/WebImageTest.php index a2788ff39f94..f0ee93727170 100644 --- a/Vision/tests/Snippet/Annotation/Web/WebImageTest.php +++ b/Vision/tests/Snippet/Annotation/Web/WebImageTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation\Web; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Web\WebImage; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -41,9 +43,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(WebImage::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -56,17 +59,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(WebImage::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/eiffel-tower.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('firstImage'); diff --git a/Vision/tests/Snippet/Annotation/Web/WebPageTest.php b/Vision/tests/Snippet/Annotation/Web/WebPageTest.php index 46807edca1f2..2d4156b2b1e2 100644 --- a/Vision/tests/Snippet/Annotation/Web/WebPageTest.php +++ b/Vision/tests/Snippet/Annotation/Web/WebPageTest.php @@ -18,8 +18,10 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation\Web; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Web\WebPage; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -41,9 +43,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(WebPage::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -56,17 +59,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(WebPage::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/eiffel-tower.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('firstPage'); diff --git a/Vision/tests/Snippet/Annotation/WebTest.php b/Vision/tests/Snippet/Annotation/WebTest.php index 5417d1960c23..4730c550634d 100644 --- a/Vision/tests/Snippet/Annotation/WebTest.php +++ b/Vision/tests/Snippet/Annotation/WebTest.php @@ -18,11 +18,13 @@ namespace Google\Cloud\Vision\Tests\Snippet\Annotation; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\Web; use Google\Cloud\Vision\Annotation\Web\WebEntity; use Google\Cloud\Vision\Annotation\Web\WebImage; use Google\Cloud\Vision\Annotation\Web\WebPage; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -54,9 +56,10 @@ public function setUp() public function testClass() { - $connectionStub = $this->prophesize(ConnectionInterface::class); + $snippet = $this->snippetFromClass(Web::class); - $connectionStub->annotate(Argument::any()) + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) ->willReturn([ 'responses' => [ [ @@ -65,17 +68,18 @@ public function testClass() ] ]); - $snippet = $this->snippetFromClass(Web::class); - $snippet->addLocal('connectionStub', $connectionStub->reveal()); + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('web'); diff --git a/Vision/tests/Snippet/AnnotationTest.php b/Vision/tests/Snippet/AnnotationTest.php index 2d35d41de34a..752c418fe6c3 100644 --- a/Vision/tests/Snippet/AnnotationTest.php +++ b/Vision/tests/Snippet/AnnotationTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Vision\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation; use Google\Cloud\Vision\Annotation\CropHint; use Google\Cloud\Vision\Annotation\Document; @@ -27,6 +28,7 @@ use Google\Cloud\Vision\Annotation\SafeSearch; use Google\Cloud\Vision\Annotation\Web; use Google\Cloud\Vision\Connection\ConnectionInterface; +use Google\Cloud\Vision\VisionClient; use Prophecy\Argument; /** @@ -37,21 +39,23 @@ class AnnotationTest extends SnippetTestCase public function testClass() { $snippet = $this->snippetFromClass(Annotation::class); + + $connection = $this->prophesize(ConnectionInterface::class); + $connection->annotate(Argument::any()) + ->willReturn(['responses' => [[]]]); + + $vision = TestHelpers::stub(VisionClient::class); + $vision->___setProperty('connection', $connection->reveal()); + + $snippet->addLocal('vision', $vision); + $snippet->replace( "__DIR__ . '/assets/family-photo.jpg'", "'php://temp'" ); - - $connectionStub = $this->prophesize(ConnectionInterface::class); - $connectionStub->annotate(Argument::any()) - ->willReturn(['responses' => [ [] ] ]); - - $snippet->addLocal('connectionStub', $connectionStub->reveal()); - $snippet->insertAfterLine(3, '$reflection = new \ReflectionClass($vision); - $property = $reflection->getProperty(\'connection\'); - $property->setAccessible(true); - $property->setValue($vision, $connectionStub); - $property->setAccessible(false);' + $snippet->replace( + '$vision = new VisionClient();', + '' ); $res = $snippet->invoke('annotation'); diff --git a/Vision/tests/Snippet/VisionClientTest.php b/Vision/tests/Snippet/VisionClientTest.php index 84922e967fa1..cb20c7f0400c 100644 --- a/Vision/tests/Snippet/VisionClientTest.php +++ b/Vision/tests/Snippet/VisionClientTest.php @@ -18,6 +18,7 @@ namespace Google\Cloud\Vision\Tests\Snippet; use Google\Cloud\Core\Testing\Snippet\SnippetTestCase; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation; use Google\Cloud\Vision\Connection\ConnectionInterface; use Google\Cloud\Vision\Image; @@ -35,7 +36,7 @@ class VisionClientTest extends SnippetTestCase public function setUp() { $this->connection = $this->prophesize(ConnectionInterface::class); - $this->client = \Google\Cloud\Core\Testing\TestHelpers::stub(VisionClient::class); + $this->client = TestHelpers::stub(VisionClient::class); $this->client->___setProperty('connection', $this->connection->reveal()); } diff --git a/Vision/tests/System/AnnotationsTest.php b/Vision/tests/System/AnnotationsTest.php index 5e54934c0fc1..256ff38e34eb 100644 --- a/Vision/tests/System/AnnotationsTest.php +++ b/Vision/tests/System/AnnotationsTest.php @@ -44,15 +44,13 @@ public function setUp() public function testAnnotate() { - $image = $this->client->image( - file_get_contents($this->getFixtureFilePath('landmark.jpg')) , [ - 'LANDMARK_DETECTION', - 'SAFE_SEARCH_DETECTION', - 'IMAGE_PROPERTIES', - 'CROP_HINTS', - 'WEB_DETECTION' - ] - ); + $image = $this->client->image(file_get_contents($this->getFixtureFilePath('landmark.jpg')), [ + 'LANDMARK_DETECTION', + 'SAFE_SEARCH_DETECTION', + 'IMAGE_PROPERTIES', + 'CROP_HINTS', + 'WEB_DETECTION' + ]); $res = $this->client->annotate($image); $this->assertInstanceOf(Annotation::class, $res); @@ -100,12 +98,10 @@ public function testAnnotate() public function testFaceAndLabelDetection() { - $image = $this->client->image( - file_get_contents($this->getFixtureFilePath('obama.jpg')) , [ - 'FACE_DETECTION', - 'LABEL_DETECTION' - ] - ); + $image = $this->client->image(file_get_contents($this->getFixtureFilePath('obama.jpg')), [ + 'FACE_DETECTION', + 'LABEL_DETECTION' + ]); $res = $this->client->annotate($image); @@ -128,11 +124,9 @@ public function testFaceAndLabelDetection() public function testLogoDetection() { - $image = $this->client->image( - file_get_contents($this->getFixtureFilePath('google.jpg')) , [ - 'LOGO_DETECTION' - ] - ); + $image = $this->client->image(file_get_contents($this->getFixtureFilePath('google.jpg')), [ + 'LOGO_DETECTION' + ]); $res = $this->client->annotate($image); $this->assertInstanceOf(Annotation::class, $res); @@ -142,11 +136,9 @@ public function testLogoDetection() public function testTextDetection() { - $image = $this->client->image( - file_get_contents($this->getFixtureFilePath('text.jpg')) , [ - 'TEXT_DETECTION' - ] - ); + $image = $this->client->image(file_get_contents($this->getFixtureFilePath('text.jpg')), [ + 'TEXT_DETECTION' + ]); $res = $this->client->annotate($image); $this->assertInstanceOf(Annotation::class, $res); @@ -157,11 +149,9 @@ public function testTextDetection() public function testDocumentTextDetection() { - $image = $this->client->image( - file_get_contents($this->getFixtureFilePath('text.jpg')) , [ - 'DOCUMENT_TEXT_DETECTION' - ] - ); + $image = $this->client->image(file_get_contents($this->getFixtureFilePath('text.jpg')), [ + 'DOCUMENT_TEXT_DETECTION' + ]); $res = $this->client->annotate($image); diff --git a/Vision/tests/Unit/Annotation/LikelihoodTraitTest.php b/Vision/tests/Unit/Annotation/LikelihoodTraitTest.php index dbb27a48cb81..1965df32edcb 100644 --- a/Vision/tests/Unit/Annotation/LikelihoodTraitTest.php +++ b/Vision/tests/Unit/Annotation/LikelihoodTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Vision\Tests\Unit\Annotation; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation\FeatureInterface; use Google\Cloud\Vision\Annotation\LikelihoodTrait; use PHPUnit\Framework\TestCase; @@ -26,40 +27,44 @@ */ class LikelihoodTraitTest extends TestCase { - public function testLikelihoods() - { - $t = new LikelihoodTraitStub; - - $this->assertTrue($t->l('VERY_LIKELY', FeatureInterface::STRENGTH_HIGH)); - $this->assertFalse($t->l('LIKELY', FeatureInterface::STRENGTH_HIGH)); - $this->assertFalse($t->l('POSSIBLE', FeatureInterface::STRENGTH_HIGH)); + private $stub; - $this->assertTrue($t->l('VERY_LIKELY', FeatureInterface::STRENGTH_MEDIUM)); - $this->assertTrue($t->l('LIKELY', FeatureInterface::STRENGTH_MEDIUM)); - $this->assertFalse($t->l('POSSIBLE', FeatureInterface::STRENGTH_MEDIUM)); - - $this->assertTrue($t->l('VERY_LIKELY', FeatureInterface::STRENGTH_LOW)); - $this->assertTrue($t->l('LIKELY', FeatureInterface::STRENGTH_LOW)); - $this->assertTrue($t->l('POSSIBLE', FeatureInterface::STRENGTH_LOW)); + public function setUp() + { + $this->stub = TestHelpers::impl(LikelihoodTrait::class); } /** - * @expectedException InvalidArgumentException + * @dataProvider likelihood */ - public function testErr() + public function testLikelihoods($expected, $value, $strength) { - $t = new LikelihoodTraitStub; - - $t->l('foo', 'bar'); + $this->assertEquals($expected, $this->stub->call('likelihood', [ + $value, + $strength + ])); } -} -class LikelihoodTraitStub -{ - use LikelihoodTrait; + public function likelihood() + { + return [ + [true, 'VERY_LIKELY', FeatureInterface::STRENGTH_HIGH], + [false, 'LIKELY', FeatureInterface::STRENGTH_HIGH], + [false, 'POSSIBLE', FeatureInterface::STRENGTH_HIGH], + [true, 'VERY_LIKELY', FeatureInterface::STRENGTH_MEDIUM], + [true, 'LIKELY', FeatureInterface::STRENGTH_MEDIUM], + [false, 'POSSIBLE', FeatureInterface::STRENGTH_MEDIUM], + [true, 'VERY_LIKELY', FeatureInterface::STRENGTH_LOW], + [true, 'LIKELY', FeatureInterface::STRENGTH_LOW], + [true, 'POSSIBLE', FeatureInterface::STRENGTH_LOW], + ]; + } - public function l($value, $strength) + /** + * @expectedException InvalidArgumentException + */ + public function testErr() { - return $this->likelihood($value, $strength); + $this->stub->call('likelihood', ['foo', 'bar']); } } diff --git a/Vision/tests/Unit/Annotation/WebTest.php b/Vision/tests/Unit/Annotation/WebTest.php index 2d9916c14176..2ff918deb38b 100644 --- a/Vision/tests/Unit/Annotation/WebTest.php +++ b/Vision/tests/Unit/Annotation/WebTest.php @@ -65,7 +65,10 @@ public function testMatchingImages() public function testPartialMatchingImages() { $this->assertInstanceOf(WebImage::class, $this->annotation->partialMatchingImages()[0]); - $this->assertEquals($this->info['partialMatchingImages'][0], $this->annotation->partialMatchingImages()[0]->info()); + $this->assertEquals( + $this->info['partialMatchingImages'][0], + $this->annotation->partialMatchingImages()[0]->info() + ); } public function testPages() diff --git a/Vision/tests/Unit/Fixtures.php b/Vision/tests/Unit/Fixtures.php index 1694fe10c588..2a9af3594d48 100644 --- a/Vision/tests/Unit/Fixtures.php +++ b/Vision/tests/Unit/Fixtures.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Vision\Tests\Unit; +//@codingStandardsIgnoreStart class Fixtures { public static function FACE_LANDMARKS_FIXTURE() @@ -29,3 +30,4 @@ public static function EIFFEL_TOWER_FIXTURE() return __DIR__ . '/fixtures/eiffel-tower.jpg'; } } +//@codingStandardsIgnoreStart diff --git a/Vision/tests/Unit/VisionClientTest.php b/Vision/tests/Unit/VisionClientTest.php index 4ad983870405..59723a0bd5dd 100644 --- a/Vision/tests/Unit/VisionClientTest.php +++ b/Vision/tests/Unit/VisionClientTest.php @@ -17,12 +17,13 @@ namespace Google\Cloud\Vision\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\Annotation; use Google\Cloud\Vision\Connection\ConnectionInterface; use Google\Cloud\Vision\Image; use Google\Cloud\Vision\VisionClient; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group vision @@ -35,7 +36,7 @@ class VisionClientTest extends TestCase public function setUp() { - $this->client = new VisionClientStub; + $this->client = TestHelpers::stub(VisionClient::class); $this->connection = $this->prophesize(ConnectionInterface::class); } @@ -65,7 +66,7 @@ public function testAnnotate() ] ]); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $res = $this->client->annotate($image); @@ -83,7 +84,7 @@ public function testAnnotateBatch() ] ]); - $this->client->setConnection($this->connection->reveal()); + $this->client->___setProperty('connection', $this->connection->reveal()); $res = $this->client->annotateBatch([$image]); @@ -101,11 +102,3 @@ public function testAnnotateBatchInvalidImageType() $this->client->annotateBatch(['test']); } } - -class VisionClientStub extends VisionClient -{ - public function setConnection($connection) - { - $this->connection = $connection; - } -} diff --git a/Vision/tests/Unit/VisionHelpersTraitTest.php b/Vision/tests/Unit/VisionHelpersTraitTest.php index cd4621243eeb..5f9f9f0f2c41 100644 --- a/Vision/tests/Unit/VisionHelpersTraitTest.php +++ b/Vision/tests/Unit/VisionHelpersTraitTest.php @@ -17,6 +17,7 @@ namespace Google\Cloud\Vision\Tests\Unit; +use Google\Cloud\Core\Testing\TestHelpers; use Google\Cloud\Vision\V1\AnnotateImageRequest; use Google\Cloud\Vision\V1\AnnotateImageResponse; use Google\Cloud\Vision\V1\BatchAnnotateImagesResponse; @@ -27,8 +28,8 @@ use Google\Cloud\Vision\V1\ImageSource; use Google\Cloud\Vision\VisionHelpersTrait; use InvalidArgumentException; -use Prophecy\Argument; use PHPUnit\Framework\TestCase; +use Prophecy\Argument; /** * @group vision @@ -41,7 +42,7 @@ class VisionHelpersTraitTest extends TestCase public function setUp() { - $this->implementation = \Google\Cloud\Core\Testing\TestHelpers::impl(VisionHelpersTrait::class); + $this->implementation = TestHelpers::impl(VisionHelpersTrait::class); } public function testAnnotateImageHelper() @@ -100,7 +101,7 @@ public function testCreateImageHelper($imageInput, $expectedContent, $expectedUr public function createImageHelperDataProvider() { $content = 'imageresourcecontent'; - $stream = fopen('php://memory','r+'); + $stream = fopen('php://memory', 'r+'); fwrite($stream, $content); rewind($stream); return [ @@ -143,4 +144,3 @@ public function invalidCreateImageHelperDataProvider() ]; } } - diff --git a/phpcs-ruleset.xml b/phpcs-ruleset.xml index 8811c3a9b285..2a9958846d2e 100644 --- a/phpcs-ruleset.xml +++ b/phpcs-ruleset.xml @@ -3,21 +3,25 @@ Storage/src/StreamWrapper.php + Speech/tests/Unit/HttpStreamWrapper.php Core/src/Testing/Lock/MockValues.php + ErrorReporting/tests/Unit/BootstrapTest.php . */src/V[0-9]+ */src/*/V[0-9]+ */src/*/*/V[0-9]+ + */tests/*/V[0-9]+ + */tests/*/*/V[0-9]+ Core/src/Testing OsLogin/src/Common - */tests vendor - tests dev docs - */metadataex + */metadata + Firestore/tests/conformance-fixtures + tests/Component/TestComposerInstall.php diff --git a/tests/System/ServiceWhitelist/WhitelistTest.php b/tests/System/ServiceWhitelist/WhitelistTest.php index bc9a400014f0..a8dba5538975 100644 --- a/tests/System/ServiceWhitelist/WhitelistTest.php +++ b/tests/System/ServiceWhitelist/WhitelistTest.php @@ -48,7 +48,7 @@ public function testPubSubListSnapshotsRest() 'transport' => 'rest' ]); - $this->checkException(function() use ($client) { + $this->checkException(function () use ($client) { iterator_to_array($client->snapshots()); }); } @@ -60,7 +60,7 @@ public function testPubSubListSnapshotsGrpc() 'transport' => 'grpc' ]); - $this->checkException(function() use ($client) { + $this->checkException(function () use ($client) { iterator_to_array($client->snapshots()); }); } diff --git a/tests/Unit/JsonFileTest.php b/tests/Unit/JsonFileTest.php index 7b82b31a2c99..c1a4abc20a01 100644 --- a/tests/Unit/JsonFileTest.php +++ b/tests/Unit/JsonFileTest.php @@ -34,7 +34,6 @@ public function testComposer() $this->assertEquals(JSON_ERROR_NONE, json_last_error()); $this->validateAndAssert($json, 'composer.json.schema'); - } /** @@ -81,7 +80,8 @@ private function validateAndAssert($input, $schemaPath) { $schema = file_get_contents(sprintf( self::SCHEMA_PATH, - __DIR__, $schemaPath + __DIR__, + $schemaPath )); $validator = Schema::import(json_decode($schema));