Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(210)

Side by Side Diff: third_party/grpc/src/php/tests/interop/interop_client.php

Issue 1932353002: Initial checkin of gRPC to third_party/ Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 4 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 <?php
2 /*
3 *
4 * Copyright 2015, Google Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
9 * met:
10 *
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following disclaimer
15 * in the documentation and/or other materials provided with the
16 * distribution.
17 * * Neither the name of Google Inc. nor the names of its
18 * contributors may be used to endorse or promote products derived from
19 * this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 *
33 */
34 require_once realpath(dirname(__FILE__).'/../../vendor/autoload.php');
35 require 'empty.php';
36 require 'messages.php';
37 require 'test.php';
38 use Google\Auth\CredentialsLoader;
39 use Google\Auth\ApplicationDefaultCredentials;
40 use GuzzleHttp\ClientInterface;
41
42 /**
43 * Assertion function that always exits with an error code if the assertion is
44 * falsy.
45 *
46 * @param $value Assertion value. Should be true.
47 * @param $error_message Message to display if the assertion is false
48 */
49 function hardAssert($value, $error_message)
50 {
51 if (!$value) {
52 echo $error_message."\n";
53 exit(1);
54 }
55 }
56
57 /**
58 * Run the empty_unary test.
59 *
60 * @param $stub Stub object that has service methods
61 */
62 function emptyUnary($stub)
63 {
64 list($result, $status) = $stub->EmptyCall(new grpc\testing\EmptyMessage())-> wait();
65 hardAssert($status->code === Grpc\STATUS_OK, 'Call did not complete successf ully');
66 hardAssert($result !== null, 'Call completed with a null response');
67 }
68
69 /**
70 * Run the large_unary test.
71 *
72 * @param $stub Stub object that has service methods
73 */
74 function largeUnary($stub)
75 {
76 performLargeUnary($stub);
77 }
78
79 /**
80 * Shared code between large unary test and auth test.
81 *
82 * @param $stub Stub object that has service methods
83 * @param $fillUsername boolean whether to fill result with username
84 * @param $fillOauthScope boolean whether to fill result with oauth scope
85 */
86 function performLargeUnary($stub, $fillUsername = false, $fillOauthScope = false ,
87 $callback = false)
88 {
89 $request_len = 271828;
90 $response_len = 314159;
91
92 $request = new grpc\testing\SimpleRequest();
93 $request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
94 $request->setResponseSize($response_len);
95 $payload = new grpc\testing\Payload();
96 $payload->setType(grpc\testing\PayloadType::COMPRESSABLE);
97 $payload->setBody(str_repeat("\0", $request_len));
98 $request->setPayload($payload);
99 $request->setFillUsername($fillUsername);
100 $request->setFillOauthScope($fillOauthScope);
101
102 $options = false;
103 if ($callback) {
104 $options['call_credentials_callback'] = $callback;
105 }
106
107 list($result, $status) = $stub->UnaryCall($request, [], $options)->wait();
108 hardAssert($status->code === Grpc\STATUS_OK, 'Call did not complete successf ully');
109 hardAssert($result !== null, 'Call returned a null response');
110 $payload = $result->getPayload();
111 hardAssert($payload->getType() === grpc\testing\PayloadType::COMPRESSABLE,
112 'Payload had the wrong type');
113 hardAssert(strlen($payload->getBody()) === $response_len,
114 'Payload had the wrong length');
115 hardAssert($payload->getBody() === str_repeat("\0", $response_len),
116 'Payload had the wrong content');
117
118 return $result;
119 }
120
121 /**
122 * Run the service account credentials auth test.
123 *
124 * @param $stub Stub object that has service methods
125 * @param $args array command line args
126 */
127 function serviceAccountCreds($stub, $args)
128 {
129 if (!array_key_exists('oauth_scope', $args)) {
130 throw new Exception('Missing oauth scope');
131 }
132 $jsonKey = json_decode(
133 file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
134 true);
135 $result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = t rue);
136 hardAssert($result->getUsername() == $jsonKey['client_email'],
137 'invalid email returned');
138 hardAssert(strpos($args['oauth_scope'], $result->getOauthScope()) !== false,
139 'invalid oauth scope returned');
140 }
141
142 /**
143 * Run the compute engine credentials auth test.
144 * Has not been run from gcloud as of 2015-05-05.
145 *
146 * @param $stub Stub object that has service methods
147 * @param $args array command line args
148 */
149 function computeEngineCreds($stub, $args)
150 {
151 if (!array_key_exists('oauth_scope', $args)) {
152 throw new Exception('Missing oauth scope');
153 }
154 if (!array_key_exists('default_service_account', $args)) {
155 throw new Exception('Missing default_service_account');
156 }
157 $result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = t rue);
158 hardAssert($args['default_service_account'] == $result->getUsername(),
159 'invalid email returned');
160 }
161
162 /**
163 * Run the jwt token credentials auth test.
164 *
165 * @param $stub Stub object that has service methods
166 * @param $args array command line args
167 */
168 function jwtTokenCreds($stub, $args)
169 {
170 $jsonKey = json_decode(
171 file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
172 true);
173 $result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = t rue);
174 hardAssert($result->getUsername() == $jsonKey['client_email'],
175 'invalid email returned');
176 }
177
178 /**
179 * Run the oauth2_auth_token auth test.
180 *
181 * @param $stub Stub object that has service methods
182 * @param $args array command line args
183 */
184 function oauth2AuthToken($stub, $args)
185 {
186 $jsonKey = json_decode(
187 file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
188 true);
189 $result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = t rue);
190 hardAssert($result->getUsername() == $jsonKey['client_email'],
191 'invalid email returned');
192 }
193
194 function updateAuthMetadataCallback($context)
195 {
196 $authUri = $context->service_url;
197 $methodName = $context->method_name;
198 $auth_credentials = ApplicationDefaultCredentials::getCredentials();
199
200 return $auth_credentials->updateMetadata($metadata = [], $authUri);
201 }
202
203 /**
204 * Run the per_rpc_creds auth test.
205 *
206 * @param $stub Stub object that has service methods
207 * @param $args array command line args
208 */
209 function perRpcCreds($stub, $args)
210 {
211 $jsonKey = json_decode(
212 file_get_contents(getenv(CredentialsLoader::ENV_VAR)),
213 true);
214
215 $result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = t rue,
216 'updateAuthMetadataCallback');
217 hardAssert($result->getUsername() == $jsonKey['client_email'],
218 'invalid email returned');
219 }
220
221 /**
222 * Run the client_streaming test.
223 *
224 * @param $stub Stub object that has service methods
225 */
226 function clientStreaming($stub)
227 {
228 $request_lengths = [27182, 8, 1828, 45904];
229
230 $requests = array_map(
231 function ($length) {
232 $request = new grpc\testing\StreamingInputCallRequest();
233 $payload = new grpc\testing\Payload();
234 $payload->setBody(str_repeat("\0", $length));
235 $request->setPayload($payload);
236
237 return $request;
238 }, $request_lengths);
239
240 $call = $stub->StreamingInputCall();
241 foreach ($requests as $request) {
242 $call->write($request);
243 }
244 list($result, $status) = $call->wait();
245 hardAssert($status->code === Grpc\STATUS_OK, 'Call did not complete successf ully');
246 hardAssert($result->getAggregatedPayloadSize() === 74922,
247 'aggregated_payload_size was incorrect');
248 }
249
250 /**
251 * Run the server_streaming test.
252 *
253 * @param $stub Stub object that has service methods.
254 */
255 function serverStreaming($stub)
256 {
257 $sizes = [31415, 9, 2653, 58979];
258
259 $request = new grpc\testing\StreamingOutputCallRequest();
260 $request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
261 foreach ($sizes as $size) {
262 $response_parameters = new grpc\testing\ResponseParameters();
263 $response_parameters->setSize($size);
264 $request->addResponseParameters($response_parameters);
265 }
266
267 $call = $stub->StreamingOutputCall($request);
268 $i = 0;
269 foreach ($call->responses() as $value) {
270 hardAssert($i < 4, 'Too many responses');
271 $payload = $value->getPayload();
272 hardAssert($payload->getType() === grpc\testing\PayloadType::COMPRESSABL E,
273 'Payload '.$i.' had the wrong type');
274 hardAssert(strlen($payload->getBody()) === $sizes[$i],
275 'Response '.$i.' had the wrong length');
276 $i += 1;
277 }
278 hardAssert($call->getStatus()->code === Grpc\STATUS_OK,
279 'Call did not complete successfully');
280 }
281
282 /**
283 * Run the ping_pong test.
284 *
285 * @param $stub Stub object that has service methods.
286 */
287 function pingPong($stub)
288 {
289 $request_lengths = [27182, 8, 1828, 45904];
290 $response_lengths = [31415, 9, 2653, 58979];
291
292 $call = $stub->FullDuplexCall();
293 for ($i = 0; $i < 4; ++$i) {
294 $request = new grpc\testing\StreamingOutputCallRequest();
295 $request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
296 $response_parameters = new grpc\testing\ResponseParameters();
297 $response_parameters->setSize($response_lengths[$i]);
298 $request->addResponseParameters($response_parameters);
299 $payload = new grpc\testing\Payload();
300 $payload->setBody(str_repeat("\0", $request_lengths[$i]));
301 $request->setPayload($payload);
302
303 $call->write($request);
304 $response = $call->read();
305
306 hardAssert($response !== null, 'Server returned too few responses');
307 $payload = $response->getPayload();
308 hardAssert($payload->getType() === grpc\testing\PayloadType::COMPRESSABL E,
309 'Payload '.$i.' had the wrong type');
310 hardAssert(strlen($payload->getBody()) === $response_lengths[$i],
311 'Payload '.$i.' had the wrong length');
312 }
313 $call->writesDone();
314 hardAssert($call->read() === null, 'Server returned too many responses');
315 hardAssert($call->getStatus()->code === Grpc\STATUS_OK,
316 'Call did not complete successfully');
317 }
318
319 /**
320 * Run the empty_stream test.
321 *
322 * @param $stub Stub object that has service methods.
323 */
324 function emptyStream($stub)
325 {
326 $call = $stub->FullDuplexCall();
327 $call->writesDone();
328 hardAssert($call->read() === null, 'Server returned too many responses');
329 hardAssert($call->getStatus()->code === Grpc\STATUS_OK,
330 'Call did not complete successfully');
331 }
332
333 /**
334 * Run the cancel_after_begin test.
335 *
336 * @param $stub Stub object that has service methods.
337 */
338 function cancelAfterBegin($stub)
339 {
340 $call = $stub->StreamingInputCall();
341 $call->cancel();
342 list($result, $status) = $call->wait();
343 hardAssert($status->code === Grpc\STATUS_CANCELLED,
344 'Call status was not CANCELLED');
345 }
346
347 /**
348 * Run the cancel_after_first_response test.
349 *
350 * @param $stub Stub object that has service methods.
351 */
352 function cancelAfterFirstResponse($stub)
353 {
354 $call = $stub->FullDuplexCall();
355 $request = new grpc\testing\StreamingOutputCallRequest();
356 $request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
357 $response_parameters = new grpc\testing\ResponseParameters();
358 $response_parameters->setSize(31415);
359 $request->addResponseParameters($response_parameters);
360 $payload = new grpc\testing\Payload();
361 $payload->setBody(str_repeat("\0", 27182));
362 $request->setPayload($payload);
363
364 $call->write($request);
365 $response = $call->read();
366
367 $call->cancel();
368 hardAssert($call->getStatus()->code === Grpc\STATUS_CANCELLED,
369 'Call status was not CANCELLED');
370 }
371
372 function timeoutOnSleepingServer($stub)
373 {
374 $call = $stub->FullDuplexCall([], ['timeout' => 1000]);
375 $request = new grpc\testing\StreamingOutputCallRequest();
376 $request->setResponseType(grpc\testing\PayloadType::COMPRESSABLE);
377 $response_parameters = new grpc\testing\ResponseParameters();
378 $response_parameters->setSize(8);
379 $request->addResponseParameters($response_parameters);
380 $payload = new grpc\testing\Payload();
381 $payload->setBody(str_repeat("\0", 9));
382 $request->setPayload($payload);
383
384 $call->write($request);
385 $response = $call->read();
386
387 hardAssert($call->getStatus()->code === Grpc\STATUS_DEADLINE_EXCEEDED,
388 'Call status was not DEADLINE_EXCEEDED');
389 }
390
391 $args = getopt('', ['server_host:', 'server_port:', 'test_case:',
392 'use_tls::', 'use_test_ca::',
393 'server_host_override:', 'oauth_scope:',
394 'default_service_account:', ]);
395 if (!array_key_exists('server_host', $args)) {
396 throw new Exception('Missing argument: --server_host is required');
397 }
398 if (!array_key_exists('server_port', $args)) {
399 throw new Exception('Missing argument: --server_port is required');
400 }
401 if (!array_key_exists('test_case', $args)) {
402 throw new Exception('Missing argument: --test_case is required');
403 }
404
405 if ($args['server_port'] == 443) {
406 $server_address = $args['server_host'];
407 } else {
408 $server_address = $args['server_host'].':'.$args['server_port'];
409 }
410
411 $test_case = $args['test_case'];
412
413 $host_override = 'foo.test.google.fr';
414 if (array_key_exists('server_host_override', $args)) {
415 $host_override = $args['server_host_override'];
416 }
417
418 $use_tls = false;
419 if (array_key_exists('use_tls', $args) &&
420 $args['use_tls'] != 'false') {
421 $use_tls = true;
422 }
423
424 $use_test_ca = false;
425 if (array_key_exists('use_test_ca', $args) &&
426 $args['use_test_ca'] != 'false') {
427 $use_test_ca = true;
428 }
429
430 $opts = [];
431
432 if ($use_tls) {
433 if ($use_test_ca) {
434 $ssl_credentials = Grpc\ChannelCredentials::createSsl(
435 file_get_contents(dirname(__FILE__).'/../data/ca.pem'));
436 } else {
437 $ssl_credentials = Grpc\ChannelCredentials::createSsl();
438 }
439 $opts['credentials'] = $ssl_credentials;
440 $opts['grpc.ssl_target_name_override'] = $host_override;
441 } else {
442 $opts['credentials'] = Grpc\ChannelCredentials::createInsecure();
443 }
444
445 if (in_array($test_case, ['service_account_creds',
446 'compute_engine_creds', 'jwt_token_creds', ])) {
447 if ($test_case == 'jwt_token_creds') {
448 $auth_credentials = ApplicationDefaultCredentials::getCredentials();
449 } else {
450 $auth_credentials = ApplicationDefaultCredentials::getCredentials(
451 $args['oauth_scope']
452 );
453 }
454 $opts['update_metadata'] = $auth_credentials->getUpdateMetadataFunc();
455 }
456
457 if ($test_case == 'oauth2_auth_token') {
458 $auth_credentials = ApplicationDefaultCredentials::getCredentials(
459 $args['oauth_scope']
460 );
461 $token = $auth_credentials->fetchAuthToken();
462 $update_metadata =
463 function ($metadata,
464 $authUri = null,
465 ClientInterface $client = null) use ($token) {
466 $metadata_copy = $metadata;
467 $metadata_copy[CredentialsLoader::AUTH_METADATA_KEY] =
468 [sprintf('%s %s',
469 $token['token_type'],
470 $token['access_token'])];
471
472 return $metadata_copy;
473 };
474 $opts['update_metadata'] = $update_metadata;
475 }
476
477 $stub = new grpc\testing\TestServiceClient($server_address, $opts);
478
479 echo "Connecting to $server_address\n";
480 echo "Running test case $test_case\n";
481
482 switch ($test_case) {
483 case 'empty_unary':
484 emptyUnary($stub);
485 break;
486 case 'large_unary':
487 largeUnary($stub);
488 break;
489 case 'client_streaming':
490 clientStreaming($stub);
491 break;
492 case 'server_streaming':
493 serverStreaming($stub);
494 break;
495 case 'ping_pong':
496 pingPong($stub);
497 break;
498 case 'empty_stream':
499 emptyStream($stub);
500 break;
501 case 'cancel_after_begin':
502 cancelAfterBegin($stub);
503 break;
504 case 'cancel_after_first_response':
505 cancelAfterFirstResponse($stub);
506 break;
507 case 'timeout_on_sleeping_server':
508 timeoutOnSleepingServer($stub);
509 break;
510 case 'service_account_creds':
511 serviceAccountCreds($stub, $args);
512 break;
513 case 'compute_engine_creds':
514 computeEngineCreds($stub, $args);
515 break;
516 case 'jwt_token_creds':
517 jwtTokenCreds($stub, $args);
518 break;
519 case 'oauth2_auth_token':
520 oauth2AuthToken($stub, $args);
521 break;
522 case 'per_rpc_creds':
523 perRpcCreds($stub, $args);
524 break;
525 default:
526 echo "Unsupported test case $test_case\n";
527 exit(1);
528 }
OLDNEW
« no previous file with comments | « third_party/grpc/src/php/tests/interop/empty.proto ('k') | third_party/grpc/src/php/tests/interop/messages.proto » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698