-
Notifications
You must be signed in to change notification settings - Fork 462
Expand file tree
/
Copy pathNodeTest.php
More file actions
557 lines (487 loc) · 21.6 KB
/
NodeTest.php
File metadata and controls
557 lines (487 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<?php
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Dev\Tests\Unit\DocFx;
use Google\Cloud\Dev\DocFx\Node\ClassNode;
use Google\Cloud\Dev\DocFx\Node\MethodNode;
use Google\Cloud\Dev\DocFx\Node\XrefTrait;
use Google\Cloud\Dev\DocFx\Node\FencedCodeBlockTrait;
use Google\Cloud\Dev\DocFx\XrefValidationTrait;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Component\Console\Output\OutputInterface;
use SimpleXMLElement;
/**
* @group dev
*/
class NodeTest extends TestCase
{
use ProphecyTrait;
public function testNestedParameters()
{
$nestedParamsXml = file_get_contents(__DIR__ . '/../../fixtures/phpdoc/nestedparams.xml');
$method = new MethodNode(new SimpleXMLElement($nestedParamsXml), '', []);
$params = $method->getParameters();
// Assert the parameters have been parsed
$this->assertCount(8, $params);
// Assert parent option parameter
$this->assertEquals('data', $params[1]->getName());
$this->assertEquals('array', $params[1]->getType());
$this->assertEquals(
'Optional. Data for populating the Message object.',
$params[1]->getDescription()
);
// Assert nested parameter
$this->assertEquals('↳ total_pages', $params[4]->getName());
$this->assertEquals('int', $params[4]->getType());
$this->assertEquals(
'This field gives the total number of pages in the file.',
$params[4]->getDescription()
);
// Assert nested parameter with whitespace
$this->assertEquals('↳ imageContext', $params[6]->getName());
$this->assertEquals('ImageContext', $params[6]->getType());
$this->assertEquals(
'Additional context that may accompany the image.',
$params[6]->getDescription()
);
// Assert nested parameter with special characters
$this->assertEquals('↳ exampleString', $params[7]->getName());
$this->assertEquals('string', $params[7]->getType());
$this->assertEquals(
'Ensure special chars are decoded, such as alice@example.com.',
$params[7]->getDescription()
);
}
public function testProtoRefInParameters()
{
$nestedParamsXml = file_get_contents(__DIR__ . '/../../fixtures/phpdoc/nestedparams.xml');
$method = new MethodNode(new SimpleXMLElement($nestedParamsXml), '', []);
$params = $method->getParameters();
// Assert proto ref
$this->assertStringContainsString(
'<xref uid="\Google\Cloud\Vision\V1\AnnotateImageResponse::getImage()">images</xref>',
$params[0]->getDescription()
);
// Assert proto ref in nested param
$this->assertStringContainsString(
'<xref uid="\Google\Cloud\Vision\V1\Image">Image</xref>',
$params[3]->getDescription()
);
}
public function testProtoPackage()
{
$serviceXml = file_get_contents(__DIR__ . '/../../fixtures/phpdoc/service.xml');
$class = new ClassNode(new SimpleXMLElement($serviceXml));
$this->assertTrue($class->isServiceClass());
$this->assertEquals('google.cloud.vision.v1', $class->getProtoPackage());
}
public function testSeeTagsInMethodDescription()
{
$serviceXml = <<<EOF
<method>
<docblock>
<description></description>
<long-description></long-description>
<tag name="see"
description="Cool External Resource"
link="https://wwww.testlink.com"/>
<tag name="see"
description=""
link="\Google\Cloud\Vision\V1\ImageAnnotatorClient"/>
<tag name="see"
description="Resume Operation method"
link="\Google\Cloud\Vision\V1\ImageAnnotatorClient::resumeOperation()"/>
</docblock>
</method>
EOF;
$method = new MethodNode(new SimpleXMLElement($serviceXml), '', []);
$content = $method->getContent();
$this->assertStringContainsString(
'See also:' . "\n" .
' - <a href="https://wwww.testlink.com">Cool External Resource</a>' . "\n" .
' - <xref uid="\Google\Cloud\Vision\V1\ImageAnnotatorClient">\Google\Cloud\Vision\V1\ImageAnnotatorClient</xref>' . "\n" .
' - <xref uid="\Google\Cloud\Vision\V1\ImageAnnotatorClient::resumeOperation()">Resume Operation method</xref>',
$content
);
}
public function testReplaceGuzzleExternalLink()
{
$guzzlePromiseClassName = '\GuzzleHttp\Promise\PromiseInterface';
$expected = '<a href="https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-GuzzleHttp.Promise.Promise.html">GuzzleHttp\Promise\PromiseInterface</a>';
$xref = new class {
use XrefTrait;
public function replace(string $uid) {
return $this->replaceUidWithLink($uid);
}
};
$result = $xref->replace($guzzlePromiseClassName);
$this->assertEquals($expected, $result);
}
public function testReplaceGenericPromiseClass()
{
$guzzlePromiseClassName = '\GuzzleHttp\Promise\PromiseInterface';
$googleReference = '\Google\Cloud\AdvisoryNotifications\V1\Notification';
$uid = $guzzlePromiseClassName . '<' . $googleReference . '>';
$expected = '<a href="https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-GuzzleHttp.Promise.Promise.html">GuzzleHttp\Promise\PromiseInterface</a>';
$expected .= '<<xref uid="' . $googleReference . '">Google\Cloud\AdvisoryNotifications\V1\Notification</xref>>';
$xref = new class {
use XrefTrait;
public function replace(string $uid) {
return $this->replaceUidWithLink($uid);
}
};
$result = $xref->replace($uid);
$this->assertEquals($expected, $result);
}
/**
* @dataProvider provideReplaceProtoRefWithXref
*/
public function testReplaceProtoRefWithXref(string $description, string $expected)
{
$xref = new class {
use XrefTrait;
private $protoPackages = [
'google.cloud.aiplatform.v1' => 'Google\\Cloud\\AIPlatform\\V1',
'google.bigtable.admin.v2' => 'Google\\Cloud\\Bigtable\\Admin\\V2',
'google.bigtable.v2' => 'Google\\Cloud\\Bigtable\\V2',
'google.logging.v2' => 'Google\\Cloud\\Logging\\V2',
'google.cloud.servicedirectory.v1' => 'Google\\Cloud\\ServiceDirectory\\V1',
];
public function replace(string $description) {
return $this->replaceProtoRef($description);
}
};
$this->assertEquals($expected, $xref->replace($description));
}
public function provideReplaceProtoRefWithXref()
{
return [
[
'Testing that a [ProtoRef][google.cloud.ProtoRef] gets replaced as expected'
. PHP_EOL
. ' and so does a [SecondProtoRef][google.cloud.SecondProtoRef].',
'Testing that a <xref uid="\Google\Cloud\ProtoRef">ProtoRef</xref> gets replaced as expected'
. PHP_EOL
. ' and so does a <xref uid="\Google\Cloud\SecondProtoRef">SecondProtoRef</xref>.',
],
[
// property reference
'[google.cloud.Operation.name][google.cloud.Operation.name]',
'<xref uid="\Google\Cloud\Operation::getName()">google.cloud.Operation.name</xref>',
],
[
// property with an underscore reference
'[display_name][google.cloud.vision.v1.Product.display_name]',
'<xref uid="\Google\Cloud\Vision\V1\Product::getDisplayName()">display_name</xref>',
],
[
// service method reference
'[projects.locations.endpoints.predict][google.cloud.aiplatform.v1.PredictionService.Predict]',
'<xref uid="\Google\Cloud\AIPlatform\V1\Client\PredictionServiceClient::predict()">projects.locations.endpoints.predict</xref>',
],
[
// nested class reference
'[TextAnnotation.TextProperty][google.cloud.vision.v1.TextAnnotation.TextProperty]',
'<xref uid="\Google\Cloud\Vision\V1\TextAnnotation\TextProperty">TextAnnotation.TextProperty</xref>',
],
[
// nested class reference with property
'[PolicyInfo.attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource]',
'<xref uid="\Google\Cloud\Asset\V1\BatchGetEffectiveIamPoliciesResponse\EffectiveIamPolicy\PolicyInfo::getAttachedResource()">PolicyInfo.attached_resource</xref>',
],
[
// service methods without a "service" suffix
'[ListBackups][google.bigtable.admin.v2.BigtableTableAdmin.ListBackups]',
'<xref uid="\Google\Cloud\Bigtable\Admin\V2\Client\BigtableTableAdminClient::listBackups()">ListBackups</xref>'
],
[
// Enum constants
'[google.some.Code.INVALID_ARGUMENT][google.some.Code.INVALID_ARGUMENT]',
'<xref uid="\Google\Some\Code::INVALID_ARGUMENT">google.some.Code.INVALID_ARGUMENT</xref>'
],
[
// Numbers in the class name
'Output only. The service account that will be used by the Log Router to access your Cloud KMS key. Before enabling CMEK for Log Router, you must first assign the cloudkms.cryptoKeyEncrypterDecrypter role to the service account that the Log Router will use to access your Cloud KMS key. Use [GetCmekSettings][google.logging.v2.ConfigServiceV2.GetCmekSettings] to obtain the service account ID. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.',
'Output only. The service account that will be used by the Log Router to access your Cloud KMS key. Before enabling CMEK for Log Router, you must first assign the cloudkms.cryptoKeyEncrypterDecrypter role to the service account that the Log Router will use to access your Cloud KMS key. Use <xref uid="\Google\Cloud\Logging\V2\ConfigServiceV2Client::getCmekSettings()">GetCmekSettings</xref> to obtain the service account ID. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.'
],
[
// Separation between links using newlines
'Required. The [Model\'s][google.cloud.aiplatform.v1.BatchPredictionJob.model]' . PHP_EOL
. '[PredictSchemata\'s][google.cloud.aiplatform.v1.Model.predict_schemata]' . PHP_EOL
. '[instance_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri].',
'Required. The <xref uid="\Google\Cloud\AIPlatform\V1\BatchPredictionJob::getModel()">Model\'s</xref>' . PHP_EOL
. '<xref uid="\Google\Cloud\AIPlatform\V1\Model::getPredictSchemata()">PredictSchemata\'s</xref>' . PHP_EOL
. '<xref uid="\Google\Cloud\AIPlatform\V1\PredictSchemata::getInstanceSchemaUri()">instance_schema_uri</xref>.'
],
[
// Separation within links using newlines
'Required. The [Model\'s]' . PHP_EOL . '[google.cloud.aiplatform.v1.BatchPredictionJob.model]'
. ' [PredictSchemata\'s]' . PHP_EOL . '[google.cloud.aiplatform.v1.Model.predict_schemata]'
. ' [instance_schema_uri]' . PHP_EOL . '[google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri].',
'Required. The <xref uid="\Google\Cloud\AIPlatform\V1\BatchPredictionJob::getModel()">Model\'s</xref>'
. ' <xref uid="\Google\Cloud\AIPlatform\V1\Model::getPredictSchemata()">PredictSchemata\'s</xref>'
. ' <xref uid="\Google\Cloud\AIPlatform\V1\PredictSchemata::getInstanceSchemaUri()">instance_schema_uri</xref>.'
],
[
// Separation within links using a space - some APIs do this :/
'Required. The [Model\'s] [google.cloud.aiplatform.v1.BatchPredictionJob.model]'
. ' [PredictSchemata\'s] [google.cloud.aiplatform.v1.Model.predict_schemata]'
. ' [instance_schema_uri] [google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri].',
'Required. The <xref uid="\Google\Cloud\AIPlatform\V1\BatchPredictionJob::getModel()">Model\'s</xref>'
. ' <xref uid="\Google\Cloud\AIPlatform\V1\Model::getPredictSchemata()">PredictSchemata\'s</xref>'
. ' <xref uid="\Google\Cloud\AIPlatform\V1\PredictSchemata::getInstanceSchemaUri()">instance_schema_uri</xref>.'
],
[
// Reserved word used in class name
'[Namespace][google.cloud.servicedirectory.v1.Namespace]',
'<xref uid="\Google\Cloud\ServiceDirectory\V1\PBNamespace">Namespace</xref>',
],
[
// Reserved word used in path name
'[Encoding][google.bigtable.v2.Type.String.Encoding]',
'<xref uid="\Google\Cloud\Bigtable\V2\Type\PBString\Encoding">Encoding</xref>',
],
[
// Parenthesis in code samples should not be modified
'Testing that a code sample like $foo["bar"]["baz"] does not get replaced',
'Testing that a code sample like $foo["bar"]["baz"] does not get replaced'
],
];
}
public function testProtoRefWithXrefUsingPackageName()
{
$description = '[ListBackups][google.bigtable.admin.v2.BigtableTableAdmin.ListBackups]';
$protoPackages = ['google.bigtable.admin.v2' => 'Google\\Cloud\\Bigtable\\Admin\\V2'];
$xref = new class($protoPackages) {
use XrefTrait;
public function __construct(private array $protoPackages) {
}
public function replace(string $description) {
return $this->replaceProtoRef($description);
}
};
$this->assertEquals(
'<xref uid="\Google\Cloud\Bigtable\Admin\V2\Client\BigtableTableAdminClient::listBackups()">ListBackups</xref>',
$xref->replace($description)
);
$classNode = new ClassNode(new SimpleXMLElement(sprintf(
'<class><docblock><description>%s</description></docblock></class>',
$description
)), $protoPackages);
$this->assertEquals(
'<xref uid="\Google\Cloud\Bigtable\Admin\V2\Client\BigtableTableAdminClient::listBackups()">ListBackups</xref>',
$classNode->getContent()
);
}
public function testAddingPhpLanguageHintToFencedCodeBlock()
{
$fencedCodeBlock = new class {
use FencedCodeBlockTrait;
public function replace(string $description) {
return $this->addPhpLanguageHintToFencedCodeblock($description);
}
};
$description = <<<EOF
This is a test fenced codeblock
```
use Some\TestFoo;
\$n = new TestFoo();
```
And now you know how to use it!
EOF;
$expected = <<<EOF
This is a test fenced codeblock
```php
use Some\TestFoo;
\$n = new TestFoo();
```
And now you know how to use it!
EOF;
$this->assertEquals(
$expected,
$fencedCodeBlock->replace($description)
);
$descriptionWithIndent = <<<EOF
This is an indented test fenced codeblock
```
use Some\TestFoo;
\$n = new TestFoo();
```
And now you know how to use it!
EOF;
// Ensure the whitespace indentation works as expected
$this->assertStringContainsString(
"\n ```php\n",
$fencedCodeBlock->replace($descriptionWithIndent)
);
$this->assertStringContainsString(
"\n ```\n",
$fencedCodeBlock->replace($descriptionWithIndent)
);
$descriptionWithMultipleCodeblocks = <<<EOF
This is a test fenced codeblock
```
// first codeblock
use Some\TestFoo;
\$n = new TestFoo();
```
```
// second codeblock
use Some\TestFoo;
\$n = new TestFoo();
```
EOF;
$expected = <<<EOF
This is a test fenced codeblock
```php
// first codeblock
use Some\TestFoo;
\$n = new TestFoo();
```
```php
// second codeblock
use Some\TestFoo;
\$n = new TestFoo();
```
EOF;
// Ensure the "php" language hint is added to both fenced code blocks.
$this->assertEquals(
$expected,
$fencedCodeBlock->replace($descriptionWithMultipleCodeblocks)
);
$descriptionWithDifferentLanguageHint = <<<EOF
This is a test fenced codeblock
```sh
pecl install grpc
```
```
use Some\TestFoo;
\$n = new TestFoo();
```
EOF;
$expected = <<<EOF
This is a test fenced codeblock
```sh
pecl install grpc
```
```php
use Some\TestFoo;
\$n = new TestFoo();
```
EOF;
// Ensure the "php" language hint is added only to the second fenced code block.
$this->assertEquals(
$expected,
$fencedCodeBlock->replace($descriptionWithDifferentLanguageHint)
);
}
/**
* @dataProvider provideStatusAndVersionByNamespace
*/
public function testStatusAndVersionByNamespace(
string $namespace,
string $version,
bool $isBeta = false
) {
$serviceXml = str_replace(
'\Google\Cloud\Vision\V1',
'\Google\Cloud\Vision\\' . $namespace,
file_get_contents(__DIR__ . '/../../fixtures/phpdoc/service.xml')
);
$class = new ClassNode(new SimpleXMLElement($serviceXml));
$this->assertTrue($class->isServiceClass());
$this->assertEquals($version, $class->getVersion());
$this->assertEquals($isBeta, $class->getStatus() === 'beta');
}
public function provideStatusAndVersionByNamespace()
{
return [
['V1alpha', 'V1alpha', true],
['V1beta', 'V1beta', true],
['V1alpha1', 'V1alpha1', true],
['V1beta1', 'V1beta1', true],
['V1p1alpha1', 'V1p1alpha1', true],
['V1p1beta1', 'V1p1beta1', true],
['V2p2beta2', 'V2p2beta2', true],
['V1beta1\Foo', 'V1beta1', true],
['V1beta\Foo', 'V1beta', true],
['V1betaFoo', ''],
['V1', 'V1'],
['V1\Foo', 'V1'],
['V1p1zeta1', ''],
['V1z1beta', ''],
['Foo', ''],
];
}
/**
* @dataProvider provideInvalidXrefs
*/
public function testInvalidXrefs(string $description, array $invalidXrefs = [])
{
$classXml = '<class><full_name>TestClass</full_name><docblock><description>%s</description></docblock></class>';
$class = new ClassNode(new SimpleXMLElement(sprintf($classXml, $description)));
$validator = new class () {
use XrefValidationTrait {
getInvalidXrefs as public;
}
};
$this->assertEquals($invalidXrefs, $validator->getInvalidXrefs($class->getContent()));
}
public function provideInvalidXrefs()
{
return [
['{@see \DoesntExist}'], // class doesn't exist, but is still a valid xref
['{@see \SimpleXMLElement::method()}'], // method doesn't exist, but is still a valid xref
['{@see \SimpleXMLElement::addAttribute()}'], // valid method
['{@see \SimpleXMLElement::OUTPUT_FOO}'], // constant doesn't exist, but is still a valid xref
[sprintf('{@see \%s::OUTPUT_NORMAL}', OutputInterface::class)], // valid constant
['Take a look at {@see https://foo.bar} for more.'], // valid
['{@see Foo\Bar}', ['Foo\Bar']], // invalid
['Take a look at {@see Foo\Bar} for more.', ['Foo\Bar']], // invalid
[
'{@see \Google\Cloud\PubSub\Google\Cloud\PubSub\Foo}',
['\Google\Cloud\PubSub\Google\Cloud\PubSub\Foo']
], // invalid
];
}
/**
* @dataProvider provideBrokenXrefs
*/
public function testBrokenXrefs(string $description, array $brokenXrefs = [])
{
$classXml = '<class><full_name>TestClass</full_name><docblock><description>%s</description></docblock></class>';
$class = new ClassNode(new SimpleXMLElement(sprintf($classXml, $description)));
$validator = new class () {
use XrefValidationTrait {
getBrokenXrefs as public;
}
};
$this->assertEquals($brokenXrefs, $validator->getBrokenXrefs($class->getContent()));
}
public function provideBrokenXrefs()
{
return [
['{@see \OutputInterface}', ['\OutputInterface']], // invalid class (doesn't exist)
['{@see \SimpleXMLElement}.'], // valid class
['{@see \SimpleXMLElement::method()}', ['\SimpleXMLElement::method()']], // invalid method (doesn't exist)
['{@see \SimpleXMLElement::addAttribute()}'], // valid method
['{@see \SimpleXMLElement::OUTPUT_FOO}', ['\SimpleXMLElement::OUTPUT_FOO']], // invalid constant (doesn't exist)
[sprintf('{@see \%s::OUTPUT_NORMAL}', OutputInterface::class)], // valid constant
];
}
}