Merge pull request #3979 from stanley-cheung/php_cs_fixer

PHP: ran php-cs-fixer to comply with php coding standard
pull/3985/head
Michael Lumish 9 years ago
commit 5fc4f77e11
  1. 40
      src/php/bin/run_php_cs_fixer.sh
  2. 34
      src/php/lib/Grpc/AbstractCall.php
  3. 139
      src/php/lib/Grpc/BaseStub.php
  4. 41
      src/php/lib/Grpc/BidiStreamingCall.php
  5. 30
      src/php/lib/Grpc/ClientStreamingCall.php
  6. 35
      src/php/lib/Grpc/ServerStreamingCall.php
  7. 23
      src/php/lib/Grpc/UnaryCall.php
  8. 104
      src/php/tests/generated_code/AbstractGeneratedCodeTest.php
  9. 11
      src/php/tests/generated_code/GeneratedCodeTest.php
  10. 18
      src/php/tests/generated_code/GeneratedCodeWithCallbackTest.php
  11. 29
      src/php/tests/generated_code/math_client.php
  12. 135
      src/php/tests/interop/interop_client.php
  13. 38
      src/php/tests/unit_tests/CallTest.php
  14. 53
      src/php/tests/unit_tests/EndToEndTest.php
  15. 51
      src/php/tests/unit_tests/SecureEndToEndTest.php
  16. 24
      src/php/tests/unit_tests/TimevalTest.php

@ -0,0 +1,40 @@
#!/bin/bash
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
set -e
command -v php-cs-fixer > /dev/null || {
echo "Cannot find php-cs-fixer. Exiting..."
exit 1
}
cd $(dirname $0)/..
php-cs-fixer fix lib/Grpc || true
php-cs-fixer fix tests/generated_code || true
php-cs-fixer fix tests/interop || true
php-cs-fixer fix tests/unit_tests || true

