-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathActionObject.php
609 lines (546 loc) · 22.3 KB
/
ActionObject.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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\Test\Objects;
use Magento\FunctionalTestingFramework\DataGenerator\Handlers\DataObjectHandler;
use Magento\FunctionalTestingFramework\DataGenerator\Objects\EntityDataObject;
use Magento\FunctionalTestingFramework\ObjectManager\ObjectHandlerInterface;
use Magento\FunctionalTestingFramework\Page\Objects\PageObject;
use Magento\FunctionalTestingFramework\Page\Objects\SectionObject;
use Magento\FunctionalTestingFramework\Page\Handlers\PageObjectHandler;
use Magento\FunctionalTestingFramework\Page\Handlers\SectionObjectHandler;
use Magento\FunctionalTestingFramework\Exceptions\TestReferenceException;
/**
* Class ActionObject
*/
class ActionObject
{
const __ENV = "_ENV";
const DATA_ENABLED_ATTRIBUTES = ["userInput", "parameterArray", "expected", "actual"];
const SELECTOR_ENABLED_ATTRIBUTES = ['selector', 'dependentSelector', "selector1", "selector2", "function"];
const OLD_ASSERTION_ATTRIBUTES = ["expected", "expectedType", "actual", "actualType"];
const ASSERTION_ATTRIBUTES = ["expectedResult" => "expected", "actualResult" => "actual"];
const ASSERTION_TYPE_ATTRIBUTE = "type";
const ASSERTION_VALUE_ATTRIBUTE = "value";
const EXTERNAL_URL_AREA_INVALID_ACTIONS = ['amOnPage'];
const MERGE_ACTION_ORDER_AFTER = 'after';
const MERGE_ACTION_ORDER_BEFORE = 'before';
const ACTION_ATTRIBUTE_URL = 'url';
const ACTION_ATTRIBUTE_SELECTOR = 'selector';
const ACTION_ATTRIBUTE_VARIABLE_REGEX_PARAMETER = '/\(.+\)/';
const ACTION_ATTRIBUTE_VARIABLE_REGEX_PATTERN = '/{{[\w]+\.[\w\[\]]+}}/';
const ACTION_ATTRIBUTE_VARIABLE_REGEX_PATTERN_WITH_PARAMS= '/{{[\w]+\.[\w]+\(.+\)}}/';
/**
* The unique identifier for the action
*
* @var string $stepKey
*/
private $stepKey;
/**
* The type of action (e.g. fillField, createData, etc)
*
* @var string $type
*/
private $type;
/**
* THe attributes which describe the action (e.g. selector, userInput)
*
* @var array $actionAttributes
*/
private $actionAttributes = [];
/**
* The name of the action to reference when merging this action into existing test steps
*
* @var null|string $linkedAction
*/
private $linkedAction;
/**
* A value used to describe position during merge
*
* @var int $orderOffset
*/
private $orderOffset = 0;
/**
* An array which contains variable resolution of all specified parameters in an action
*
* @var array $resolvedCustomAttributes
*/
private $resolvedCustomAttributes = [];
/**
* A string which represents a needed timeout whenever the action is referenced
*
* @var string timeout
*/
private $timeout;
/**
* ActionObject constructor.
*
* @param string $stepKey
* @param string $type
* @param array $actionAttributes
* @param string|null $linkedAction
* @param string $order
*/
public function __construct(
$stepKey,
$type,
$actionAttributes,
$linkedAction = null,
$order = ActionObject::MERGE_ACTION_ORDER_BEFORE
) {
$this->stepKey = $stepKey;
$this->type = $type;
$this->actionAttributes = $actionAttributes;
$this->linkedAction = $linkedAction;
if ($order == ActionObject::MERGE_ACTION_ORDER_AFTER) {
$this->orderOffset = 1;
}
}
/**
* This function returns the string property stepKey.
*
* @return string
*/
public function getStepKey()
{
return $this->stepKey;
}
/**
* This function returns the string property type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* This function returns an array of action attributes mapped by key. For example
* the tag <seeNumberOfElements selector="value1" expected="value2" stepKey=""/> has 3 attributes,
* only 2 of which are specific to the 'seeNumberOfElements' tag. As a result this function would
* return the array would return [selector => value1, expected => value2]
* The returned array is also the merged result of the resolved and normal actions, giving
* priority to the resolved actions (resolved selector instead of section.element, etc).
*
* @return array
*/
public function getCustomActionAttributes()
{
return array_merge($this->actionAttributes, $this->resolvedCustomAttributes);
}
/**
* This function returns the string property linkedAction, describing a step to reference for a merge.
*
* @return string
*/
public function getLinkedAction()
{
return $this->linkedAction;
}
/**
* This function returns the int property orderOffset, describing before or after for a merge.
*
* @return int
*/
public function getOrderOffset()
{
return $this->orderOffset;
}
/**
* This function returns the int property timeout, this can be set as a result of the use of a section element
* requiring a wait.
*
* @return int
*/
public function getTimeout()
{
return $this->timeout;
}
/**
* Set the timeout value.
*
* @param int $timeout
* @return void
*/
public function setTimeout($timeout)
{
$this->timeout = $timeout;
}
/**
* Populate the resolved custom attributes array with lookup values for the following attributes:
* selector
* url
* userInput
*
* @return void
*/
public function resolveReferences()
{
if (empty($this->resolvedCustomAttributes)) {
$this->resolveSelectorReferenceAndTimeout();
$this->resolveUrlReference();
$this->resolveDataInputReferences();
}
}
/**
* Flattens expectedResult/actualResults/array nested elements, if necessary.
* e.g. expectedResults[] -> ["expectedType" => "string", "expected" => "value"]
* Warns user if they are using old Assertion syntax.
*
* @return void
*/
public function trimAssertionAttributes()
{
$actionAttributeKeys = array_keys($this->actionAttributes);
// Flatten AssertSorted "array" element to parameterArray
if (isset($this->actionAttributes["array"])) {
$this->resolvedCustomAttributes['parameterArray'] = $this->actionAttributes['array']['value'];
}
/** MQE-683 DEPRECATE OLD METHOD HERE
* Checks if action has any of the old, single line attributes
* Throws a warning and returns, assuming old syntax is used.
*/
$oldAttributes = array_intersect($actionAttributeKeys, ActionObject::OLD_ASSERTION_ATTRIBUTES);
if (!empty($oldAttributes)) {
// @codingStandardsIgnoreStart
if ($GLOBALS['GENERATE_TESTS'] ?? false == true) {
echo("WARNING: Use of one line Assertion actions will be deprecated in MFTF 3.0.0, please use nested syntax (Action: {$this->type} StepKey: {$this->stepKey})" . PHP_EOL);
}
// @codingStandardsIgnoreEnd
return;
}
$relevantKeys = array_keys(ActionObject::ASSERTION_ATTRIBUTES);
$relevantAssertionAttributes = array_intersect($actionAttributeKeys, $relevantKeys);
if (empty($relevantAssertionAttributes)) {
return;
}
$this->validateAssertionSchema($relevantAssertionAttributes);
// Flatten nested Elements's type and value into key=>value entries
foreach ($this->actionAttributes as $key => $subAttributes) {
if (in_array($key, $relevantKeys)) {
$prefix = ActionObject::ASSERTION_ATTRIBUTES[$key];
$this->resolvedCustomAttributes[$prefix . ucfirst(ActionObject::ASSERTION_TYPE_ATTRIBUTE)] =
$subAttributes[ActionObject::ASSERTION_TYPE_ATTRIBUTE];
$this->resolvedCustomAttributes[$prefix] =
$subAttributes[ActionObject::ASSERTION_VALUE_ATTRIBUTE];
unset($this->actionAttributes[$key]);
}
}
}
/**
* Validates that the given assertion attributes have valid schema according to nested assertion syntax.
* @param array $attributes
* @return void
* @throws TestReferenceException
*/
private function validateAssertionSchema($attributes)
{
/** MQE-683 DEPRECATE OLD METHOD HERE
* Unnecessary validation, only needed for backwards compatibility
*/
$singleChildTypes = ['assertEmpty', 'assertFalse', 'assertFileExists', 'assertFileNotExists',
'assertIsEmpty', 'assertNotEmpty', 'assertNotNull', 'assertNull', 'assertTrue',
'assertElementContainsAttribute'];
if (!in_array($this->type, $singleChildTypes)) {
if (!in_array('expectedResult', $attributes)
|| !in_array('actualResult', $attributes)) {
// @codingStandardsIgnoreStart
throw new TestReferenceException("{$this->type} must have both an expectedResult and actualResult defined (stepKey: {$this->stepKey})");
// @codingStandardsIgnoreEnd
}
}
}
/**
* Look up the selector for SomeSectionName.ElementName and set it as the selector attribute in the
* resolved custom attributes. Also set the timeout value.
* e.g. {{SomeSectionName.ElementName}} becomes #login-button
*
* @return void
*/
private function resolveSelectorReferenceAndTimeout()
{
$actionAttributeKeys = array_keys($this->actionAttributes);
$relevantSelectorAttributes = array_intersect($actionAttributeKeys, ActionObject::SELECTOR_ENABLED_ATTRIBUTES);
if (empty($relevantSelectorAttributes)) {
return;
}
foreach ($relevantSelectorAttributes as $selectorAttribute) {
$selector = $this->actionAttributes[$selectorAttribute];
$replacement = $this->findAndReplaceReferences(SectionObjectHandler::getInstance(), $selector);
if ($replacement) {
$this->resolvedCustomAttributes[$selectorAttribute] = $replacement;
}
}
}
/**
* Look up the url for SomePageName and set it, with MAGENTO_BASE_URL prepended, as the url attribute in the
* resolved custom attributes.
* e.g. {{SomePageName}} becomes http://localhost:76543/some/url
*
* @return void
*/
private function resolveUrlReference()
{
if (!array_key_exists(ActionObject::ACTION_ATTRIBUTE_URL, $this->actionAttributes)) {
return;
}
$url = $this->actionAttributes[ActionObject::ACTION_ATTRIBUTE_URL];
$replacement = $this->findAndReplaceReferences(PageObjectHandler::getInstance(), $url);
if ($replacement) {
$this->resolvedCustomAttributes[ActionObject::ACTION_ATTRIBUTE_URL] = $replacement;
}
}
/**
* Look up the value for EntityDataObjectName.Key and set it as the corresponding attribute in the resolved custom
* attributes.
* e.g. {{CustomerEntityFoo.FirstName}} becomes Jerry
*
* @return void
*/
private function resolveDataInputReferences()
{
$actionAttributeKeys = array_keys($this->actionAttributes);
$relevantDataAttributes = array_intersect($actionAttributeKeys, ActionObject::DATA_ENABLED_ATTRIBUTES);
if (empty($relevantDataAttributes)) {
return;
}
foreach ($relevantDataAttributes as $dataAttribute) {
$varInput = $this->actionAttributes[$dataAttribute];
$replacement = $this->findAndReplaceReferences(DataObjectHandler::getInstance(), $varInput);
if ($replacement != null) {
$this->resolvedCustomAttributes[$dataAttribute] = $replacement;
}
}
}
/**
* Return an array containing the name (before the period) and key (after the period) in a {{reference.foo}}.
* Also truncates variables inside parenthesis.
*
* @param string $reference
* @return string[] The name and key that is referenced.
*/
private function stripAndSplitReference($reference)
{
$strippedReference = str_replace('}}', '', str_replace('{{', '', $reference));
$strippedReference = preg_replace(
ActionObject::ACTION_ATTRIBUTE_VARIABLE_REGEX_PARAMETER,
'',
$strippedReference
);
return explode('.', $strippedReference);
}
/**
* Returns an array containing all parameters found inside () block of test input. Expected delimiter is ', '.
* Returns null if no parameters were found.
*
* @param string $reference
* @return array|null
*/
private function stripAndReturnParameters($reference)
{
// 'string', or 'string,!@#$%^&*()_+, '
$literalParametersRegex = "/'[^']+'/";
$postCleanupDelimiter = "::::";
preg_match(ActionObject::ACTION_ATTRIBUTE_VARIABLE_REGEX_PARAMETER, $reference, $matches);
if (!empty($matches)) {
$strippedReference = ltrim(rtrim($matches[0], ")"), "(");
// Pull out all 'string' references, as they can contain 'string with , comma in it'
preg_match_all($literalParametersRegex, $strippedReference, $literalReferences);
$strippedReference = preg_replace($literalParametersRegex, '&&stringReference&&', $strippedReference);
// Sanitize 'string, data.field,$persisted.field$' => 'string::::data.field::::$persisted.field$'
$strippedReference = preg_replace('/,/', ', ', $strippedReference);
$strippedReference = str_replace(',', $postCleanupDelimiter, $strippedReference);
$strippedReference = str_replace(' ', '', $strippedReference);
// Replace string references into string, needed to keep sequence
foreach ($literalReferences[0] as $key => $value) {
$strippedReference = preg_replace('/&&stringReference&&/', $value, $strippedReference, 1);
}
return explode($postCleanupDelimiter, $strippedReference);
}
return null;
}
/**
* Return a string based on a reference to a page, section, or data field (e.g. {{foo.ref}} resolves to 'data')
*
* @param ObjectHandlerInterface $objectHandler
* @param string $inputString
* @return string | null
* @throws \Exception
*/
private function findAndReplaceReferences($objectHandler, $inputString)
{
//look for parameter area, if so use different regex
$regex = $this->resolveRegexPatternForReference($inputString);
preg_match_all($regex, $inputString, $matches);
$outputString = $inputString;
foreach ($matches[0] as $match) {
$replacement = null;
$parameterized = false;
list($objName) = $this->stripAndSplitReference($match);
$obj = $objectHandler->getObject($objName);
// Leave {{_ENV.VARIABLE}} references to be replaced in TestGenerator with getenv("VARIABLE")
if ($objName === ActionObject::__ENV) {
continue;
}
// specify behavior depending on field
switch (get_class($obj)) {
case PageObject::class:
$this->validateUrlAreaAgainstActionType($obj);
$replacement = $obj->getUrl();
$parameterized = $obj->isParameterized();
break;
case SectionObject::class:
list(,$objField) = $this->stripAndSplitReference($match);
if ($obj->getElement($objField) == null) {
throw new TestReferenceException("Could not resolve entity reference " . $inputString);
}
$parameterized = $obj->getElement($objField)->isParameterized();
$replacement = $obj->getElement($objField)->getPrioritizedSelector();
$this->setTimeout($obj->getElement($objField)->getTimeout());
break;
case EntityDataObject::class:
$replacement = $this->resolveEntityDataObjectReference($obj, $match);
break;
}
if ($replacement == null) {
if (get_class($objectHandler) != DataObjectHandler::class) {
return $this->findAndReplaceReferences(DataObjectHandler::getInstance(), $outputString);
} else {
throw new TestReferenceException("Could not resolve entity reference " . $inputString);
}
}
$replacement = $this->resolveParameterization($parameterized, $replacement, $match, $obj);
$outputString = str_replace($match, $replacement, $outputString);
}
return $outputString;
}
/**
* Validates the page objects area 'external' against a list of known incompatible types
*
* @param PageObject $obj
* @return void
* @throws TestReferenceException
*/
private function validateUrlAreaAgainstActionType($obj)
{
if ($obj->getArea() == 'external' &&
in_array($this->getType(), self::EXTERNAL_URL_AREA_INVALID_ACTIONS)) {
throw new TestReferenceException(
"Page of type 'external' is not compatible with action type '{$this->getType()}'"
);
}
}
/**
* Determines whether the given $inputString has (params), and returns the appropriate regex for use in matching.
* @param string $inputString
* @return string
*/
private function resolveRegexPatternForReference($inputString)
{
if (preg_match(ActionObject::ACTION_ATTRIBUTE_VARIABLE_REGEX_PATTERN_WITH_PARAMS, $inputString) === 1) {
return ActionObject::ACTION_ATTRIBUTE_VARIABLE_REGEX_PATTERN_WITH_PARAMS;
} else {
return ActionObject::ACTION_ATTRIBUTE_VARIABLE_REGEX_PATTERN;
}
}
/**
* Gets the object's dataByName with given $match, differentiating behavior between <array> and <data> nodes.
* @param string $obj
* @param string $match
* @return string
*/
private function resolveEntityDataObjectReference($obj, $match)
{
list(,$objField) = $this->stripAndSplitReference($match);
if (strpos($objField, '[') == true) {
// Access <array>...</array>
$parts = explode('[', $objField);
$name = $parts[0];
$index = str_replace(']', '', $parts[1]);
return $obj->getDataByName($name, EntityDataObject::CEST_UNIQUE_NOTATION)[$index];
} else {
// Access <data></data>
return $obj->getDataByName($objField, EntityDataObject::CEST_UNIQUE_NOTATION);
}
}
/**
* Resolves $replacement parameterization with given conditional.
* @param boolean $isParameterized
* @param string $replacement
* @param string $match
* @param object $object
* @return string
*/
private function resolveParameterization($isParameterized, $replacement, $match, $object)
{
if ($isParameterized) {
$parameterList = $this->stripAndReturnParameters($match);
$resolvedReplacement = $this->matchParameterReferences($replacement, $parameterList);
} else {
$resolvedReplacement = $replacement;
}
if (get_class($object) == PageObject::class && $object->getArea() == PageObject::ADMIN_AREA) {
$resolvedReplacement = "/{{_ENV.MAGENTO_BACKEND_NAME}}/" . $resolvedReplacement;
}
return $resolvedReplacement;
}
/**
* Finds all {{var}} occurrences in reference, and replaces them in sequence with parameters list given.
* Parameter list given is also resolved, attempting to match {{data.field}} references.
*
* @param string $reference
* @param array $parameters
* @return string
* @throws \Exception
*/
private function matchParameterReferences($reference, $parameters)
{
preg_match_all('/{{[\w.]+}}/', $reference, $varMatches);
$varMatches[0] = array_unique($varMatches[0]);
if (count($varMatches[0]) > count($parameters)) {
if (is_array($parameters)) {
$parametersGiven = implode(",", $parameters);
} elseif ($parameters == null) {
$parametersGiven = "NONE";
} else {
$parametersGiven = $parameters;
}
throw new TestReferenceException(
"Parameter Resolution Failed: Not enough parameters given for reference " .
$reference . ". Parameters Given: " . $parametersGiven
);
} elseif (count($varMatches[0]) < count($parameters)) {
throw new TestReferenceException(
"Parameter Resolution Failed: Too many parameters given for reference " .
$reference . ". Parameters Given: " . implode(", ", $parameters)
);
}
//Attempt to Resolve {{data}} references to actual output. Trim parameter for whitespace before processing it.
//If regex matched it means that it's either a 'StringLiteral' or $key.data$/$$key.data$$ reference.
//Elseif regex match for {$data}
//Else assume it's a normal {{data.key}} reference and recurse through findAndReplace
$resolvedParameters = [];
foreach ($parameters as $parameter) {
$parameter = trim($parameter);
preg_match_all("/[$'][\w\D]+[$']/", $parameter, $stringOrPersistedMatch);
preg_match_all('/{\$[a-z][a-zA-Z\d]+}/', $parameter, $variableMatch);
if (!empty($stringOrPersistedMatch[0])) {
$resolvedParameters[] = ltrim(rtrim($parameter, "'"), "'");
} elseif (!empty($variableMatch[0])) {
$resolvedParameters[] = $parameter;
} else {
$resolvedParameters[] = $this->findAndReplaceReferences(
DataObjectHandler::getInstance(),
'{{' . $parameter . '}}'
);
}
}
$resolveIndex = 0;
foreach ($varMatches[0] as $var) {
$reference = str_replace($var, $resolvedParameters[$resolveIndex++], $reference);
}
return $reference;
}
}