-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnnotationGeneratorTest.php
More file actions
1184 lines (1119 loc) · 50.7 KB
/
AnnotationGeneratorTest.php
File metadata and controls
1184 lines (1119 loc) · 50.7 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
declare(strict_types=1);
namespace Piwik\Plugins\OpenApiDocs\tests\Unit;
require_once PIWIK_INCLUDE_PATH . '/plugins/OpenApiDocs/vendor/autoload.php';
use PHPUnit\Framework\TestCase;
use Piwik\API\DocumentationGenerator;
use Piwik\API\NoDefaultValue;
use Piwik\Plugins\OpenApiDocs\Annotations\AnnotationGenerator;
use Piwik\Plugins\OpenApiDocs\OpenApiDocs;
/**
* @group OpenApiDocs
* @group OpenApiDocs_Unit
* @group OpenApiDocs_AnnotationGeneratorTest
*/
class AnnotationGeneratorTest extends TestCase
{
public const TEST_RESOURCES_DIR = __DIR__ . '/../Resources';
public const EXAMPLE_API_ENDPOINTS = [
'API.get',
'API.getGlossaryMetrics',
'API.getGlossaryReports',
'API.getIpFromHeader',
'API.getMatomoVersion',
'API.getMetadata',
'API.getPagesComparisonsDisabledFor',
'API.getPhpVersion',
'API.getProcessedReport',
'API.getReportMetadata',
'API.getReportPagesMetadata',
'API.getSegmentsMetadata',
'API.getSettings',
'API.getSuggestedValuesForSegment',
'API.getWidgetMetadata',
'CustomAlerts.deleteAlert',
'CustomAlerts.getAlert',
'CustomAlerts.getAlerts',
'CustomAlerts.getTriggeredAlerts',
'CustomDimensions.getAvailableExtractionDimensions',
'CustomDimensions.getAvailableScopes',
'CustomDimensions.getConfiguredCustomDimensions',
'CustomDimensions.getCustomDimension',
'LogViewer.getAvailableLogReaders',
'LogViewer.getConfiguredLogReaders',
'LogViewer.getLogConfig',
'LogViewer.getLogEntries',
'MarketingCampaignsReporting.getContent',
'MarketingCampaignsReporting.getGroup',
'MarketingCampaignsReporting.getId',
'MarketingCampaignsReporting.getKeyword',
'MarketingCampaignsReporting.getMedium',
'MarketingCampaignsReporting.getName',
'MarketingCampaignsReporting.getPlacement',
'MarketingCampaignsReporting.getSource',
'MarketingCampaignsReporting.getSourceMedium',
];
public const EXAMPLE_RESPONSE_FILE_NAMES = [
'API.get.json',
'API.get.tsv',
'API.get.xml',
'API.getGlossaryMetrics.json',
'API.getGlossaryMetrics.tsv',
'API.getGlossaryMetrics.xml',
'API.getGlossaryReports.json',
'API.getGlossaryReports.tsv',
'API.getGlossaryReports.xml',
'API.getIpFromHeader.json',
'API.getIpFromHeader.tsv',
'API.getIpFromHeader.xml',
'API.getMatomoVersion.json',
'API.getMatomoVersion.tsv',
'API.getMatomoVersion.xml',
'API.getMetadata.json',
'API.getMetadata.xml',
'API.getPagesComparisonsDisabledFor.json',
'API.getPagesComparisonsDisabledFor.tsv',
'API.getPagesComparisonsDisabledFor.xml',
'API.getPhpVersion.json',
'API.getPhpVersion.tsv',
'API.getPhpVersion.xml',
'API.getProcessedReport.json',
'API.getProcessedReport.xml',
'API.getReportMetadata.json',
'API.getReportMetadata.xml',
'API.getReportPagesMetadata.json',
'API.getReportPagesMetadata.xml',
'API.getSegmentsMetadata.json',
'API.getSegmentsMetadata.xml',
'API.getSettings.json',
'API.getSettings.tsv',
'API.getSettings.xml',
'API.getSuggestedValuesForSegment.json',
'API.getSuggestedValuesForSegment.tsv',
'API.getSuggestedValuesForSegment.xml',
'API.getWidgetMetadata.json',
'API.getWidgetMetadata.xml',
'CustomAlerts.deleteAlert.json',
'CustomAlerts.deleteAlert.xml',
'CustomAlerts.getAlert.json',
'CustomAlerts.getAlerts.json',
'CustomAlerts.getAlerts.xml',
'CustomAlerts.getAlert.xml',
'CustomAlerts.getTriggeredAlerts.json',
'CustomAlerts.getTriggeredAlerts.xml',
'CustomDimensions.getAvailableExtractionDimensions.json',
'CustomDimensions.getAvailableExtractionDimensions.tsv',
'CustomDimensions.getAvailableExtractionDimensions.xml',
'CustomDimensions.getAvailableScopes.json',
'CustomDimensions.getAvailableScopes.tsv',
'CustomDimensions.getAvailableScopes.xml',
'CustomDimensions.getConfiguredCustomDimensions.json',
'CustomDimensions.getConfiguredCustomDimensions.xml',
'CustomDimensions.getCustomDimension.json',
'CustomDimensions.getCustomDimension.tsv',
'CustomDimensions.getCustomDimension.xml',
'LogViewer.getAvailableLogReaders.json',
'LogViewer.getAvailableLogReaders.tsv',
'LogViewer.getAvailableLogReaders.xml',
'LogViewer.getConfiguredLogReaders.json',
'LogViewer.getConfiguredLogReaders.tsv',
'LogViewer.getConfiguredLogReaders.xml',
'LogViewer.getLogConfig.json',
'LogViewer.getLogConfig.xml',
'LogViewer.getLogEntries.json',
'LogViewer.getLogEntries.tsv',
'LogViewer.getLogEntries.xml',
'MarketingCampaignsReporting.getKeyword.json',
'MarketingCampaignsReporting.getKeyword.tsv',
'MarketingCampaignsReporting.getKeyword.xml',
'MarketingCampaignsReporting.getName.json',
'MarketingCampaignsReporting.getName.tsv',
'MarketingCampaignsReporting.getName.xml',
];
public const EXAMPLE_API_METHOD_DOC_BLOCK1 = '/**
* Copies a specified custom report to one or more sites. If a custom report with the same name already exists, the new custom report
* will have an automatically adjusted name to make it unique to the assigned site.
*
* @param int $idSite
* @param int $idCustomReport ID of the custom report to duplicate.
* @param int[] $idDestinationSites Optional array of IDs identifying which site(s) the new custom report is to be
* assigned to. The default is [idSite] when nothing is provided.
*
* @return array Some test description for the return annotation.
* @throws Exception
*/';
/**
* @var array
*/
private static $normalisedExamples;
/**
* @var array
*/
private static $truncatedExamples;
/**
* @var array
*/
private static $exampleSchemas;
/**
* @var AnnotationGenerator
*/
private $annotationGenerator;
public function setUp(): void
{
$this->annotationGenerator = new AnnotationGenerator(new DocumentationGenerator());
}
/**
* @param string $apiEndpoint The identifier of the endpoint, like CustomAlerts.getAlert.
* @param string $format
*
* @return string String contents of the raw response body. If the file isn't found, an empty string is returned.
* @throws \Exception
*/
private static function getRawExampleResponseForApiEndpoint(string $apiEndpoint, string $format = 'json'): string
{
if (!in_array(strtolower($format), ['json', 'xml', 'tsv'])) {
throw new \Exception('Invalid format: ' . $format . '. Must be: "json", "xml", or "tsv"');
}
return file_get_contents(self::TEST_RESOURCES_DIR . "/ExampleResponses/{$apiEndpoint}.{$format}") ?: '';
}
/**
* @param string $plugin
* @param string $method
* @param string $format
*
* @return string String contents of the raw response body. If the file isn't found, an empty string is returned.
* @throws \Exception
*/
private static function getRawExampleResponseForPluginMethod(string $plugin, string $method, string $format = 'json'): string
{
return self::getRawExampleResponseForApiEndpoint("{$plugin}.{$method}", $format);
}
/**
* Get the map of example responses which have been normalised in preparation of building schemas.
*
* @return array The map of example responses for a bunch of API endpoints.
* E.g. ['plugin.method' => ['json' => '...', 'xml' => '...', 'tsv' => '...']]
*/
private static function getNormalisedExamples(): array
{
if (empty(self::$normalisedExamples)) {
$demoExampleResponsesString = file_get_contents(self::TEST_RESOURCES_DIR . '/ExampleResponsesNormalised/ExamplesFromDemoByType.json') ?: '';
$localExampleResponsesString = file_get_contents(self::TEST_RESOURCES_DIR . '/ExampleResponsesNormalised/ExamplesFromLocalByType.json') ?: '';
$demoJson = json_decode($demoExampleResponsesString, true) ?? [];
$localJson = json_decode($localExampleResponsesString, true) ?? [];
self::$normalisedExamples = array_merge($demoJson, $localJson);
}
return self::$normalisedExamples;
}
/**
* Get the map of example responses which have been normalised and truncated.
*
* @return array The map of example responses for a bunch of API endpoints.
* E.g. ['plugin.method' => ['json' => '...', 'xml' => '...', 'tsv' => '...']]
*/
private static function getTruncatedExamples(bool $onlyTruncated = false): array
{
if (empty(self::$truncatedExamples)) {
$exampleResponsesPostTruncationString = file_get_contents(self::TEST_RESOURCES_DIR . '/ExampleResponsesNormalised/ExamplesPostTruncationByType.json') ?: '';
self::$truncatedExamples = json_decode($exampleResponsesPostTruncationString, true) ?? [];
}
if ($onlyTruncated) {
return self::$truncatedExamples;
}
// Return the normalised examples with any truncated examples overriding them
return array_merge(self::getNormalisedExamples(), self::$truncatedExamples);
}
/**
* Get the map of example schemas.
*
* @return array The map of example schemas for a bunch of API endpoints.
* E.g. ['plugin.method' => ['json' => '...', 'xml' => '...', 'tsv' => '...']]
*/
private static function getExampleSchemas(): array
{
if (empty(self::$exampleSchemas)) {
$exampleResponseSchemasString = file_get_contents(self::TEST_RESOURCES_DIR . '/ExampleResponsesNormalised/ExamplesSchemasByType.json') ?: '';
self::$exampleSchemas = json_decode($exampleResponseSchemasString, true) ?? [];
}
return self::$exampleSchemas;
}
public function testGeneratePluginApiAnnotations(): void
{
// TODO - Test the generatePluginApiAnnotations method
$this->expectNotToPerformAssertions();
}
public function testGetContentForGeneratedAnnotationsFile(): void
{
// TODO - getContentForGeneratedAnnotationsFile method
$this->expectNotToPerformAssertions();
}
public function testBuildAnnotationForMethod(): void
{
// TODO - buildAnnotationForMethod method
$this->expectNotToPerformAssertions();
}
public function testGetParamInfoFromDocBlock(): void
{
// TODO - Update to use resource file and/or dataprovider to test more than one comment block
$expected = [
'idSite' => [
'type' => 'int',
'description' => '',
'byRef' => false,
'variadic' => false,
],
'idCustomReport' => [
'type' => 'int',
'description' => 'ID of the custom report to duplicate.',
'byRef' => false,
'variadic' => false,
],
'idDestinationSites' => [
'type' => 'int[]',
'description' => 'Optional array of IDs identifying which site(s) the new custom report is to be assigned to. The default is [idSite] when nothing is provided.',
'byRef' => false,
'variadic' => false,
],
];
$this->assertEquals($expected, $this->annotationGenerator->getParamInfoFromDocBlock(self::EXAMPLE_API_METHOD_DOC_BLOCK1));
}
public function testGetResponseInfoFromDocBlock(): void
{
// TODO - Update to use resource file and/or dataprovider to test more than one comment block
$expected = [
'type' => 'array',
'description' => 'Some test description for the return annotation.',
];
$this->assertEquals($expected, $this->annotationGenerator->getResponseInfoFromDocBlock(self::EXAMPLE_API_METHOD_DOC_BLOCK1));
}
/**
* @dataProvider getTestDataForBuildVirtualPath
*
* @param string $pathTemplate
* @param string $pluginName
* @param string $methodName
* @param string $expected
*
* @return void
*/
public function testBuildVirtualPath(string $pathTemplate, string $pluginName, string $methodName, string $expected): void
{
$this->assertEquals($expected, $this->annotationGenerator->buildVirtualPath($pathTemplate, $pluginName, $methodName));
}
/**
* @return iterable<string, string, string, string>
*/
public static function getTestDataForBuildVirtualPath(): iterable
{
yield 'should be empty when all values are empty' => ['', '', '', ''];
yield 'should be empty when template is empty' => ['', 'SomePlugin', 'SomeMethod', ''];
yield 'should remain the same when template does not include placeholders' => ['/some/test/path', 'SomePlugin', 'SomeMethod', '/some/test/path'];
yield 'should replace only plugin when the only placeholder' => ['/{plugin}/test/path', 'SomePlugin', 'SomeMethod', '/SomePlugin/test/path'];
yield 'should replace only method when the only placeholder' => ['/{method}/test/path', 'SomePlugin', 'SomeMethod', '/SomeMethod/test/path'];
yield 'should include both values when placeholders are present' => ['/{plugin}/{method}/test/path', 'SomePlugin', 'SomeMethod', '/SomePlugin/SomeMethod/test/path'];
yield 'should follow placement of placeholders' => ['/{method}/{plugin}/test/path', 'SomePlugin', 'SomeMethod', '/SomeMethod/SomePlugin/test/path'];
yield 'should allow duplication of placeholders' => ['/{plugin}/{method}/test/path/{plugin}', 'SomePlugin', 'SomeMethod', '/SomePlugin/SomeMethod/test/path/SomePlugin'];
yield 'should work with query parameter format' => ['/index.php?module=API&method={plugin}.{method}', 'SomePlugin', 'SomeMethod', '/index.php?module=API&method=SomePlugin.SomeMethod'];
yield 'should work with different names' => ['/index.php?module=API&method={plugin}.{method}', 'TagManager', 'GetContainers', '/index.php?module=API&method=TagManager.GetContainers'];
}
/**
* @dataProvider getTestDataForBuildParameterAnnotationData
*
* @param string $paramName
* @param array $paramMetadata
* @param array $paramDocInfo
* @param array $expected
*
* @return void
*/
public function testBuildParameterAnnotationData(string $paramName, array $paramMetadata, array $paramDocInfo, array $expected): void
{
$this->assertEquals($expected, $this->annotationGenerator->buildParameterAnnotationData('someMethodName', $paramName, $paramMetadata, $paramDocInfo));
}
/**
* @return iterable<string, array, array, array>
*/
public function getTestDataForBuildParameterAnnotationData(): iterable
{
yield 'should be default values with no data' => ['', [], [], [
'name' => '',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should be very basic with only param name' => ['someParam', [], [], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should be fine with another param name' => ['idSite', [], [], [
'name' => 'idSite',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should be still have string type when string is provided' => ['someParam', [
'type' => 'string',
], [], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should be integer type when int is provided' => ['someParam', [
'type' => 'int',
], [], [
'name' => 'someParam',
'types' => ['integer' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should be array type when array is provided' => ['someParam', [
'type' => 'array',
], [], [
'name' => 'someParam',
'types' => ['array' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should show as not required and use metadata default when provided' => ['someParam', [
'default' => 'SomeDefaultValue',
], [], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'false',
'default' => '"SomeDefaultValue"',
'example' => '',
]];
yield 'should not wrap metadata default value when boolean type' => ['someParam', [
'type' => 'bool',
'default' => true,
], [], [
'name' => 'someParam',
'types' => ['boolean' => null],
'description' => '',
'required' => 'false',
'default' => 'true',
'example' => '',
]];
yield 'should still count false boolean as a default value' => ['someParam', [
'type' => 'bool',
'default' => false,
], [], [
'name' => 'someParam',
'types' => ['boolean' => null],
'description' => '',
'required' => 'false',
'default' => 'false',
'example' => '',
]];
yield 'should still count empty string as a default value' => ['someParam', [
'default' => '',
], [], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'false',
'default' => '""',
'example' => '',
]];
yield 'should not count the NoDefaultValue class as a default value' => ['someParam', [
'default' => new NoDefaultValue(),
], [], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should not override the metadata type when it is integer' => ['someParam', [
'type' => 'int',
], [
'type' => 'array',
], [
'name' => 'someParam',
'types' => ['integer' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should override the metadata type when it is string and docInfo is array' => ['someParam', [
'type' => 'string',
], [
'type' => 'array',
], [
'name' => 'someParam',
'types' => ['array' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should use docInfo type when metadata type is empty' => ['someParam', [], [
'type' => 'boolean',
], [
'name' => 'someParam',
'types' => ['boolean' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should determine subtype when docInfo type indicates the type of array items' => ['someParam', [], [
'type' => 'int[]',
], [
'name' => 'someParam',
'types' => ['array' => 'integer'],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should still determine subtype when metadata type is array and docInfo indicates subtype' => ['someParam', [
'type' => 'array',
], [
'type' => 'int[]',
], [
'name' => 'someParam',
'types' => ['array' => 'integer'],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should allow multiple types when docInfo includes them' => ['someParam', [], [
'type' => 'string|int|int[]',
], [
'name' => 'someParam',
'types' => ['string' => null, 'integer' => null, 'array' => 'integer'],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should show one type when docInfo has two types and one is bool' => ['someParam', [], [
'type' => 'string|bool',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should remove bool type when docInfo has more than 2 types and one is bool' => ['someParam', [], [
'type' => 'string|int|bool',
], [
'name' => 'someParam',
'types' => ['string' => null, 'integer' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should remove bool type regardless of spacing around pipe' => ['someParam', [], [
'type' => 'string | int | bool',
], [
'name' => 'someParam',
'types' => ['string' => null, 'integer' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should remove bool type regardless of spacing and order' => ['someParam', [], [
'type' => 'bool | string',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should remove bool type even when type hints are wrapped by parenthesis' => ['someParam', [], [
'type' => '(bool | string)',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should allow multiple types when metadata type is string' => ['someParam', [
'type' => 'string',
], [
'type' => 'string|int|int[]',
], [
'name' => 'someParam',
'types' => ['string' => null, 'integer' => null, 'array' => 'integer'],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should allow multiple types when metadata type is bool and doc type is piped' => ['someParam', [
'type' => 'bool',
], [
'type' => 'string|int|bool',
], [
'name' => 'someParam',
'types' => ['string' => null, 'integer' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should allow multiple types when metadata type is bool and doc type is piped even if default is bool' => ['someParam', [
'type' => 'bool',
'default' => false,
], [
'type' => 'string|int|bool',
], [
'name' => 'someParam',
'types' => ['string' => null, 'integer' => null],
'description' => '',
'required' => 'false',
'default' => 'false',
'example' => '',
]];
yield 'should not allow multiple types when metadata type is specified' => ['someParam', [
'type' => 'integer',
], [
'type' => 'string|int|int[]',
], [
'name' => 'someParam',
'types' => ['integer' => null],
'description' => '',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should use docInfo description when provided' => ['someParam', [], [
'description' => 'Some test description.',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => 'Some test description.',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '',
]];
yield 'should use example when provided using custom syntax in docInfo description' => ['someParam', [], [
'description' => 'Some test description. [@example=true]',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => 'Some test description.',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => 'true',
]];
yield 'should use string example when provided using custom syntax in docInfo description' => ['someParam', [], [
'description' => 'Some test description. [@example="Some test example string."]',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => 'Some test description.',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => 'Some test example string.',
]];
yield 'should allow full JSON in docInfo description examples' => ['someParam', [], [
'description' => 'Some test description. [@example={"key1":"value1","key2":"value2"}]',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => 'Some test description.',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '{"key1":"value1","key2":"value2"}',
]];
yield 'should allow full JSON array in docInfo description examples' => ['someParam', [], [
'description' => 'Some test description. [@example=[{"key1":"value1","key2":"value2"},{"key3":"value3","key4":"value4"}]]',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => 'Some test description.',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '[{"key1":"value1","key2":"value2"},{"key3":"value3","key4":"value4"}]',
]];
yield 'should allow full JSON array examples even when in the middle of the docInfo description' => ['someParam', [], [
'description' => 'Some test description. [@example=[{"key1":"value1","key2":"value2"},{"key3":"value3","key4":"value4"}]] More test description.',
], [
'name' => 'someParam',
'types' => ['string' => null],
'description' => 'Some test description. More test description.',
'required' => 'true',
'default' => 'Piwik\API\NoDefaultValue',
'example' => '[{"key1":"value1","key2":"value2"},{"key3":"value3","key4":"value4"}]',
]];
}
public function testDetermineParameters(): void
{
// TODO - determineParameters method
$this->expectNotToPerformAssertions();
}
/**
* @dataProvider getTestDataForGetOpenApiTypeFromPhpType
*
* @param string $type
* @param string $expected
* @return void
*/
public function testGetOpenApiTypeFromPhpType(string $type, string $expected): void
{
$this->assertEquals($expected, $this->annotationGenerator->getOpenApiTypeFromPhpType($type));
}
/**
* @return iterable<string, string}>
*/
public function getTestDataForGetOpenApiTypeFromPhpType(): iterable
{
yield 'should be string for empty' => ['', 'string'];
yield 'should be string for unknown' => ['unknown', 'string'];
yield 'should be string for abc123' => ['abc123', 'string'];
yield 'should be array for array' => ['array', 'array'];
yield 'should be array for []' => ['[]', 'array'];
yield 'should be array for int[]' => ['int[]', 'array'];
yield 'should be array for string[]' => ['string[]', 'array'];
yield 'should be array for bool[]' => ['bool[]', 'array'];
yield 'should be array for float[]' => ['float[]', 'array'];
yield 'should be array for double[]' => ['double[]', 'array'];
yield 'should be integer for int' => ['int', 'integer'];
yield 'should be integer for integer' => ['integer', 'integer'];
yield 'should be boolean for bool' => ['bool', 'boolean'];
yield 'should be boolean for boolean' => ['boolean', 'boolean'];
yield 'should be number for float' => ['float', 'number'];
yield 'should be number for double' => ['double', 'number'];
}
public function testGetApplicableDemoExampleUrls(): void
{
// TODO - getApplicableDemoExampleUrls method
$this->expectNotToPerformAssertions();
}
public function testGetDemoReportMetadata(): void
{
// TODO - getDemoReportMetadata method
$this->expectNotToPerformAssertions();
}
public function testGetExampleIfAvailable(): void
{
// TODO - getExampleIfAvailable method
$this->expectNotToPerformAssertions();
}
public function testGetReportExampleUrlFromMetadata(): void
{
// TODO - getReportExampleUrlFromMetadata method
$this->expectNotToPerformAssertions();
}
/**
* @dataProvider getTestXmlExampleObjectData
*
* @param string $endpoint
* @param string $content
* @param string $expected
*
* @return void
* @throws \Exception
*/
public function testConvertExampleXmlToObject(string $endpoint, string $content, string $expected): void
{
$this->assertNotEmpty($content, 'The example response should not be empty for endpoint: ' . $endpoint);
$this->assertEquals($expected, json_encode($this->annotationGenerator->convertExampleXmlToObject($content)), "The converted XML was not as expected for endpoint $endpoint.");
}
/**
* @return iterable<string, string, string>
* @throws \Exception
*/
public static function getTestXmlExampleObjectData(): iterable
{
$normalisedMap = self::getNormalisedExamples();
foreach (self::EXAMPLE_API_ENDPOINTS as $endpoint) {
$content = self::getRawExampleResponseForApiEndpoint($endpoint, 'xml');
$expected = $normalisedMap[$endpoint]['xml'] ?? [];
yield "converted XML should match expected JSON for $endpoint endpoint" => [$endpoint, $content, $expected];
}
}
public function testDetermineResponses(): void
{
// TODO - determineResponses method
$this->expectNotToPerformAssertions();
}
/**
* @dataProvider getTestTruncatedExampleObjectData
*
* @param string $endpoint
* @param string $type
* @param string $normalisedExample
* @param string $expectedExample
*
* @return void
*/
public function testCutExampleCloseToCharLimit(string $endpoint, string $type, string $normalisedExample, string $expectedExample): void
{
$this->assertNotEmpty($normalisedExample, "The example response should not be empty for endpoint '$endpoint' and type '$type'.");
$result = $this->annotationGenerator->cutExampleCloseToCharLimit($normalisedExample, $type);
// Add a little wiggle room since the truncation isn't exact and might allow a little over the limit
$this->assertLessThanOrEqual(AnnotationGenerator::EXAMPLE_CHAR_LIMIT + 30, strlen($result), "The example response should not exceed the character limit for endpoint '$endpoint' and type '$type'.");
$this->assertEquals($expectedExample, $result, "The truncated example was not as expected for endpoint '$endpoint' and type '$type'.");
}
/**
* @return iterable<string, string, string, string>
*/
public static function getTestTruncatedExampleObjectData(): iterable
{
$truncatedMap = self::getTruncatedExamples();
$normalisedMap = self::getNormalisedExamples();
foreach (self::EXAMPLE_API_ENDPOINTS as $endpoint) {
$normalisedExamples = $normalisedMap[$endpoint] ?? [];
foreach ($normalisedExamples as $type => $normalisedExample) {
$expectedExample = $normalisedExample;
if (!empty($truncatedMap[$endpoint][$type])) {
$expectedExample = $truncatedMap[$endpoint][$type];
}
// Skip the endpoints which don't have TSV examples
if (
(
$type === 'tsv'
&& in_array($endpoint, [
'CustomAlerts.deleteAlert',
'CustomAlerts.getAlert',
'CustomAlerts.getAlerts',
'CustomAlerts.getTriggeredAlerts',
'CustomDimensions.getConfiguredCustomDimensions',
'LogViewer.getLogConfig',
])
)
) {
continue;
}
yield "truncated example should match expected JSON for $endpoint endpoint and $type type" => [$endpoint, $type, $normalisedExample, $expectedExample];
}
}
}
/**
* @dataProvider getTestJsonSchemaData
*
* @param string $endpoint
* @param array $normalisedObject
* @param array $expected
*
* @return void
*/
public function testBuildSchemaAnnotationFromJsonExample(string $endpoint, array $normalisedObject, array $expected): void
{
$this->assertNotEmpty($normalisedObject, 'The decoded example response should not be empty for endpoint: ' . $endpoint);
$result = $this->annotationGenerator->buildSchemaAnnotationFromJsonExample($normalisedObject);
$this->assertEquals($expected, $result, "The JSON schema was not as expected for endpoint $endpoint.");
}
/**
* @return iterable<string, array, array>
*/
public static function getTestJsonSchemaData(): iterable
{
$normalisedMap = self::getNormalisedExamples();
$schemasMap = self::getExampleSchemas();
foreach (self::EXAMPLE_API_ENDPOINTS as $endpoint) {
$normalisedString = $normalisedMap[$endpoint]['json'] ?? '';
$normalisedObject = json_decode($normalisedString, true) ?? [];
$expected = json_decode($schemasMap[$endpoint]['json'] ?? '', true) ?? [];
yield "should match expected JSON schema for $endpoint endpoint" => [$endpoint, $normalisedObject, $expected];
}
}
public function testBuildPropertyAnnotationFromJsonExample(): void
{
// TODO - buildPropertyAnnotationFromJsonExample method. It's covered pretty well by testBuildSchemaAnnotationFromJsonExample, but there might be specific cases to test
$this->expectNotToPerformAssertions();
}
/**
* @dataProvider getTestXmlSchemaData
*
* @param string $endpoint
* @param array $normalisedObject
* @param array $expected
*
* @return void
*/
public function testBuildSchemaAnnotationFromXmlExample(string $endpoint, array $normalisedObject, array $expected): void
{
$this->assertNotEmpty($normalisedObject, 'The decoded example response should not be empty for endpoint: ' . $endpoint);
$result = $this->annotationGenerator->buildSchemaAnnotationFromXmlExample($normalisedObject);
$this->assertEquals(json_encode($expected), json_encode($result), "The XML schema was not as expected for endpoint $endpoint.");
$this->assertStringNotContainsString(OpenApiDocs::OA_XML_ATTRIBUTES_TEMP_PROPERTY_NAME, json_encode($normalisedObject), "The XML example object should no longer contain the temp attribute property for endpoint $endpoint.");
}
/**
* @return iterable<string, array, array>
*/
public static function getTestXmlSchemaData(): iterable
{
$normalisedMap = self::getNormalisedExamples();
$schemasMap = self::getExampleSchemas();
foreach (self::EXAMPLE_API_ENDPOINTS as $endpoint) {
$normalisedString = $normalisedMap[$endpoint]['xml'] ?? '';
$normalisedObject = json_decode($normalisedString, true) ?? [];
$expected = json_decode($schemasMap[$endpoint]['xml'] ?? '', true) ?? [];
yield "should match expected XML schema for $endpoint endpoint" => [$endpoint, $normalisedObject, $expected];
}
}
public function testBuildPropertyAnnotationFromXmlExample(): void
{
// TODO - buildPropertyAnnotationFromXmlExample method. It's covered pretty well by testBuildSchemaAnnotationFromXmlExample, but there might be specific cases to test
$this->expectNotToPerformAssertions();
}
/**
* @dataProvider getTestDataForTestBuildXmlAttributeSchemaLines
*
* @param array $attributes
* @param array $expected
*
* @return void
*/
public function testBuildXmlAttributeSchemaLines(array $attributes, array $expected): void
{
$this->assertEquals($expected, $this->annotationGenerator->buildXmlAttributeSchemaLines($attributes));
}
public static function getTestDataForTestBuildXmlAttributeSchemaLines(): iterable
{
yield 'should return empty array when attributes are empty' => [[], []];
yield 'should return empty array when attributes are nested empty' => [[[]], []];
yield 'should return empty array when no attributes have a name' => [[['' => 'value']], []];
yield 'should return annotation array as long as the attribute has a name' => [
['testAttribute' => ''],
[['@OA\Property' => ['property="testAttribute",', 'type="string",', '@OA\Xml(attribute=true),']]],
];
yield 'should return annotation array as long as the attribute has a name even when nested' => [
[['testAttribute' => '']],
[['@OA\Property' => ['property="testAttribute",', 'type="string",', '@OA\Xml(attribute=true),']]],
];
yield 'should return annotation array with example when value is set' => [
['testAttribute' => 'testValue'],
[['@OA\Property' => ['property="testAttribute",', 'type="string",', '@OA\Xml(attribute=true),', 'example="testValue"']]],
];
yield 'should return annotation array with example when value is set when nested' => [
[['testAttribute' => 'testValue']],
[['@OA\Property' => ['property="testAttribute",', 'type="string",', '@OA\Xml(attribute=true),', 'example="testValue"']]],
];
yield 'should return multiple annotation arrays without example when value is not set' => [
['testAttribute1' => '', 'testAttribute2' => ''],
[
['@OA\Property' => ['property="testAttribute1",', 'type="string",', '@OA\Xml(attribute=true),']],
['@OA\Property' => ['property="testAttribute2",', 'type="string",', '@OA\Xml(attribute=true),']],
],
];
yield 'should return multiple annotation arrays without example when value is not set when nested' => [
[['testAttribute1' => ''], ['testAttribute2' => '']],
[
['@OA\Property' => ['property="testAttribute1",', 'type="string",', '@OA\Xml(attribute=true),']],
['@OA\Property' => ['property="testAttribute2",', 'type="string",', '@OA\Xml(attribute=true),']],
],
];
yield 'should return multiple annotation arrays with example when value is set' => [
['testAttribute1' => 'testValue1', 'testAttribute2' => 'testValue2'],
[
['@OA\Property' => ['property="testAttribute1",', 'type="string",', '@OA\Xml(attribute=true),', 'example="testValue1"']],
['@OA\Property' => ['property="testAttribute2",', 'type="string",', '@OA\Xml(attribute=true),', 'example="testValue2"']],
],
];
yield 'should return multiple annotation arrays with example when value is set when nested' => [
[['testAttribute1' => 'testValue1'], ['testAttribute2' => 'testValue2']],
[