@ -31,23 +31,30 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Grpc;
abstract class AbstractCall {
namespace Grpc;
abstract class AbstractCall
{
protected $call;
protected $deserialize;
protected $metadata;
/**
* Create a new Call wrapper object.
*
* @param Channel $channel The channel to communicate on
* @param string $method The method to call on the remote server
* @param string $method The method to call on the
* remote server
* @param callback $deserialize A callback function to deserialize
* the response
* @param (optional) long $timeout Timeout in microseconds
*/
public function __construct(Channel $channel, $method, $deserialize, $timeout = false) {
public function __construct(Channel $channel,
$method,
$deserialize,
$timeout = false)
{
if ($timeout) {
$now = Timeval::now();
$delta = new Timeval($timeout);
@ -63,33 +70,40 @@ abstract class AbstractCall {
/**
* @return The metadata sent by the server.
*/
public function getMetadata() {
public function getMetadata()
{
return $this->metadata;
}
/**
* @return string The URI of the endpoint.
*/
public function getPeer() {
public function getPeer()
{
return $this->call->getPeer();
}
/**
* Cancels the call
* Cancels the call.
*/
public function cancel() {
public function cancel()
{
$this->call->cancel();
}
/**
* Deserialize a response value to an object.
*
* @param string $value The binary value to deserialize
*
* @return The deserialized value
*/
protected function deserializeResponse($value) {
protected function deserializeResponse($value)
{
if ($value === null) {
return null;
return;
}
return call_user_func($this->deserialize, $value);
}
}

@ -31,14 +31,15 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Grpc;
/**
* Base class for generated client stubs. Stub methods are expected to call
* _simpleRequest or _streamRequest and return the result.
*/
class BaseStub {
class BaseStub
{
private $hostname;
private $channel;
@ -51,7 +52,8 @@ class BaseStub {
* - 'update_metadata': (optional) a callback function which takes in a
* metadata array, and returns an updated metadata array
*/
public function __construct($hostname, $opts) {
public function __construct($hostname, $opts)
{
$this->hostname = $hostname;
$this->update_metadata = null;
if (isset($opts['update_metadata'])) {
@ -61,33 +63,38 @@ class BaseStub {
unset($opts['update_metadata']);
}
$package_config = json_decode(
file_get_contents(dirname(__FILE__) . '/../../composer.json'), true);
file_get_contents(dirname(__FILE__).'/../../composer.json'), true);
$opts['grpc.primary_user_agent'] =
'grpc-php/' . $package_config['version'];
'grpc-php/'.$package_config['version'];
$this->channel = new Channel($hostname, $opts);
}
/**
* @return string The URI of the endpoint.
*/
public function getTarget() {
public function getTarget()
{
return $this->channel->getTarget();
}
/**
* @param $try_to_connect bool
*
* @return int The grpc connectivity state
*/
public function getConnectivityState($try_to_connect = false) {
public function getConnectivityState($try_to_connect = false)
{
return $this->channel->getConnectivityState($try_to_connect);
}
/**
* @param $timeout in microseconds
*
* @return bool true if channel is ready
* @throw Exception if channel is in FATAL_ERROR state
*/
public function waitForReady($timeout) {
public function waitForReady($timeout)
{
$new_state = $this->getConnectivityState(true);
if ($this->_checkConnectivityState($new_state)) {
return true;
@ -106,62 +113,74 @@ class BaseStub {
}
// deadline has passed
$new_state = $this->getConnectivityState();
return $this->_checkConnectivityState($new_state);
}
private function _checkConnectivityState($new_state) {
private function _checkConnectivityState($new_state)
{
if ($new_state == \Grpc\CHANNEL_READY) {
return true;
}
if ($new_state == \Grpc\CHANNEL_FATAL_FAILURE) {
// @codeCoverageIgnoreStart
throw new \Exception('Failed to connect to server');
// @codeCoverageIgnoreEnd
}
return false;
}
/**
* Close the communication channel associated with this stub
* Close the communication channel associated with this stub.
*/
public function close() {
public function close()
{
$this->channel->close();
}
/**
* constructs the auth uri for the jwt
* constructs the auth uri for the jwt.
*/
private function _get_jwt_aud_uri($method) {
private function _get_jwt_aud_uri($method)
{
$last_slash_idx = strrpos($method, '/');
if ($last_slash_idx === false) {
throw new \InvalidArgumentException('service name must have a slash');
throw new \InvalidArgumentException(
'service name must have a slash');
}
$service_name = substr($method, 0, $last_slash_idx);
return "https://" . $this->hostname . $service_name;
return 'https://'.$this->hostname.$service_name;
}
/**
* extract $timeout from $metadata
* extract $timeout from $metadata.
*
* @param $metadata The metadata map
*
* @return list($metadata_copy, $timeout)
*/
private function _extract_timeout_from_metadata($metadata) {
private function _extract_timeout_from_metadata($metadata)
{
$timeout = false;
$metadata_copy = $metadata;
if (isset($metadata['timeout'])) {
$timeout = $metadata['timeout'];
unset($metadata_copy['timeout']);
}
return [$metadata_copy, $timeout];
}
/**
* validate and normalize the metadata array
* validate and normalize the metadata array.
*
* @param $metadata The metadata map
*
* @return $metadata Validated and key-normalized metadata map
* @throw InvalidArgumentException if key contains invalid characters
*/
private function _validate_and_normalize_metadata($metadata) {
private function _validate_and_normalize_metadata($metadata)
{
$metadata_copy = [];
foreach ($metadata as $key => $value) {
if (!preg_match('/^[A-Za-z\d_-]+$/', $key)) {
@ -171,115 +190,149 @@ class BaseStub {
}
$metadata_copy[strtolower($key)] = $value;
}
return $metadata_copy;
}
/* This class is intended to be subclassed by generated code, so all functions
begin with "_" to avoid name collisions. */
/* This class is intended to be subclassed by generated code, so
* all functions begin with "_" to avoid name collisions. */
/**
* Call a remote method that takes a single argument and has a single output
* Call a remote method that takes a single argument and has a
* single output.
*
* @param string $method The name of the method to call
* @param $argument The argument to the method
* @param callable $deserialize A function that deserializes the response
* @param array $metadata A metadata map to send to the server
*
* @return SimpleSurfaceActiveCall The active call object
*/
public function _simpleRequest($method,
$argument,
callable $deserialize,
$metadata = [],
$options = []) {
list($actual_metadata, $timeout) = $this->_extract_timeout_from_metadata($metadata);
$call = new UnaryCall($this->channel, $method, $deserialize, $timeout);
$options = [])
{
list($actual_metadata, $timeout) =
$this->_extract_timeout_from_metadata($metadata);
$call = new UnaryCall($this->channel,
$method,
$deserialize,
$timeout);
$jwt_aud_uri = $this->_get_jwt_aud_uri($method);
if (is_callable($this->update_metadata)) {
$actual_metadata = call_user_func($this->update_metadata,
$actual_metadata,
$jwt_aud_uri);
}
$actual_metadata = $this->_validate_and_normalize_metadata($actual_metadata);
$actual_metadata = $this->_validate_and_normalize_metadata(
$actual_metadata);
$call->start($argument, $actual_metadata, $options);
return $call;
}
/**
* Call a remote method that takes a stream of arguments and has a single
* output
* output.
*
* @param string $method The name of the method to call
* @param $arguments An array or Traversable of arguments to stream to the
* server
* @param callable $deserialize A function that deserializes the response
* @param array $metadata A metadata map to send to the server
*
* @return ClientStreamingSurfaceActiveCall The active call object
*/
public function _clientStreamRequest($method,
callable $deserialize,
$metadata = []) {
list($actual_metadata, $timeout) = $this->_extract_timeout_from_metadata($metadata);
$call = new ClientStreamingCall($this->channel, $method, $deserialize, $timeout);
$metadata = [])
{
list($actual_metadata, $timeout) =
$this->_extract_timeout_from_metadata($metadata);
$call = new ClientStreamingCall($this->channel,
$method,
$deserialize,
$timeout);
$jwt_aud_uri = $this->_get_jwt_aud_uri($method);
if (is_callable($this->update_metadata)) {
$actual_metadata = call_user_func($this->update_metadata,
$actual_metadata,
$jwt_aud_uri);
}
$actual_metadata = $this->_validate_and_normalize_metadata($actual_metadata);
$actual_metadata = $this->_validate_and_normalize_metadata(
$actual_metadata);
$call->start($actual_metadata);
return $call;
}
/**
* Call a remote method that takes a single argument and returns a stream of
* responses
* responses.
*
* @param string $method The name of the method to call
* @param $argument The argument to the method
* @param callable $deserialize A function that deserializes the responses
* @param array $metadata A metadata map to send to the server
*
* @return ServerStreamingSurfaceActiveCall The active call object
*/
public function _serverStreamRequest($method,
$argument,
callable $deserialize,
$metadata = [],
$options = []) {
list($actual_metadata, $timeout) = $this->_extract_timeout_from_metadata($metadata);
$call = new ServerStreamingCall($this->channel, $method, $deserialize, $timeout);
$options = [])
{
list($actual_metadata, $timeout) =
$this->_extract_timeout_from_metadata($metadata);
$call = new ServerStreamingCall($this->channel,
$method,
$deserialize,
$timeout);
$jwt_aud_uri = $this->_get_jwt_aud_uri($method);
if (is_callable($this->update_metadata)) {
$actual_metadata = call_user_func($this->update_metadata,
$actual_metadata,
$jwt_aud_uri);
}
$actual_metadata = $this->_validate_and_normalize_metadata($actual_metadata);
$actual_metadata = $this->_validate_and_normalize_metadata(
$actual_metadata);
$call->start($argument, $actual_metadata, $options);
return $call;
}
/**
* Call a remote method with messages streaming in both directions
* Call a remote method with messages streaming in both directions.
*
* @param string $method The name of the method to call
* @param callable $deserialize A function that deserializes the responses
* @param array $metadata A metadata map to send to the server
*
* @return BidiStreamingSurfaceActiveCall The active call object
*/
public function _bidiRequest($method,
callable $deserialize,
$metadata = []) {
list($actual_metadata, $timeout) = $this->_extract_timeout_from_metadata($metadata);
$call = new BidiStreamingCall($this->channel, $method, $deserialize, $timeout);
$metadata = [])
{
list($actual_metadata, $timeout) =
$this->_extract_timeout_from_metadata($metadata);
$call = new BidiStreamingCall($this->channel,
$method,
$deserialize,
$timeout);
$jwt_aud_uri = $this->_get_jwt_aud_uri($method);
if (is_callable($this->update_metadata)) {
$actual_metadata = call_user_func($this->update_metadata,
$actual_metadata,
$jwt_aud_uri);
}
$actual_metadata = $this->_validate_and_normalize_metadata($actual_metadata);
$actual_metadata = $this->_validate_and_normalize_metadata(
$actual_metadata);
$call->start($actual_metadata);
return $call;
}
}

@ -31,26 +31,34 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Grpc;
/**
* Represents an active call that allows for sending and recieving messages in
* streams in any order.
*/
class BidiStreamingCall extends AbstractCall {
class BidiStreamingCall extends AbstractCall
{
/**
* Start the call
* Start the call.
*
* @param array $metadata Metadata to send with the call, if applicable
*/
public function start($metadata = []) {
$this->call->startBatch([OP_SEND_INITIAL_METADATA => $metadata]);
public function start($metadata = [])
{
$this->call->startBatch([
OP_SEND_INITIAL_METADATA => $metadata,
]);
}
/**
* Reads the next value from the server.
*
* @return The next value from the server, or null if there is none
*/
public function read() {
public function read()
{
$batch = [OP_RECV_MESSAGE => true];
if ($this->metadata === null) {
$batch[OP_RECV_INITIAL_METADATA] = true;
@ -59,40 +67,51 @@ class BidiStreamingCall extends AbstractCall {
if ($this->metadata === null) {
$this->metadata = $read_event->metadata;
}
return $this->deserializeResponse($read_event->message);
}
/**
* Write a single message to the server. This cannot be called after
* writesDone is called.
*
* @param ByteBuffer $data The data to write
* @param array $options an array of options, possible keys:
* 'flags' => a number
*/
public function write($data, $options = []) {
public function write($data, $options = [])
{
$message_array = ['message' => $data->serialize()];
if (isset($options['flags'])) {
$message_array['flags'] = $options['flags'];
}
$this->call->startBatch([OP_SEND_MESSAGE => $message_array]);
$this->call->startBatch([
OP_SEND_MESSAGE => $message_array,
]);
}
/**
* Indicate that no more writes will be sent.
*/
public function writesDone() {
$this->call->startBatch([OP_SEND_CLOSE_FROM_CLIENT => true]);
public function writesDone()
{
$this->call->startBatch([
OP_SEND_CLOSE_FROM_CLIENT => true,
]);
}
/**
* Wait for the server to send the status, and return it.
*
* @return object The status object, with integer $code, string $details,
* and array $metadata members
*/
public function getStatus() {
public function getStatus()
{
$status_event = $this->call->startBatch([
OP_RECV_STATUS_ON_CLIENT => true
OP_RECV_STATUS_ON_CLIENT => true,
]);
return $status_event->status;
}
}

@ -31,47 +31,61 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Grpc;
/**
* Represents an active call that sends a stream of messages and then gets a
* single response.
*/
class ClientStreamingCall extends AbstractCall {
class ClientStreamingCall extends AbstractCall
{
/**
* Start the call.
*
* @param array $metadata Metadata to send with the call, if applicable
*/
public function start($metadata = []) {
$this->call->startBatch([OP_SEND_INITIAL_METADATA => $metadata]);
public function start($metadata = [])
{
$this->call->startBatch([
OP_SEND_INITIAL_METADATA => $metadata,
]);
}
/**
* Write a single message to the server. This cannot be called after
* wait is called.
*
* @param ByteBuffer $data The data to write
* @param array $options an array of options, possible keys:
* 'flags' => a number
*/
public function write($data, $options = []) {
public function write($data, $options = [])
{
$message_array = ['message' => $data->serialize()];
if (isset($options['flags'])) {
$message_array['flags'] = $options['flags'];
}
$this->call->startBatch([OP_SEND_MESSAGE => $message_array]);
$this->call->startBatch([
OP_SEND_MESSAGE => $message_array,
]);
}
/**
* Wait for the server to respond with data and a status
* Wait for the server to respond with data and a status.
*
* @return [response data, status]
*/
public function wait() {
public function wait()
{
$event = $this->call->startBatch([
OP_SEND_CLOSE_FROM_CLIENT => true,
OP_RECV_INITIAL_METADATA => true,
OP_RECV_MESSAGE => true,
OP_RECV_STATUS_ON_CLIENT => true]);
OP_RECV_STATUS_ON_CLIENT => true,
]);
$this->metadata = $event->metadata;
return [$this->deserializeResponse($event->message), $event->status];
}
}

@ -31,21 +31,25 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Grpc;
/**
* Represents an active call that sends a single message and then gets a stream
* of reponses
* of reponses.
*/
class ServerStreamingCall extends AbstractCall {
class ServerStreamingCall extends AbstractCall
{
/**
* Start the call
* Start the call.
*
* @param $data The data to send
* @param array $metadata Metadata to send with the call, if applicable
* @param array $options an array of options, possible keys:
* 'flags' => a number
*/
public function start($data, $metadata = [], $options = []) {
public function start($data, $metadata = [], $options = [])
{
$message_array = ['message' => $data->serialize()];
if (isset($options['flags'])) {
$message_array['flags'] = $options['flags'];
@ -54,30 +58,39 @@ class ServerStreamingCall extends AbstractCall {
OP_SEND_INITIAL_METADATA => $metadata,
OP_RECV_INITIAL_METADATA => true,
OP_SEND_MESSAGE => $message_array,
OP_SEND_CLOSE_FROM_CLIENT => true]);
OP_SEND_CLOSE_FROM_CLIENT => true,
]);
$this->metadata = $event->metadata;
}
/**
* @return An iterator of response values
*/
public function responses() {
$response = $this->call->startBatch([OP_RECV_MESSAGE => true])->message;
while($response !== null) {
public function responses()
{
$response = $this->call->startBatch([
OP_RECV_MESSAGE => true,
])->message;
while ($response !== null) {
yield $this->deserializeResponse($response);
$response = $this->call->startBatch([OP_RECV_MESSAGE => true])->message;
$response = $this->call->startBatch([
OP_RECV_MESSAGE => true,
])->message;
}
}
/**
* Wait for the server to send the status, and return it.
*
* @return object The status object, with integer $code, string $details,
* and array $metadata members
*/
public function getStatus() {
public function getStatus()
{
$status_event = $this->call->startBatch([
OP_RECV_STATUS_ON_CLIENT => true
OP_RECV_STATUS_ON_CLIENT => true,
]);
return $status_event->status;
}
}

@ -31,21 +31,25 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Grpc;
/**
* Represents an active call that sends a single message and then gets a single
* response.
*/
class UnaryCall extends AbstractCall {
class UnaryCall extends AbstractCall
{
/**
* Start the call
* Start the call.
*
* @param $data The data to send
* @param array $metadata Metadata to send with the call, if applicable
* @param array $options an array of options, possible keys:
* 'flags' => a number
*/
public function start($data, $metadata = [], $options = []) {
public function start($data, $metadata = [], $options = [])
{
$message_array = ['message' => $data->serialize()];
if (isset($options['flags'])) {
$message_array['flags'] = $options['flags'];
@ -54,18 +58,23 @@ class UnaryCall extends AbstractCall {
OP_SEND_INITIAL_METADATA => $metadata,
OP_RECV_INITIAL_METADATA => true,
OP_SEND_MESSAGE => $message_array,
OP_SEND_CLOSE_FROM_CLIENT => true]);
OP_SEND_CLOSE_FROM_CLIENT => true,
]);
$this->metadata = $event->metadata;
}
/**
* Wait for the server to respond with data and a status
* Wait for the server to respond with data and a status.
*
* @return [response data, status]
*/
public function wait() {
public function wait()
{
$event = $this->call->startBatch([
OP_RECV_MESSAGE => true,
OP_RECV_STATUS_ON_CLIENT => true]);
OP_RECV_STATUS_ON_CLIENT => true,
]);
return [$this->deserializeResponse($event->message), $event->status];
}
}

@ -31,36 +31,44 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once realpath(dirname(__FILE__) . '/../../vendor/autoload.php');
require_once dirname(__FILE__) . '/math.php';
require_once realpath(dirname(__FILE__).'/../../vendor/autoload.php');
require_once dirname(__FILE__).'/math.php';
abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
/* These tests require that a server exporting the math service must be
* running on $GRPC_TEST_HOST */
abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase
{
/**
* These tests require that a server exporting the math service must be
* running on $GRPC_TEST_HOST.
*/
protected static $client;
protected static $timeout;
public function testWaitForNotReady() {
public function testWaitForNotReady()
{
$this->assertFalse(self::$client->waitForReady(1));
}
public function testWaitForReady() {
public function testWaitForReady()
{
$this->assertTrue(self::$client->waitForReady(250000));
}
public function testAlreadyReady() {
public function testAlreadyReady()
{
$this->assertTrue(self::$client->waitForReady(250000));
$this->assertTrue(self::$client->waitForReady(100));
}
public function testGetTarget() {
public function testGetTarget()
{
$this->assertTrue(is_string(self::$client->getTarget()));
}
/**
* @expectedException InvalidArgumentException
*/
public function testClose() {
public function testClose()
{
self::$client->close();
$div_arg = new math\DivArgs();
$call = self::$client->Div($div_arg);
@ -69,25 +77,29 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException InvalidArgumentException
*/
public function testInvalidMetadata() {
public function testInvalidMetadata()
{
$div_arg = new math\DivArgs();
$call = self::$client->Div($div_arg, array(' ' => 'abc123'));
$call = self::$client->Div($div_arg, [' ' => 'abc123']);
}
public function testGetCallMetadata() {
public function testGetCallMetadata()
{
$div_arg = new math\DivArgs();
$call = self::$client->Div($div_arg);
$this->assertTrue(is_array($call->getMetadata()));
}
public function testTimeout() {
public function testTimeout()
{
$div_arg = new math\DivArgs();
$call = self::$client->Div($div_arg, array('timeout' => 100));
$call = self::$client->Div($div_arg, ['timeout' => 100]);
list($response, $status) = $call->wait();
$this->assertSame(\Grpc\STATUS_DEADLINE_EXCEEDED, $status->code);
}
public function testCancel() {
public function testCancel()
{
$div_arg = new math\DivArgs();
$call = self::$client->Div($div_arg);
$call->cancel();
@ -98,17 +110,20 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException InvalidArgumentException
*/
public function testInvalidMethodName() {
$invalid_client = new DummyInvalidClient('host', array());
public function testInvalidMethodName()
{
$invalid_client = new DummyInvalidClient('host', []);
$div_arg = new math\DivArgs();
$invalid_client->InvalidUnaryCall($div_arg);
}
public function testWriteFlags() {
public function testWriteFlags()
{
$div_arg = new math\DivArgs();
$div_arg->setDividend(7);
$div_arg->setDivisor(4);
$call = self::$client->Div($div_arg, array(), array('flags' => Grpc\WRITE_NO_COMPRESS));
$call = self::$client->Div($div_arg, [],
['flags' => Grpc\WRITE_NO_COMPRESS]);
$this->assertTrue(is_string($call->getPeer()));
list($response, $status) = $call->wait();
$this->assertSame(1, $response->getQuotient());
@ -116,37 +131,42 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
$this->assertSame(\Grpc\STATUS_OK, $status->code);
}
public function testWriteFlagsServerStreaming() {
public function testWriteFlagsServerStreaming()
{
$fib_arg = new math\FibArgs();
$fib_arg->setLimit(7);
$call = self::$client->Fib($fib_arg, array(), array('flags' => Grpc\WRITE_NO_COMPRESS));
$call = self::$client->Fib($fib_arg, [],
['flags' => Grpc\WRITE_NO_COMPRESS]);
$result_array = iterator_to_array($call->responses());
$status = $call->getStatus();
$this->assertSame(\Grpc\STATUS_OK, $status->code);
}
public function testWriteFlagsClientStreaming() {
public function testWriteFlagsClientStreaming()
{
$call = self::$client->Sum();
$num = new math\Num();
$num->setNum(1);
$call->write($num, array('flags' => Grpc\WRITE_NO_COMPRESS));
$call->write($num, ['flags' => Grpc\WRITE_NO_COMPRESS]);
list($response, $status) = $call->wait();
$this->assertSame(\Grpc\STATUS_OK, $status->code);
}
public function testWriteFlagsBidiStreaming() {
public function testWriteFlagsBidiStreaming()
{
$call = self::$client->DivMany();
$div_arg = new math\DivArgs();
$div_arg->setDividend(7);
$div_arg->setDivisor(4);
$call->write($div_arg, array('flags' => Grpc\WRITE_NO_COMPRESS));
$call->write($div_arg, ['flags' => Grpc\WRITE_NO_COMPRESS]);
$response = $call->read();
$call->writesDone();
$status = $call->getStatus();
$this->assertSame(\Grpc\STATUS_OK, $status->code);
}
public function testSimpleRequest() {
public function testSimpleRequest()
{
$div_arg = new math\DivArgs();
$div_arg->setDividend(7);
$div_arg->setDivisor(4);
@ -158,13 +178,14 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
$this->assertSame(\Grpc\STATUS_OK, $status->code);
}
public function testServerStreaming() {
public function testServerStreaming()
{
$fib_arg = new math\FibArgs();
$fib_arg->setLimit(7);
$call = self::$client->Fib($fib_arg);
$this->assertTrue(is_string($call->getPeer()));
$result_array = iterator_to_array($call->responses());
$extract_num = function($num){
$extract_num = function ($num) {
return $num->getNum();
};
$values = array_map($extract_num, $result_array);
@ -173,10 +194,11 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
$this->assertSame(\Grpc\STATUS_OK, $status->code);
}
public function testClientStreaming() {
public function testClientStreaming()
{
$call = self::$client->Sum();
$this->assertTrue(is_string($call->getPeer()));
for ($i = 0; $i < 7; $i++) {
for ($i = 0; $i < 7; ++$i) {
$num = new math\Num();
$num->setNum($i);
$call->write($num);
@ -186,10 +208,11 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
$this->assertSame(\Grpc\STATUS_OK, $status->code);
}
public function testBidiStreaming() {
public function testBidiStreaming()
{
$call = self::$client->DivMany();
$this->assertTrue(is_string($call->getPeer()));
for ($i = 0; $i < 7; $i++) {
for ($i = 0; $i < 7; ++$i) {
$div_arg = new math\DivArgs();
$div_arg->setDividend(2 * $i + 1);
$div_arg->setDivisor(2);
@ -204,11 +227,16 @@ abstract class AbstractGeneratedCodeTest extends PHPUnit_Framework_TestCase {
}
}
class DummyInvalidClient extends \Grpc\BaseStub {
class DummyInvalidClient extends \Grpc\BaseStub
{
public function InvalidUnaryCall(\math\DivArgs $argument,
$metadata = array(),
$options = array()) {
return $this->_simpleRequest('invalidMethodName', $argument,
function() {}, $metadata, $options);
$metadata = [],
$options = [])
{
return $this->_simpleRequest('invalidMethodName',
$argument,
function () {},
$metadata,
$options);
}
}

@ -31,15 +31,18 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once dirname(__FILE__) . '/AbstractGeneratedCodeTest.php';
require_once dirname(__FILE__).'/AbstractGeneratedCodeTest.php';
class GeneratedCodeTest extends AbstractGeneratedCodeTest {
public function setUp() {
class GeneratedCodeTest extends AbstractGeneratedCodeTest
{
public function setUp()
{
self::$client = new math\MathClient(
getenv('GRPC_TEST_HOST'), []);
}
public static function tearDownAfterClass() {
public static function tearDownAfterClass()
{
self::$client->close();
}
}

@ -31,21 +31,25 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once dirname(__FILE__) . '/AbstractGeneratedCodeTest.php';
require_once dirname(__FILE__).'/AbstractGeneratedCodeTest.php';
class GeneratedCodeWithCallbackTest extends AbstractGeneratedCodeTest {
public function setUp() {
class GeneratedCodeWithCallbackTest extends AbstractGeneratedCodeTest
{
public function setUp()
{
self::$client = new math\MathClient(
getenv('GRPC_TEST_HOST'), ['update_metadata' =>
function($a_hash,
$client = array()) {
getenv('GRPC_TEST_HOST'),
['update_metadata' => function ($a_hash,
$client = []) {
$a_copy = $a_hash;
$a_copy['foo'] = ['bar'];
return $a_copy;
}]);
}
public static function tearDownAfterClass() {
public static function tearDownAfterClass()
{
self::$client->close();
}
}

@ -36,31 +36,32 @@
include 'vendor/autoload.php';
include 'tests/generated_code/math.php';
function p($line) {
function p($line)
{
print("$line<br/>\n");
}
$host = "localhost:50051";
$host = 'localhost:50051';
p("Connecting to host: $host");
$client = new math\MathClient($host, []);
p("Client class: ".get_class($client));
p('Client class: '.get_class($client));
p('');
p("Running unary call test:");
p('Running unary call test:');
$dividend = 7;
$divisor = 4;
$div_arg = new math\DivArgs();
$div_arg->setDividend($dividend);
$div_arg->setDivisor($divisor);
$call = $client->Div($div_arg);
p("Call peer: ".$call->getPeer());
p('Call peer: '.$call->getPeer());
p("Dividing $dividend by $divisor");
list($response, $status) = $call->wait();
p("quotient = ".$response->getQuotient());
p("remainder = ".$response->getRemainder());
p('quotient = '.$response->getQuotient());
p('remainder = '.$response->getRemainder());
p('');
p("Running server streaming test:");
p('Running server streaming test:');
$limit = 7;
$fib_arg = new math\FibArgs();
$fib_arg->setLimit($limit);
@ -73,21 +74,21 @@ foreach ($result_array as $num) {
p("The first $limit Fibonacci numbers are:".$result);
p('');
p("Running client streaming test:");
p('Running client streaming test:');
$call = $client->Sum();
for ($i = 0; $i <= $limit; $i++) {
for ($i = 0; $i <= $limit; ++$i) {
$num = new math\Num();
$num->setNum($i);
$call->write($num);
}
list($response, $status) = $call->wait();
p(sprintf("The first %d positive integers sum to: %d",
p(sprintf('The first %d positive integers sum to: %d',
$limit, $response->getNum()));
p('');
p("Running bidi-streaming test:");
p('Running bidi-streaming test:');
$call = $client->DivMany();
for ($i = 0; $i < 7; $i++) {
for ($i = 0; $i < 7; ++$i) {
$div_arg = new math\DivArgs();
$dividend = 2 * $i + 1;
$divisor = 3;
@ -96,7 +97,7 @@ for ($i = 0; $i < 7; $i++) {
$call->write($div_arg);
p("client writing: $dividend / $divisor");
$response = $call->read();
p(sprintf("server writing: quotient = %d, remainder = %d",
p(sprintf('server writing: quotient = %d, remainder = %d',
$response->getQuotient(), $response->getRemainder()));
}
$call->writesDone();

@ -31,7 +31,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
require_once realpath(dirname(__FILE__) . '/../../vendor/autoload.php');
require_once realpath(dirname(__FILE__).'/../../vendor/autoload.php');
require 'empty.php';
require 'messages.php';
require 'test.php';
@ -41,22 +41,26 @@ use GuzzleHttp\ClientInterface;
/**
* Assertion function that always exits with an error code if the assertion is
* falsy
* falsy.
*
* @param $value Assertion value. Should be true.
* @param $error_message Message to display if the assertion is false
*/
function hardAssert($value, $error_message) {
function hardAssert($value, $error_message)
{
if (!$value) {
echo $error_message . "\n";
echo $error_message."\n";
exit(1);
}
}
/**
* Run the empty_unary test.
*
* @param $stub Stub object that has service methods
*/
function emptyUnary($stub) {
function emptyUnary($stub)
{
list($result, $status) = $stub->EmptyCall(new grpc\testing\EmptyMessage())->wait();
hardAssert($status->code === Grpc\STATUS_OK, 'Call did not complete successfully');
hardAssert($result !== null, 'Call completed with a null response');
@ -64,20 +68,24 @@ function emptyUnary($stub) {
/**
* Run the large_unary test.
*
* @param $stub Stub object that has service methods
*/
function largeUnary($stub) {
function largeUnary($stub)
{
performLargeUnary($stub);
}
/**
* Shared code between large unary test and auth test
* Shared code between large unary test and auth test.
*
* @param $stub Stub object that has service methods
* @param $fillUsername boolean whether to fill result with username
* @param $fillOauthScope boolean whether to fill result with oauth scope
*/
function performLargeUnary($stub, $fillUsername = false, $fillOauthScope = false,
$metadata = array()) {
$metadata = [])
{
$request_len = 271828;
$response_len = 314159;
@ -101,22 +109,25 @@ function performLargeUnary($stub, $fillUsername = false, $fillOauthScope = false
'Payload had the wrong length');
hardAssert($payload->getBody() === str_repeat("\0", $response_len),
'Payload had the wrong content');
return $result;
}
/**
* Run the service account credentials auth test.
*
* @param $stub Stub object that has service methods
* @param $args array command line args
*/
function serviceAccountCreds($stub, $args) {
function serviceAccountCreds($stub, $args)
{
if (!array_key_exists('oauth_scope', $args)) {
throw new Exception('Missing oauth scope');
}
$jsonKey = json_decode(
file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
true);
$result = performLargeUnary($stub, $fillUsername=true, $fillOauthScope=true);
$result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = true);
hardAssert($result->getUsername() == $jsonKey['client_email'],
'invalid email returned');
hardAssert(strpos($args['oauth_scope'], $result->getOauthScope()) !== false,
@ -125,56 +136,64 @@ function serviceAccountCreds($stub, $args) {
/**
* Run the compute engine credentials auth test.
* Has not been run from gcloud as of 2015-05-05
* Has not been run from gcloud as of 2015-05-05.
*
* @param $stub Stub object that has service methods
* @param $args array command line args
*/
function computeEngineCreds($stub, $args) {
function computeEngineCreds($stub, $args)
{
if (!array_key_exists('oauth_scope', $args)) {
throw new Exception('Missing oauth scope');
}
if (!array_key_exists('default_service_account', $args)) {
throw new Exception('Missing default_service_account');
}
$result = performLargeUnary($stub, $fillUsername=true, $fillOauthScope=true);
$result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = true);
hardAssert($args['default_service_account'] == $result->getUsername(),
'invalid email returned');
}
/**
* Run the jwt token credentials auth test.
*
* @param $stub Stub object that has service methods
* @param $args array command line args
*/
function jwtTokenCreds($stub, $args) {
function jwtTokenCreds($stub, $args)
{
$jsonKey = json_decode(
file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
true);
$result = performLargeUnary($stub, $fillUsername=true, $fillOauthScope=true);
$result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = true);
hardAssert($result->getUsername() == $jsonKey['client_email'],
'invalid email returned');
}
/**
* Run the oauth2_auth_token auth test.
*
* @param $stub Stub object that has service methods
* @param $args array command line args
*/
function oauth2AuthToken($stub, $args) {
function oauth2AuthToken($stub, $args)
{
$jsonKey = json_decode(
file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
true);
$result = performLargeUnary($stub, $fillUsername=true, $fillOauthScope=true);
$result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = true);
hardAssert($result->getUsername() == $jsonKey['client_email'],
'invalid email returned');
}
/**
* Run the per_rpc_creds auth test.
*
* @param $stub Stub object that has service methods
* @param $args array command line args
*/
function perRpcCreds($stub, $args) {
function perRpcCreds($stub, $args)
{
$jsonKey = json_decode(
file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
true);
@ -182,11 +201,10 @@ function perRpcCreds($stub, $args) {
$args['oauth_scope']
);
$token = $auth_credentials->fetchAuthToken();
$metadata = array(CredentialsLoader::AUTH_METADATA_KEY =>
array(sprintf("%s %s",
$metadata = [CredentialsLoader::AUTH_METADATA_KEY => [sprintf('%s %s',
$token['token_type'],
$token['access_token'])));
$result = performLargeUnary($stub, $fillUsername=true, $fillOauthScope=true,
$token['access_token'])]];
$result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = true,
$metadata);
hardAssert($result->getUsername() == $jsonKey['client_email'],
'invalid email returned');
@ -194,17 +212,20 @@ function perRpcCreds($stub, $args) {
/**
* Run the client_streaming test.
*
* @param $stub Stub object that has service methods
*/
function clientStreaming($stub) {
$request_lengths = array(27182, 8, 1828, 45904);
function clientStreaming($stub)
{
$request_lengths = [27182, 8, 1828, 45904];
$requests = array_map(
function($length) {
function ($length) {
$request = new grpc\testing\StreamingInputCallRequest();
$payload = new grpc\testing\Payload();
$payload->setBody(str_repeat("\0", $length));
$request->setPayload($payload);
return $request;
}, $request_lengths);
@ -220,14 +241,16 @@ function clientStreaming($stub) {
/**
* Run the server_streaming test.
*
* @param $stub Stub object that has service methods.
*/
function serverStreaming($stub) {
$sizes = array(31415, 9, 2653, 58979);
function serverStreaming($stub)
{
$sizes = [31415, 9, 2653, 58979];
$request = new grpc\testing\StreamingOutputCallRequest();
$request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
foreach($sizes as $size) {
foreach ($sizes as $size) {
$response_parameters = new grpc\testing\ResponseParameters();
$response_parameters->setSize($size);
$request->addResponseParameters($response_parameters);
@ -235,13 +258,13 @@ function serverStreaming($stub) {
$call = $stub->StreamingOutputCall($request);
$i = 0;
foreach($call->responses() as $value) {
foreach ($call->responses() as $value) {
hardAssert($i < 4, 'Too many responses');
$payload = $value->getPayload();
hardAssert($payload->getType() === grpc\testing\PayloadType::COMPRESSABLE,
'Payload ' . $i . ' had the wrong type');
'Payload '.$i.' had the wrong type');
hardAssert(strlen($payload->getBody()) === $sizes[$i],
'Response ' . $i . ' had the wrong length');
'Response '.$i.' had the wrong length');
$i += 1;
}
hardAssert($call->getStatus()->code === Grpc\STATUS_OK,
@ -250,14 +273,16 @@ function serverStreaming($stub) {
/**
* Run the ping_pong test.
*
* @param $stub Stub object that has service methods.
*/
function pingPong($stub) {
$request_lengths = array(27182, 8, 1828, 45904);
$response_lengths = array(31415, 9, 2653, 58979);
function pingPong($stub)
{
$request_lengths = [27182, 8, 1828, 45904];
$response_lengths = [31415, 9, 2653, 58979];
$call = $stub->FullDuplexCall();
for($i = 0; $i < 4; $i++) {
for ($i = 0; $i < 4; ++$i) {
$request = new grpc\testing\StreamingOutputCallRequest();
$request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
$response_parameters = new grpc\testing\ResponseParameters();
@ -273,9 +298,9 @@ function pingPong($stub) {
hardAssert($response !== null, 'Server returned too few responses');
$payload = $response->getPayload();
hardAssert($payload->getType() === grpc\testing\PayloadType::COMPRESSABLE,
'Payload ' . $i . ' had the wrong type');
'Payload '.$i.' had the wrong type');
hardAssert(strlen($payload->getBody()) === $response_lengths[$i],
'Payload ' . $i . ' had the wrong length');
'Payload '.$i.' had the wrong length');
}
$call->writesDone();
hardAssert($call->read() === null, 'Server returned too many responses');
@ -285,9 +310,11 @@ function pingPong($stub) {
/**
* Run the empty_stream test.
*
* @param $stub Stub object that has service methods.
*/
function emptyStream($stub) {
function emptyStream($stub)
{
$call = $stub->FullDuplexCall();
$call->writesDone();
hardAssert($call->read() === null, 'Server returned too many responses');
@ -297,9 +324,11 @@ function emptyStream($stub) {
/**
* Run the cancel_after_begin test.
*
* @param $stub Stub object that has service methods.
*/
function cancelAfterBegin($stub) {
function cancelAfterBegin($stub)
{
$call = $stub->StreamingInputCall();
$call->cancel();
list($result, $status) = $call->wait();
@ -309,9 +338,11 @@ function cancelAfterBegin($stub) {
/**
* Run the cancel_after_first_response test.
*
* @param $stub Stub object that has service methods.
*/
function cancelAfterFirstResponse($stub) {
function cancelAfterFirstResponse($stub)
{
$call = $stub->FullDuplexCall();
$request = new grpc\testing\StreamingOutputCallRequest();
$request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
@ -330,8 +361,9 @@ function cancelAfterFirstResponse($stub) {
'Call status was not CANCELLED');
}
function timeoutOnSleepingServer($stub) {
$call = $stub->FullDuplexCall(array('timeout' => 1000));
function timeoutOnSleepingServer($stub)
{
$call = $stub->FullDuplexCall(['timeout' => 1000]);
$request = new grpc\testing\StreamingOutputCallRequest();
$request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
$response_parameters = new grpc\testing\ResponseParameters();
@ -348,10 +380,10 @@ function timeoutOnSleepingServer($stub) {
'Call status was not DEADLINE_EXCEEDED');
}
$args = getopt('', array('server_host:', 'server_port:', 'test_case:',
$args = getopt('', ['server_host:', 'server_port:', 'test_case:',
'use_tls::', 'use_test_ca::',
'server_host_override:', 'oauth_scope:',
'default_service_account:'));
'default_service_account:', ]);
if (!array_key_exists('server_host', $args)) {
throw new Exception('Missing argument: --server_host is required');
}
@ -365,7 +397,7 @@ if (!array_key_exists('test_case', $args)) {
if ($args['server_port'] == 443) {
$server_address = $args['server_host'];
} else {
$server_address = $args['server_host'] . ':' . $args['server_port'];
$server_address = $args['server_host'].':'.$args['server_port'];
}
$test_case = $args['test_case'];
@ -392,7 +424,7 @@ $opts = [];
if ($use_tls) {
if ($use_test_ca) {
$ssl_credentials = Grpc\Credentials::createSsl(
file_get_contents(dirname(__FILE__) . '/../data/ca.pem'));
file_get_contents(dirname(__FILE__).'/../data/ca.pem'));
} else {
$ssl_credentials = Grpc\Credentials::createSsl();
}
@ -400,8 +432,8 @@ if ($use_tls) {
$opts['grpc.ssl_target_name_override'] = $host_override;
}
if (in_array($test_case, array('service_account_creds',
'compute_engine_creds', 'jwt_token_creds'))) {
if (in_array($test_case, ['service_account_creds',
'compute_engine_creds', 'jwt_token_creds', ])) {
if ($test_case == 'jwt_token_creds') {
$auth_credentials = ApplicationDefaultCredentials::getCredentials();
} else {
@ -418,14 +450,15 @@ if ($test_case == 'oauth2_auth_token') {
);
$token = $auth_credentials->fetchAuthToken();
$update_metadata =
function($metadata,
function ($metadata,
$authUri = null,
ClientInterface $client = null) use ($token) {
$metadata_copy = $metadata;
$metadata_copy[CredentialsLoader::AUTH_METADATA_KEY] =
array(sprintf("%s %s",
[sprintf('%s %s',
$token['token_type'],
$token['access_token']));
$token['access_token'])];
return $metadata_copy;
};
$opts['update_metadata'] = $update_metadata;

@ -31,56 +31,64 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
class CallTest extends PHPUnit_Framework_TestCase{
static $server;
static $port;
class CallTest extends PHPUnit_Framework_TestCase
{
public static $server;
public static $port;
public static function setUpBeforeClass() {
public static function setUpBeforeClass()
{
self::$server = new Grpc\Server([]);
self::$port = self::$server->addHttp2Port('0.0.0.0:0');
}
public function setUp() {
$this->channel = new Grpc\Channel('localhost:' . self::$port, []);
public function setUp()
{
$this->channel = new Grpc\Channel('localhost:'.self::$port, []);
$this->call = new Grpc\Call($this->channel,
'/foo',
Grpc\Timeval::infFuture());
}
public function testAddEmptyMetadata() {
public function testAddEmptyMetadata()
{
$batch = [
Grpc\OP_SEND_INITIAL_METADATA => []
Grpc\OP_SEND_INITIAL_METADATA => [],
];
$result = $this->call->startBatch($batch);
$this->assertTrue($result->send_metadata);
}
public function testAddSingleMetadata() {
public function testAddSingleMetadata()
{
$batch = [
Grpc\OP_SEND_INITIAL_METADATA => ['key' => ['value']]
Grpc\OP_SEND_INITIAL_METADATA => ['key' => ['value']],
];
$result = $this->call->startBatch($batch);
$this->assertTrue($result->send_metadata);
}
public function testAddMultiValueMetadata() {
public function testAddMultiValueMetadata()
{
$batch = [
Grpc\OP_SEND_INITIAL_METADATA => ['key' => ['value1', 'value2']]
Grpc\OP_SEND_INITIAL_METADATA => ['key' => ['value1', 'value2']],
];
$result = $this->call->startBatch($batch);
$this->assertTrue($result->send_metadata);
}
public function testAddSingleAndMultiValueMetadata() {
public function testAddSingleAndMultiValueMetadata()
{
$batch = [
Grpc\OP_SEND_INITIAL_METADATA => ['key1' => ['value1'],
'key2' => ['value2', 'value3']]
'key2' => ['value2', 'value3'], ],
];
$result = $this->call->startBatch($batch);
$this->assertTrue($result->send_metadata);
}
public function testGetPeer() {
public function testGetPeer()
{
$this->assertTrue(is_string($this->call->getPeer()));
}
}

@ -31,20 +31,24 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
class EndToEndTest extends PHPUnit_Framework_TestCase{
public function setUp() {
class EndToEndTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->server = new Grpc\Server([]);
$this->port = $this->server->addHttp2Port('0.0.0.0:0');
$this->channel = new Grpc\Channel('localhost:' . $this->port, []);
$this->channel = new Grpc\Channel('localhost:'.$this->port, []);
$this->server->start();
}
public function tearDown() {
public function tearDown()
{
unset($this->channel);
unset($this->server);
}
public function testSimpleRequestBody() {
public function testSimpleRequestBody()
{
$deadline = Grpc\Timeval::infFuture();
$status_text = 'xyz';
$call = new Grpc\Call($this->channel,
@ -53,7 +57,7 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
$event = $call->startBatch([
Grpc\OP_SEND_INITIAL_METADATA => [],
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true,
]);
$this->assertTrue($event->send_metadata);
@ -68,9 +72,9 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
Grpc\OP_SEND_STATUS_FROM_SERVER => [
'metadata' => [],
'code' => Grpc\STATUS_OK,
'details' => $status_text
'details' => $status_text,
],
Grpc\OP_RECV_CLOSE_ON_SERVER => true
Grpc\OP_RECV_CLOSE_ON_SERVER => true,
]);
$this->assertTrue($event->send_metadata);
@ -79,7 +83,7 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
$event = $call->startBatch([
Grpc\OP_RECV_INITIAL_METADATA => true,
Grpc\OP_RECV_STATUS_ON_CLIENT => true
Grpc\OP_RECV_STATUS_ON_CLIENT => true,
]);
$status = $event->status;
@ -91,7 +95,8 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
unset($server_call);
}
public function testMessageWriteFlags() {
public function testMessageWriteFlags()
{
$deadline = Grpc\Timeval::infFuture();
$req_text = 'message_write_flags_test';
$status_text = 'xyz';
@ -102,8 +107,8 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
$event = $call->startBatch([
Grpc\OP_SEND_INITIAL_METADATA => [],
Grpc\OP_SEND_MESSAGE => ['message' => $req_text,
'flags' => Grpc\WRITE_NO_COMPRESS],
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true
'flags' => Grpc\WRITE_NO_COMPRESS, ],
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true,
]);
$this->assertTrue($event->send_metadata);
@ -118,13 +123,13 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
Grpc\OP_SEND_STATUS_FROM_SERVER => [
'metadata' => [],
'code' => Grpc\STATUS_OK,
'details' => $status_text
'details' => $status_text,
],
]);
$event = $call->startBatch([
Grpc\OP_RECV_INITIAL_METADATA => true,
Grpc\OP_RECV_STATUS_ON_CLIENT => true
Grpc\OP_RECV_STATUS_ON_CLIENT => true,
]);
$status = $event->status;
@ -136,7 +141,8 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
unset($server_call);
}
public function testClientServerFullRequestResponse() {
public function testClientServerFullRequestResponse()
{
$deadline = Grpc\Timeval::infFuture();
$req_text = 'client_server_full_request_response';
$reply_text = 'reply:client_server_full_request_response';
@ -166,7 +172,7 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
Grpc\OP_SEND_STATUS_FROM_SERVER => [
'metadata' => [],
'code' => Grpc\STATUS_OK,
'details' => $status_text
'details' => $status_text,
],
Grpc\OP_RECV_MESSAGE => true,
Grpc\OP_RECV_CLOSE_ON_SERVER => true,
@ -195,15 +201,18 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
unset($server_call);
}
public function testGetTarget() {
public function testGetTarget()
{
$this->assertTrue(is_string($this->channel->getTarget()));
}
public function testGetConnectivityState() {
public function testGetConnectivityState()
{
$this->assertTrue($this->channel->getConnectivityState() == Grpc\CHANNEL_IDLE);
}
public function testWatchConnectivityStateFailed() {
public function testWatchConnectivityStateFailed()
{
$idle_state = $this->channel->getConnectivityState();
$this->assertTrue($idle_state == Grpc\CHANNEL_IDLE);
@ -215,7 +224,8 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
$idle_state, $deadline));
}
public function testWatchConnectivityStateSuccess() {
public function testWatchConnectivityStateSuccess()
{
$idle_state = $this->channel->getConnectivityState(true);
$this->assertTrue($idle_state == Grpc\CHANNEL_IDLE);
@ -230,7 +240,8 @@ class EndToEndTest extends PHPUnit_Framework_TestCase{
$this->assertTrue($idle_state != $new_state);
}
public function testWatchConnectivityStateDoNothing() {
public function testWatchConnectivityStateDoNothing()
{
$idle_state = $this->channel->getConnectivityState();
$this->assertTrue($idle_state == Grpc\CHANNEL_IDLE);

@ -31,34 +31,39 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
public function setUp() {
class SecureEndToEndTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$credentials = Grpc\Credentials::createSsl(
file_get_contents(dirname(__FILE__) . '/../data/ca.pem'));
file_get_contents(dirname(__FILE__).'/../data/ca.pem'));
$server_credentials = Grpc\ServerCredentials::createSsl(
null,
file_get_contents(dirname(__FILE__) . '/../data/server1.key'),
file_get_contents(dirname(__FILE__) . '/../data/server1.pem'));
file_get_contents(dirname(__FILE__).'/../data/server1.key'),
file_get_contents(dirname(__FILE__).'/../data/server1.pem'));
$this->server = new Grpc\Server();
$this->port = $this->server->addSecureHttp2Port('0.0.0.0:0',
$server_credentials);
$this->server->start();
$this->host_override = 'foo.test.google.fr';
$this->channel = new Grpc\Channel(
'localhost:' . $this->port,
'localhost:'.$this->port,
[
'grpc.ssl_target_name_override' => $this->host_override,
'grpc.default_authority' => $this->host_override,
'credentials' => $credentials
]);
'credentials' => $credentials,
]
);
}
public function tearDown() {
public function tearDown()
{
unset($this->channel);
unset($this->server);
}
public function testSimpleRequestBody() {
public function testSimpleRequestBody()
{
$deadline = Grpc\Timeval::infFuture();
$status_text = 'xyz';
$call = new Grpc\Call($this->channel,
@ -68,7 +73,7 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
$event = $call->startBatch([
Grpc\OP_SEND_INITIAL_METADATA => [],
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true,
]);
$this->assertTrue($event->send_metadata);
@ -83,9 +88,9 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
Grpc\OP_SEND_STATUS_FROM_SERVER => [
'metadata' => [],
'code' => Grpc\STATUS_OK,
'details' => $status_text
'details' => $status_text,
],
Grpc\OP_RECV_CLOSE_ON_SERVER => true
Grpc\OP_RECV_CLOSE_ON_SERVER => true,
]);
$this->assertTrue($event->send_metadata);
@ -94,7 +99,7 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
$event = $call->startBatch([
Grpc\OP_RECV_INITIAL_METADATA => true,
Grpc\OP_RECV_STATUS_ON_CLIENT => true
Grpc\OP_RECV_STATUS_ON_CLIENT => true,
]);
$this->assertSame([], $event->metadata);
@ -107,7 +112,8 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
unset($server_call);
}
public function testMessageWriteFlags() {
public function testMessageWriteFlags()
{
$deadline = Grpc\Timeval::infFuture();
$req_text = 'message_write_flags_test';
$status_text = 'xyz';
@ -119,8 +125,8 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
$event = $call->startBatch([
Grpc\OP_SEND_INITIAL_METADATA => [],
Grpc\OP_SEND_MESSAGE => ['message' => $req_text,
'flags' => Grpc\WRITE_NO_COMPRESS],
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true
'flags' => Grpc\WRITE_NO_COMPRESS, ],
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true,
]);
$this->assertTrue($event->send_metadata);
@ -135,13 +141,13 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
Grpc\OP_SEND_STATUS_FROM_SERVER => [
'metadata' => [],
'code' => Grpc\STATUS_OK,
'details' => $status_text
'details' => $status_text,
],
]);
$event = $call->startBatch([
Grpc\OP_RECV_INITIAL_METADATA => true,
Grpc\OP_RECV_STATUS_ON_CLIENT => true
Grpc\OP_RECV_STATUS_ON_CLIENT => true,
]);
$this->assertSame([], $event->metadata);
@ -154,7 +160,8 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
unset($server_call);
}
public function testClientServerFullRequestResponse() {
public function testClientServerFullRequestResponse()
{
$deadline = Grpc\Timeval::infFuture();
$req_text = 'client_server_full_request_response';
$reply_text = 'reply:client_server_full_request_response';
@ -168,7 +175,7 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
$event = $call->startBatch([
Grpc\OP_SEND_INITIAL_METADATA => [],
Grpc\OP_SEND_CLOSE_FROM_CLIENT => true,
Grpc\OP_SEND_MESSAGE => ['message' => $req_text]
Grpc\OP_SEND_MESSAGE => ['message' => $req_text],
]);
$this->assertTrue($event->send_metadata);
@ -185,7 +192,7 @@ class SecureEndToEndTest extends PHPUnit_Framework_TestCase{
Grpc\OP_SEND_STATUS_FROM_SERVER => [
'metadata' => [],
'code' => Grpc\STATUS_OK,
'details' => $status_text
'details' => $status_text,
],
Grpc\OP_RECV_MESSAGE => true,
Grpc\OP_RECV_CLOSE_ON_SERVER => true,

@ -31,20 +31,24 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
class TimevalTest extends PHPUnit_Framework_TestCase{
public function testCompareSame() {
class TimevalTest extends PHPUnit_Framework_TestCase
{
public function testCompareSame()
{
$zero = Grpc\Timeval::zero();
$this->assertSame(0, Grpc\Timeval::compare($zero, $zero));
}
public function testPastIsLessThanZero() {
public function testPastIsLessThanZero()
{
$zero = Grpc\Timeval::zero();
$past = Grpc\Timeval::infPast();
$this->assertLessThan(0, Grpc\Timeval::compare($past, $zero));
$this->assertGreaterThan(0, Grpc\Timeval::compare($zero, $past));
}
public function testFutureIsGreaterThanZero() {
public function testFutureIsGreaterThanZero()
{
$zero = Grpc\Timeval::zero();
$future = Grpc\Timeval::infFuture();
$this->assertLessThan(0, Grpc\Timeval::compare($zero, $future));
@ -54,7 +58,8 @@ class TimevalTest extends PHPUnit_Framework_TestCase{
/**
* @depends testFutureIsGreaterThanZero
*/
public function testNowIsBetweenZeroAndFuture() {
public function testNowIsBetweenZeroAndFuture()
{
$zero = Grpc\Timeval::zero();
$future = Grpc\Timeval::infFuture();
$now = Grpc\Timeval::now();
@ -62,21 +67,24 @@ class TimevalTest extends PHPUnit_Framework_TestCase{
$this->assertLessThan(0, Grpc\Timeval::compare($now, $future));
}
public function testNowAndAdd() {
public function testNowAndAdd()
{
$now = Grpc\Timeval::now();
$delta = new Grpc\Timeval(1000);
$deadline = $now->add($delta);
$this->assertGreaterThan(0, Grpc\Timeval::compare($deadline, $now));
}
public function testNowAndSubtract() {
public function testNowAndSubtract()
{
$now = Grpc\Timeval::now();
$delta = new Grpc\Timeval(1000);
$deadline = $now->subtract($delta);
$this->assertLessThan(0, Grpc\Timeval::compare($deadline, $now));
}
public function testAddAndSubtract() {
public function testAddAndSubtract()
{
$now = Grpc\Timeval::now();
$delta = new Grpc\Timeval(1000);
$deadline = $now->add($delta);

Loading…
Cancel
Save