-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathTestGenerator.php
2086 lines (1900 loc) · 77.5 KB
/
TestGenerator.php
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
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\Util;
use Magento\FunctionalTestingFramework\Config\MftfApplicationConfig;
use Magento\FunctionalTestingFramework\DataGenerator\Handlers\CredentialStore;
use Magento\FunctionalTestingFramework\DataGenerator\Handlers\PersistedObjectHandler;
use Magento\FunctionalTestingFramework\DataGenerator\Objects\EntityDataObject;
use Magento\FunctionalTestingFramework\Exceptions\TestFrameworkException;
use Magento\FunctionalTestingFramework\Exceptions\TestReferenceException;
use Magento\FunctionalTestingFramework\Suite\Handlers\SuiteObjectHandler;
use Magento\FunctionalTestingFramework\Test\Handlers\ActionGroupObjectHandler;
use Magento\FunctionalTestingFramework\Test\Handlers\TestObjectHandler;
use Magento\FunctionalTestingFramework\Test\Objects\ActionGroupObject;
use Magento\FunctionalTestingFramework\Test\Objects\ActionObject;
use Magento\FunctionalTestingFramework\DataGenerator\Handlers\DataObjectHandler;
use Magento\FunctionalTestingFramework\Test\Objects\TestHookObject;
use Magento\FunctionalTestingFramework\Test\Objects\TestObject;
use Magento\FunctionalTestingFramework\Util\Logger\LoggingUtil;
use Magento\FunctionalTestingFramework\Util\Manifest\BaseTestManifest;
use Magento\FunctionalTestingFramework\Util\Manifest\TestManifestFactory;
use Magento\FunctionalTestingFramework\Test\Util\ActionObjectExtractor;
use Magento\FunctionalTestingFramework\Test\Util\TestObjectExtractor;
use Magento\FunctionalTestingFramework\Util\Filesystem\DirSetupUtil;
use Magento\FunctionalTestingFramework\Test\Util\ActionMergeUtil;
use Magento\FunctionalTestingFramework\Util\Path\FilePathFormatter;
/**
* Class TestGenerator
* @SuppressWarnings(PHPMD)
*/
class TestGenerator
{
const ACTION_GROUP_STEP_KEY_REGEX = "/\[(?<actionGroupStepKey>.*)\]/";
const ACTION_STEP_KEY_REGEX = "/\/\/ stepKey: (?<stepKey>.*)/";
const REQUIRED_ENTITY_REFERENCE = 'createDataKey';
const GENERATED_DIR = '_generated';
const DEFAULT_DIR = 'default';
const TEST_SCOPE = 'test';
const HOOK_SCOPE = 'hook';
const SUITE_SCOPE = 'suite';
const PRESSKEY_ARRAY_ANCHOR_KEY = '987654321098765432109876543210';
const PERSISTED_OBJECT_NOTATION_REGEX = '/\${1,2}[\w.\[\]]+\${1,2}/';
const NO_STEPKEY_ACTIONS = [
'comment',
'retrieveEntityField',
'getSecret',
'magentoCLI',
'generateDate',
'field'
];
const STEP_KEY_ANNOTATION = " // stepKey: %s";
/**
* Actor name for AcceptanceTest
*
* @var string
*/
private $actor = 'I';
/**
* Path to the export dir.
*
* @var string
*/
private $exportDirectory;
/**
* Export dir name.
*
* @var string
*/
private $exportDirName;
/**
* Array of testObjects to be generated
*
* @var array
*/
private $tests;
/**
* Symfony console output interface.
*
* @var \Symfony\Component\Console\Output\ConsoleOutput
*/
private $consoleOutput;
/**
* Debug flag.
*
* @var boolean
*/
private $debug;
/**
* Current generation scope.
*
* @var string
*/
private $currentGenerationScope = TestGenerator::TEST_SCOPE;
/**
* TestGenerator constructor.
*
* @param string $exportDir
* @param array $tests
* @param boolean $debug
* @throws TestFrameworkException
*/
private function __construct($exportDir, $tests, $debug = false)
{
// private constructor for factory
$this->exportDirName = $exportDir ?? self::DEFAULT_DIR;
$exportDir = $exportDir ?? self::DEFAULT_DIR;
$this->exportDirectory = FilePathFormatter::format(TESTS_MODULE_PATH)
. self::GENERATED_DIR
. DIRECTORY_SEPARATOR
. $exportDir;
$this->tests = $tests;
$this->consoleOutput = new \Symfony\Component\Console\Output\ConsoleOutput();
$this->debug = $debug;
}
/**
* Singleton method to retrieve Test Generator
*
* @param string $dir
* @param array $tests
* @param boolean $debug
* @return TestGenerator
*/
public static function getInstance($dir = null, $tests = [], $debug = false)
{
return new TestGenerator($dir, $tests, $debug);
}
/**
* Returns the absolute path to the test export director for the generator instance.
*
* @return string
*/
public function getExportDir()
{
return $this->exportDirectory;
}
/**
* Load all Test files as Objects using the Test Object Handler, additionally validates test references being loaded
* for validity.
*
* @param array $testsToIgnore
* @return array
*/
private function loadAllTestObjects($testsToIgnore)
{
if ($this->tests === null || empty($this->tests)) {
$testObjects = TestObjectHandler::getInstance()->getAllObjects();
return array_diff_key($testObjects, $testsToIgnore);
}
// If we have a custom configuration, we need to check the tests passed in to insure that we can generate
// them in the current context.
$invalidTestObjects = array_intersect_key($this->tests, $testsToIgnore);
if (!empty($invalidTestObjects)) {
throw new TestReferenceException(
"Cannot reference test configuration for generation without accompanying suite.",
['tests' => array_keys($invalidTestObjects)]
);
}
return $this->tests;
}
/**
* Create a single PHP file containing the $cestPhp using the $filename.
* If the _generated directory doesn't exist it will be created.
*
* @param string $testPhp
* @param string $filename
* @return void
* @throws \Exception
*/
private function createCestFile($testPhp, $filename)
{
$exportFilePath = $this->exportDirectory . DIRECTORY_SEPARATOR . $filename . ".php";
$file = fopen($exportFilePath, 'w');
if (!$file) {
throw new \Exception("Could not open the file.");
}
fwrite($file, $testPhp);
fclose($file);
}
/**
* Assemble ALL PHP strings using the assembleAllTestPhp function. Loop over and pass each array item
* to the createCestFile function.
*
* @param BaseTestManifest $testManifest
* @param array $testsToIgnore
* @return void
* @throws TestReferenceException
* @throws \Exception
*/
public function createAllTestFiles($testManifest = null, $testsToIgnore = null)
{
if ($this->tests === null) {
// no-op if the test configuration is null
return;
}
DirSetupUtil::createGroupDir($this->exportDirectory);
if ($testsToIgnore === null) {
$testsToIgnore = SuiteObjectHandler::getInstance()->getAllTestReferences();
}
$testPhpArray = $this->assembleAllTestPhp($testManifest, $testsToIgnore);
foreach ($testPhpArray as $testPhpFile) {
$this->createCestFile($testPhpFile[1], $testPhpFile[0]);
}
}
/**
* Assemble the entire PHP string for a single Test based on a Test Object.
* Create all of the PHP strings for a Test. Concatenate the strings together.
*
* @param \Magento\FunctionalTestingFramework\Test\Objects\TestObject $testObject
* @return string
* @throws TestReferenceException
* @throws \Exception
*/
public function assembleTestPhp($testObject)
{
$usePhp = $this->generateUseStatementsPhp();
$classAnnotationsPhp = $this->generateAnnotationsPhp($testObject->getAnnotations());
$className = $testObject->getCodeceptionName();
try {
if (!$testObject->isSkipped() || MftfApplicationConfig::getConfig()->allowSkipped()) {
$hookPhp = $this->generateHooksPhp($testObject->getHooks());
} else {
$hookPhp = null;
}
$testsPhp = $this->generateTestPhp($testObject);
} catch (TestReferenceException $e) {
throw new TestReferenceException($e->getMessage() . "\n" . $testObject->getFilename());
}
$cestPhp = "<?php\n";
$cestPhp .= "namespace Magento\AcceptanceTest\\_" . $this->exportDirName . "\Backend;\n\n";
$cestPhp .= $usePhp;
$cestPhp .= $classAnnotationsPhp;
$cestPhp .= sprintf("class %s\n", $className);
$cestPhp .= "{\n";
$cestPhp .= $hookPhp;
$cestPhp .= $testsPhp;
$cestPhp .= "}\n";
return $cestPhp;
}
/**
* Load ALL Test objects. Loop over and pass each to the assembleTestPhp function.
*
* @param BaseTestManifest $testManifest
* @param array $testsToIgnore
* @return array
*/
private function assembleAllTestPhp($testManifest, array $testsToIgnore)
{
/** @var TestObject[] $testObjects */
$testObjects = $this->loadAllTestObjects($testsToIgnore);
$cestPhpArray = [];
foreach ($testObjects as $test) {
// Do not generate test if it is an extended test and parent does not exist
if ($test->isSkipped() && !empty($test->getParentName())) {
try {
TestObjectHandler::getInstance()->getObject($test->getParentName());
} catch (TestReferenceException $e) {
print("{$test->getName()} will not be generated. Parent {$e->getMessage()} \n");
continue;
}
}
$this->debug("<comment>Start creating test: " . $test->getCodeceptionName() . "</comment>");
$php = $this->assembleTestPhp($test);
$cestPhpArray[] = [$test->getCodeceptionName(), $php];
$debugInformation = $test->getDebugInformation();
$this->debug($debugInformation);
$this->debug("<comment>Finish creating test: " . $test->getCodeceptionName() . "</comment>" . PHP_EOL);
//write to manifest here if manifest is not null
if ($testManifest != null) {
$testManifest->addTest($test);
}
}
return $cestPhpArray;
}
/**
* Output information in console when debug flag is enabled.
*
* @param array|string $messages
* @return void
*/
private function debug($messages)
{
if ($this->debug && $messages) {
$messages = (array)$messages;
foreach ($messages as $message) {
$this->consoleOutput->writeln($message);
}
}
}
/**
* Creates a PHP string for the necessary Allure and AcceptanceTester use statements.
* Since we don't support other dependencies at this time, this function takes no parameter.
*
* @return string
*/
private function generateUseStatementsPhp()
{
$useStatementsPhp = "use Magento\FunctionalTestingFramework\AcceptanceTester;\n";
$useStatementsPhp .= "use \Codeception\Util\Locator;\n";
$allureStatements = [
"Yandex\Allure\Adapter\Annotation\Features;",
"Yandex\Allure\Adapter\Annotation\Stories;",
"Yandex\Allure\Adapter\Annotation\Title;",
"Yandex\Allure\Adapter\Annotation\Description;",
"Yandex\Allure\Adapter\Annotation\Parameter;",
"Yandex\Allure\Adapter\Annotation\Severity;",
"Yandex\Allure\Adapter\Model\SeverityLevel;",
"Yandex\Allure\Adapter\Annotation\TestCaseId;\n"
];
foreach ($allureStatements as $allureUseStatement) {
$useStatementsPhp .= sprintf("use %s\n", $allureUseStatement);
}
return $useStatementsPhp;
}
/**
* Generates Annotations PHP for given object, using given scope to determine indentation and additional output.
*
* @param array $annotationsObject
* @param boolean $isMethod
* @return string
*/
private function generateAnnotationsPhp($annotationsObject, $isMethod = false)
{
//TODO: Refactor to deal with PHPMD.CyclomaticComplexity
if ($isMethod) {
$indent = "\t";
} else {
$indent = "";
}
$annotationsPhp = "{$indent}/**\n";
foreach ($annotationsObject as $annotationType => $annotationName) {
//Remove conditional and output useCaseId upon completion of MQE-588
if ($annotationType == "useCaseId") {
continue;
}
if (!$isMethod) {
$annotationsPhp .= $this->generateClassAnnotations($annotationType, $annotationName);
} else {
$annotationsPhp .= $this->generateMethodAnnotations($annotationType, $annotationName);
}
}
if ($isMethod) {
$annotationsPhp .= $this->generateMethodAnnotations();
}
$annotationsPhp .= "{$indent} */\n";
return $annotationsPhp;
}
/**
* Method which returns formatted method level annotation based on type and name(s).
*
* @param string $annotationType
* @param string|null $annotationName
* @return null|string
*/
private function generateMethodAnnotations($annotationType = null, $annotationName = null)
{
$annotationToAppend = null;
$indent = "\t";
switch ($annotationType) {
case "features":
$features = "";
foreach ($annotationName as $name) {
$features .= sprintf("\"%s\"", $name);
if (next($annotationName)) {
$features .= ", ";
}
}
$annotationToAppend .= sprintf("{$indent} * @Features({%s})\n", $features);
break;
case "stories":
$stories = "";
foreach ($annotationName as $name) {
$stories .= sprintf("\"%s\"", $name);
if (next($annotationName)) {
$stories .= ", ";
}
}
$annotationToAppend .= sprintf("{$indent} * @Stories({%s})\n", $stories);
break;
case "severity":
$annotationToAppend = sprintf("{$indent} * @Severity(level = SeverityLevel::%s)\n", $annotationName[0]);
break;
case null:
$annotationToAppend = sprintf(
"{$indent} * @Parameter(name = \"%s\", value=\"$%s\")\n",
"AcceptanceTester",
"I"
);
$annotationToAppend .= sprintf("{$indent} * @param %s $%s\n", "AcceptanceTester", "I");
$annotationToAppend .= "{$indent} * @return void\n";
$annotationToAppend .= "{$indent} * @throws \Exception\n";
break;
}
return $annotationToAppend;
}
/**
* Method which return formatted class level annotations based on type and name(s).
*
* @param string $annotationType
* @param string $annotationName
* @return null|string
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private function generateClassAnnotations($annotationType, $annotationName)
{
$annotationToAppend = null;
switch ($annotationType) {
case "title":
$annotationToAppend = sprintf(" * @Title(\"%s\")\n", $annotationName[0]);
break;
case "description":
$annotationToAppend = sprintf(" * @Description(\"%s\")\n", $annotationName[0]);
break;
case "testCaseId":
$annotationToAppend = sprintf(" * @TestCaseId(\"%s\")\n", $annotationName[0]);
break;
case "useCaseId":
$annotationToAppend = sprintf(" * @UseCaseId(\"%s\")\n", $annotationName[0]);
break;
case "group":
foreach ($annotationName as $group) {
$annotationToAppend .= sprintf(" * @group %s\n", $group);
}
break;
}
return $annotationToAppend;
}
/**
* Creates a PHP string for the actions contained withing a <test> block.
* Since nearly half of all Codeception methods don't share the same signature I had to setup a massive Case
* statement to handle each unique action. At the bottom of the case statement there is a generic function that can
* construct the PHP string for nearly half of all Codeception actions.
*
* @param array $actionObjects
* @param string $generationScope
* @param string $actor
* @return string
* @throws TestReferenceException
* @throws \Exception
* @SuppressWarnings(PHPMD)
*/
public function generateStepsPhp($actionObjects, $generationScope = TestGenerator::TEST_SCOPE, $actor = "I")
{
//TODO: Refactor Method according to PHPMD warnings, remove @SuppressWarnings accordingly.
$testSteps = '';
$this->actor = $actor;
$this->currentGenerationScope = $generationScope;
foreach ($actionObjects as $actionObject) {
$stepKey = $actionObject->getStepKey();
$customActionAttributes = $actionObject->getCustomActionAttributes();
$attribute = null;
$selector = null;
$selector1 = null;
$selector2 = null;
$input = null;
$parameterArray = null;
$returnVariable = null;
$x = null;
$y = null;
$html = null;
$url = null;
$function = null;
$time = null;
$locale = null;
$username = null;
$password = null;
$width = null;
$height = null;
$requiredAction = null;
$value = null;
$button = null;
$parameter = null;
$dependentSelector = null;
$visible = null;
$command = null;
$arguments = null;
$sortOrder = null;
$storeCode = null;
$format = null;
$assertExpected = null;
$assertActual = null;
$assertMessage = null;
$assertIsStrict = null;
$assertDelta = null;
// Validate action attributes and print notice messages on violation.
$this->validateXmlAttributesMutuallyExclusive($stepKey, $actionObject->getType(), $customActionAttributes);
if (isset($customActionAttributes['command'])) {
$command = $this->addUniquenessFunctionCall($customActionAttributes['command']);
}
if (isset($customActionAttributes['arguments'])) {
$arguments = $this->addUniquenessFunctionCall($customActionAttributes['arguments']);
}
if (isset($customActionAttributes['attribute'])) {
$attribute = $customActionAttributes['attribute'];
}
if (isset($customActionAttributes['sortOrder'])) {
$sortOrder = $customActionAttributes['sortOrder'];
}
if (isset($customActionAttributes['userInput']) && isset($customActionAttributes['url'])) {
$input = $this->addUniquenessFunctionCall($customActionAttributes['userInput']);
$url = $this->addUniquenessFunctionCall($customActionAttributes['url']);
} elseif (isset($customActionAttributes['userInput'])) {
$input = $this->addUniquenessFunctionCall($customActionAttributes['userInput']);
} elseif (isset($customActionAttributes['url'])) {
$input = $this->addUniquenessFunctionCall($customActionAttributes['url']);
$url = $this->addUniquenessFunctionCall($customActionAttributes['url']);
} elseif (isset($customActionAttributes['expectedValue'])) {
//For old Assert backwards Compatibility, remove when deprecating
$assertExpected = $this->addUniquenessFunctionCall($customActionAttributes['expectedValue']);
} elseif (isset($customActionAttributes['regex'])) {
$input = $this->addUniquenessFunctionCall($customActionAttributes['regex']);
}
if (isset($customActionAttributes['date']) && isset($customActionAttributes['format'])) {
$input = $this->addUniquenessFunctionCall($customActionAttributes['date']);
if ($input === "") {
$input = "\"Now\"";
}
$format = $this->addUniquenessFunctionCall($customActionAttributes['format']);
if ($format === "") {
$format = "\"r\"";
}
}
if (isset($customActionAttributes['expected'])) {
$assertExpected = $this->resolveValueByType(
$customActionAttributes['expected'],
isset($customActionAttributes['expectedType']) ? $customActionAttributes['expectedType'] : null
);
}
if (isset($customActionAttributes['actual'])) {
$assertActual = $this->resolveValueByType(
$customActionAttributes['actual'],
isset($customActionAttributes['actualType']) ? $customActionAttributes['actualType'] : null
);
}
if (isset($customActionAttributes['message'])) {
$assertMessage = $this->addUniquenessFunctionCall($customActionAttributes['message']);
}
if (isset($customActionAttributes['delta'])) {
$assertDelta = $this->resolveValueByType($customActionAttributes['delta'], "float");
}
if (isset($customActionAttributes['strict'])) {
$assertIsStrict = $this->resolveValueByType($customActionAttributes['strict'], "bool");
}
if (isset($customActionAttributes['time'])) {
$time = $customActionAttributes['time'];
}
if (isset($customActionAttributes['timeout'])) {
$time = $customActionAttributes['timeout'];
}
if (in_array($actionObject->getType(), ActionObject::COMMAND_ACTION_ATTRIBUTES)) {
$time = $time ?? ActionObject::DEFAULT_COMMAND_WAIT_TIMEOUT;
} else {
$time = $time ?? ActionObject::getDefaultWaitTimeout();
}
if (isset($customActionAttributes['parameterArray']) && $actionObject->getType() != 'pressKey') {
// validate the param array is in the correct format
$this->validateParameterArray($customActionAttributes['parameterArray']);
$parameterArray = "[";
$parameterArray .= $this->addUniquenessToParamArray($customActionAttributes['parameterArray']);
$parameterArray .= "]";
}
if (isset($customActionAttributes['requiredAction'])) {
$requiredAction = $customActionAttributes['requiredAction'];
}
if (isset($customActionAttributes['selectorArray'])) {
$selector = $customActionAttributes['selectorArray'];
} elseif (isset($customActionAttributes['selector'])) {
$selector = $this->addUniquenessFunctionCall($customActionAttributes['selector']);
$selector = $this->resolveLocatorFunctionInAttribute($selector);
}
if (isset($customActionAttributes['selector1']) || isset($customActionAttributes['filterSelector'])) {
$selectorOneValue = $customActionAttributes['selector1'] ?? $customActionAttributes['filterSelector'];
$selector1 = $this->addUniquenessFunctionCall($selectorOneValue);
$selector1 = $this->resolveLocatorFunctionInAttribute($selector1);
}
if (isset($customActionAttributes['selector2']) || isset($customActionAttributes['optionSelector'])) {
$selectorTwoValue = $customActionAttributes['selector2'] ?? $customActionAttributes['optionSelector'];
$selector2 = $this->addUniquenessFunctionCall($selectorTwoValue);
$selector2 = $this->resolveLocatorFunctionInAttribute($selector2);
}
if (isset($customActionAttributes['x'])) {
$x = $customActionAttributes['x'];
}
if (isset($customActionAttributes['y'])) {
$y = $customActionAttributes['y'];
}
if (isset($customActionAttributes['function'])) {
$function = $this->addUniquenessFunctionCall(
$customActionAttributes['function'],
$actionObject->getType() !== "executeInSelenium"
);
if (in_array($actionObject->getType(), ActionObject::FUNCTION_CLOSURE_ACTIONS)) {
// Argument must be a closure function, not a string.
$function = trim($function, '"');
}
// turn $javaVariable => \$javaVariable but not {$mftfVariable}
if ($actionObject->getType() == "executeJS") {
$function = preg_replace('/(?<!{)(\$[A-Za-z._]+)(?![A-z.]*+\$)/', '\\\\$1', $function);
}
}
if (isset($customActionAttributes['html'])) {
$html = $this->addUniquenessFunctionCall($customActionAttributes['html']);
}
if (isset($customActionAttributes['locale'])) {
$locale = $this->wrapWithDoubleQuotes($customActionAttributes['locale']);
}
if (isset($customActionAttributes['username'])) {
$username = $this->wrapWithDoubleQuotes($customActionAttributes['username']);
}
if (isset($customActionAttributes['password'])) {
$password = $this->wrapWithDoubleQuotes($customActionAttributes['password']);
}
if (isset($customActionAttributes['width'])) {
$width = $customActionAttributes['width'];
}
if (isset($customActionAttributes['height'])) {
$height = $customActionAttributes['height'];
}
if (isset($customActionAttributes['value'])) {
$value = $this->wrapWithDoubleQuotes($customActionAttributes['value']);
}
if (isset($customActionAttributes['button'])) {
$button = $this->wrapWithDoubleQuotes($customActionAttributes['button']);
}
if (isset($customActionAttributes['parameter'])) {
$parameter = $this->wrapWithDoubleQuotes($customActionAttributes['parameter']);
}
if (isset($customActionAttributes['dependentSelector'])) {
$dependentSelector = $this->addUniquenessFunctionCall($customActionAttributes['dependentSelector']);
}
if (isset($customActionAttributes['visible'])) {
$visible = $customActionAttributes['visible'];
}
if (isset($customActionAttributes['storeCode'])) {
$storeCode = $customActionAttributes['storeCode'];
}
switch ($actionObject->getType()) {
case "createData":
$entity = $customActionAttributes['entity'];
//TODO refactor entity field override to not be individual actionObjects
$customEntityFields =
$customActionAttributes[ActionObjectExtractor::ACTION_OBJECT_PERSISTENCE_FIELDS] ?? [];
$requiredEntityKeys = [];
foreach ($actionObject->getCustomActionAttributes() as $actionAttribute) {
if (is_array($actionAttribute) && $actionAttribute['nodeName'] == 'requiredEntity') {
//append ActionGroup if provided
$requiredEntityActionGroup = $actionAttribute['actionGroup'] ?? null;
$requiredEntityKeys[] = $actionAttribute['createDataKey'] . $requiredEntityActionGroup;
}
}
// Build array of requiredEntities
$requiredEntityKeysArray = "";
if (!empty($requiredEntityKeys)) {
$requiredEntityKeysArray = '"' . implode('", "', $requiredEntityKeys) . '"';
}
//Determine Scope
$scope = PersistedObjectHandler::TEST_SCOPE;
if ($generationScope == TestGenerator::HOOK_SCOPE) {
$scope = PersistedObjectHandler::HOOK_SCOPE;
} elseif ($generationScope == TestGenerator::SUITE_SCOPE) {
$scope = PersistedObjectHandler::SUITE_SCOPE;
}
$createEntityFunctionCall = "\t\t\${$actor}->createEntity(";
$createEntityFunctionCall .= "\"{$stepKey}\",";
$createEntityFunctionCall .= " \"{$scope}\",";
$createEntityFunctionCall .= " \"{$entity}\",";
$createEntityFunctionCall .= " [{$requiredEntityKeysArray}],";
if (count($customEntityFields) > 1) {
$createEntityFunctionCall .= " \${$stepKey}Fields";
} else {
$createEntityFunctionCall .= " []";
}
if ($storeCode !== null) {
$createEntityFunctionCall .= ", \"{$storeCode}\"";
}
$createEntityFunctionCall .= ");";
$testSteps .= $createEntityFunctionCall;
break;
case "deleteData":
if (isset($customActionAttributes['createDataKey'])) {
$key = $this->resolveStepKeyReferences(
$customActionAttributes['createDataKey'],
$actionObject->getActionOrigin(),
true
);
$actionGroup = $actionObject->getCustomActionAttributes()['actionGroup'] ?? null;
$key .= $actionGroup;
//Determine Scope
$scope = PersistedObjectHandler::TEST_SCOPE;
if ($generationScope == TestGenerator::HOOK_SCOPE) {
$scope = PersistedObjectHandler::HOOK_SCOPE;
} elseif ($generationScope == TestGenerator::SUITE_SCOPE) {
$scope = PersistedObjectHandler::SUITE_SCOPE;
}
$deleteEntityFunctionCall = "\t\t\${$actor}->deleteEntity(";
$deleteEntityFunctionCall .= "\"{$key}\",";
$deleteEntityFunctionCall .= " \"{$scope}\"";
$deleteEntityFunctionCall .= ");";
$testSteps .= $deleteEntityFunctionCall;
} else {
$url = $this->resolveAllRuntimeReferences([$url])[0];
$url = $this->resolveTestVariable([$url], null)[0];
$output = sprintf(
"\t\t$%s->deleteEntityByUrl(%s);",
$actor,
$url
);
$testSteps .= $output;
}
break;
case "updateData":
$key = $this->resolveStepKeyReferences(
$customActionAttributes['createDataKey'],
$actionObject->getActionOrigin(),
true
);
$updateEntity = $customActionAttributes['entity'];
$actionGroup = $actionObject->getCustomActionAttributes()['actionGroup'] ?? null;
$key .= $actionGroup;
// Build array of requiredEntities
$requiredEntityKeys = [];
foreach ($actionObject->getCustomActionAttributes() as $actionAttribute) {
if (is_array($actionAttribute) && $actionAttribute['nodeName'] == 'requiredEntity') {
//append ActionGroup if provided
$requiredEntityActionGroup = $actionAttribute['actionGroup'] ?? null;
$requiredEntityKeys[] = $actionAttribute['createDataKey'] . $requiredEntityActionGroup;
}
}
$requiredEntityKeysArray = "";
if (!empty($requiredEntityKeys)) {
$requiredEntityKeysArray = '"' . implode('", "', $requiredEntityKeys) . '"';
}
$scope = PersistedObjectHandler::TEST_SCOPE;
if ($generationScope == TestGenerator::HOOK_SCOPE) {
$scope = PersistedObjectHandler::HOOK_SCOPE;
} elseif ($generationScope == TestGenerator::SUITE_SCOPE) {
$scope = PersistedObjectHandler::SUITE_SCOPE;
}
$updateEntityFunctionCall = "\t\t\${$actor}->updateEntity(";
$updateEntityFunctionCall .= "\"{$key}\",";
$updateEntityFunctionCall .= " \"{$scope}\",";
$updateEntityFunctionCall .= " \"{$updateEntity}\",";
$updateEntityFunctionCall .= "[{$requiredEntityKeysArray}]";
if ($storeCode !== null) {
$updateEntityFunctionCall .= ", \"{$storeCode}\"";
}
$updateEntityFunctionCall .= ");";
$testSteps .= $updateEntityFunctionCall;
break;
case "getData":
$entity = $customActionAttributes['entity'];
$index = null;
if (isset($customActionAttributes['index'])) {
$index = (int)$customActionAttributes['index'];
}
// Build array of requiredEntities
$requiredEntityKeys = [];
foreach ($actionObject->getCustomActionAttributes() as $actionAttribute) {
if (is_array($actionAttribute) && $actionAttribute['nodeName'] == 'requiredEntity') {
$requiredEntityActionGroup = $actionAttribute['actionGroup'] ?? null;
$requiredEntityKeys[] = $actionAttribute['createDataKey'] . $requiredEntityActionGroup;
}
}
$requiredEntityKeysArray = "";
if (!empty($requiredEntityKeys)) {
$requiredEntityKeysArray = '"' . implode('", "', $requiredEntityKeys) . '"';
}
//Determine Scope
$scope = PersistedObjectHandler::TEST_SCOPE;
if ($generationScope == TestGenerator::HOOK_SCOPE) {
$scope = PersistedObjectHandler::HOOK_SCOPE;
} elseif ($generationScope == TestGenerator::SUITE_SCOPE) {
$scope = PersistedObjectHandler::SUITE_SCOPE;
}
//Create Function
$getEntityFunctionCall = "\t\t\${$actor}->getEntity(";
$getEntityFunctionCall .= "\"{$stepKey}\",";
$getEntityFunctionCall .= " \"{$scope}\",";
$getEntityFunctionCall .= " \"{$entity}\",";
$getEntityFunctionCall .= " [{$requiredEntityKeysArray}],";
if ($storeCode !== null) {
$getEntityFunctionCall .= " \"{$storeCode}\"";
} else {
$getEntityFunctionCall .= " null";
}
if ($index !== null) {
$getEntityFunctionCall .= ", {$index}";
}
$getEntityFunctionCall .= ");";
$testSteps .= $getEntityFunctionCall;
break;
case "assertArrayIsSorted":
$testSteps .= $this->wrapFunctionCall(
$actor,
$actionObject,
$parameterArray,
$this->wrapWithDoubleQuotes($sortOrder)
);
break;
case "seeCurrentUrlEquals":
case "seeCurrentUrlMatches":
case "dontSeeCurrentUrlEquals":
case "dontSeeCurrentUrlMatches":
case "seeInPopup":
case "saveSessionSnapshot":
case "seeInTitle":
case "seeInCurrentUrl":
case "switchToIFrame":
case "switchToWindow":
case "typeInPopup":
case "dontSee":
case "see":
$testSteps .= $this->wrapFunctionCall($actor, $actionObject, $input, $selector);
break;
case "switchToNextTab":
case "switchToPreviousTab":
$testSteps .= $this->wrapFunctionCall($actor, $actionObject, $input);
break;
case "clickWithLeftButton":
case "clickWithRightButton":
case "moveMouseOver":
case "scrollTo":
if (!$selector) {
$selector = 'null';
}
$testSteps .= $this->wrapFunctionCall($actor, $actionObject, $selector, $x, $y);
break;
case "dontSeeCookie":
case "resetCookie":
case "seeCookie":
$testSteps .= $this->wrapFunctionCall(
$actor,
$actionObject,
$input,
$parameterArray
);
break;
case "grabCookie":
$testSteps .= $this->wrapFunctionCallWithReturnValue(
$stepKey,
$actor,
$actionObject,
$input,
$parameterArray
);
break;
case "dontSeeElement":
case "dontSeeElementInDOM":
case "dontSeeInFormFields":
case "seeElement":
case "seeElementInDOM":
case "seeInFormFields":
$testSteps .= $this->wrapFunctionCall(
$actor,
$actionObject,
$selector,
$parameterArray
);
break;
case "pressKey":
$parameterArray = $customActionAttributes['parameterArray'] ?? null;
if ($parameterArray) {
$parameterArray = $this->processPressKey($parameterArray);
}
$testSteps .= $this->wrapFunctionCall(
$actor,
$actionObject,
$selector,
$input,
$parameterArray
);
break;
case "selectOption":
case "unselectOption":
$testSteps .= $this->wrapFunctionCall(
$actor,
$actionObject,
$selector,
$input,
$parameterArray
);
break;
case "submitForm":
$testSteps .= $this->wrapFunctionCall(
$actor,
$actionObject,
$selector,
$parameterArray,
$button
);
break;
case "dragAndDrop":
$testSteps .= $this->wrapFunctionCall(