-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathTestDependencyCheck.php
453 lines (406 loc) · 16.3 KB
/
TestDependencyCheck.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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\StaticCheck;
use Magento\FunctionalTestingFramework\Config\MftfApplicationConfig;
use Magento\FunctionalTestingFramework\DataGenerator\Handlers\DataObjectHandler;
use Magento\FunctionalTestingFramework\Exceptions\TestReferenceException;
use Magento\FunctionalTestingFramework\Exceptions\XmlException;
use Magento\FunctionalTestingFramework\Page\Handlers\PageObjectHandler;
use Magento\FunctionalTestingFramework\Page\Handlers\SectionObjectHandler;
use Magento\FunctionalTestingFramework\Test\Handlers\ActionGroupObjectHandler;
use Magento\FunctionalTestingFramework\Test\Handlers\TestObjectHandler;
use Magento\FunctionalTestingFramework\Test\Objects\ActionObject;
use Magento\FunctionalTestingFramework\Util\ModuleResolver;
use Magento\FunctionalTestingFramework\Util\TestGenerator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Finder\Finder;
use Exception;
/**
* Class TestDependencyCheck
* @package Magento\FunctionalTestingFramework\StaticCheck
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class TestDependencyCheck implements StaticCheckInterface
{
const EXTENDS_REGEX_PATTERN = '/extends=["\']([^\'"]*)/';
const ACTIONGROUP_REGEX_PATTERN = '/ref=["\']([^\'"]*)/';
const ACTIONGROUP_ARGUMENT_REGEX_PATTERN = '/<argument[^\/>]*name="([^"\']*)/';
const ERROR_LOG_FILENAME = 'mftf-dependency-checks';
const ERROR_LOG_MESSAGE = 'MFTF File Dependency Check';
/**
* Array of FullModuleName => [dependencies]
* @var array
*/
private $allDependencies;
/**
* Array of FullModuleName => [dependencies], including flattened dependency tree
* @var array
*/
private $flattenedDependencies;
/**
* Array of FullModuleName => PathToModule
* @var array
*/
private $moduleNameToPath;
/**
* Array of FullModuleName => ComposerModuleName
* @var array
*/
private $moduleNameToComposerName;
/**
* Transactional Array to keep track of what dependencies have already been extracted.
* @var array
*/
private $alreadyExtractedDependencies;
/**
* Array containing all errors found after running the execute() function.
* @var array
*/
private $errors = [];
/**
* String representing the output summary found after running the execute() function.
* @var string
*/
private $output;
/**
* Array containing all entities after resolving references.
* @var array
*/
private $allEntities = [];
/**
* Checks test dependencies, determined by references in tests versus the dependencies listed in the Magento module
*
* @param InputInterface $input
* @return string
* @throws Exception;
*/
public function execute(InputInterface $input)
{
MftfApplicationConfig::create(
true,
MftfApplicationConfig::UNIT_TEST_PHASE,
false,
MftfApplicationConfig::LEVEL_NONE,
true
);
ModuleResolver::getInstance()->getModulesPath();
if (!class_exists('\Magento\Framework\Component\ComponentRegistrar')) {
return "TEST DEPENDENCY CHECK ABORTED: MFTF must be attached or pointing to Magento codebase.";
}
$registrar = new \Magento\Framework\Component\ComponentRegistrar();
$this->moduleNameToPath = $registrar->getPaths(\Magento\Framework\Component\ComponentRegistrar::MODULE);
$this->moduleNameToComposerName = $this->buildModuleNameToComposerName($this->moduleNameToPath);
$this->flattenedDependencies = $this->buildComposerDependencyList();
$allModules = ModuleResolver::getInstance()->getModulesPath();
$filePaths = [
DIRECTORY_SEPARATOR . 'Test' . DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR . 'ActionGroup' . DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR . 'Data' . DIRECTORY_SEPARATOR,
];
// These files can contain references to other modules.
$testXmlFiles = StaticCheckHelper::buildFileList($allModules, $filePaths[0]);
$actionGroupXmlFiles = StaticCheckHelper::buildFileList($allModules, $filePaths[1]);
$dataXmlFiles= StaticCheckHelper::buildFileList($allModules, $filePaths[2]);
$this->errors = [];
$this->errors += $this->findErrorsInFileSet($testXmlFiles);
$this->errors += $this->findErrorsInFileSet($actionGroupXmlFiles);
$this->errors += $this->findErrorsInFileSet($dataXmlFiles);
// hold on to the output and print any errors to a file
$this->output = StaticCheckHelper::printErrorsToFile(
$this->errors,
self::ERROR_LOG_FILENAME,
self::ERROR_LOG_MESSAGE
);
}
/**
* Return array containing all errors found after running the execute() function.
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* Return string of a short human readable result of the check. For example: "No Dependency errors found."
* @return string
*/
public function getOutput()
{
return $this->output;
}
/**
* Finds all reference errors in given set of files
* @param Finder $files
* @return array
* @throws TestReferenceException
* @throws XmlException
*/
private function findErrorsInFileSet($files)
{
$testErrors = [];
foreach ($files as $filePath) {
$modulePath = dirname(dirname(dirname(dirname($filePath))));
$moduleFullName = array_search($modulePath, $this->moduleNameToPath) ?? null;
// Not a module, is either dev/tests/acceptance or loose folder with test materials
if ($moduleFullName == null) {
continue;
}
$contents = file_get_contents($filePath);
preg_match_all(ActionObject::ACTION_ATTRIBUTE_VARIABLE_REGEX_PATTERN, $contents, $braceReferences);
preg_match_all(self::ACTIONGROUP_REGEX_PATTERN, $contents, $actionGroupReferences);
preg_match_all(self::EXTENDS_REGEX_PATTERN, $contents, $extendReferences);
// Remove Duplicates
$braceReferences[0] = array_unique($braceReferences[0]);
$actionGroupReferences[1] = array_unique($actionGroupReferences[1]);
$braceReferences[1] = array_unique($braceReferences[1]);
$braceReferences[2] = array_filter(array_unique($braceReferences[2]));
// resolve data entity references
$this->resolveDataEntityReferences($braceReferences[0], $contents);
//resolve entity references
$this->resolveParametrizedReferences($braceReferences[2], $contents);
// Check actionGroup references
$this->resolveEntityReferences($actionGroupReferences[1]);
// Check extended objects
$this->resolveEntityReferences($extendReferences[1]);
// Find violating references and set error output
$violatingReferences = $this->findViolatingReferences($moduleFullName);
$testErrors = $this->setErrorOutput($violatingReferences, $filePath);
}
return $testErrors;
}
/**
* Drill down into params in {{ref.params('string', $data.key$, entity.reference)}}
* and resolve references.
*
* @param array $braceReferences
* @param string $contents
* @return void
* @throws XmlException
*/
private function resolveParametrizedReferences($braceReferences, $contents)
{
foreach ($braceReferences as $parameterizedReference) {
preg_match(
ActionObject::ACTION_ATTRIBUTE_VARIABLE_REGEX_PARAMETER,
$parameterizedReference,
$arguments
);
$splitArguments = explode(',', ltrim(rtrim($arguments[0], ")"), "("));
foreach ($splitArguments as $argument) {
// Do nothing for 'string' or $persisted.data$
if (preg_match(ActionObject::STRING_PARAMETER_REGEX, $argument)) {
continue;
} elseif (preg_match(TestGenerator::PERSISTED_OBJECT_NOTATION_REGEX, $argument)) {
continue;
}
// trim `data.field` to `data`
preg_match('/([^.]+)/', $argument, $entityName);
// Double check that {{data.field}} isn't an argument for an ActionGroup
$entity = $this->findEntity($entityName[1]);
preg_match_all(self::ACTIONGROUP_ARGUMENT_REGEX_PATTERN, $contents, $possibleArgument);
if (array_search($entityName[1], $possibleArgument[1]) !== false) {
continue;
}
if ($entity !== null) {
$this->allEntities[$entity->getName()] = $entity;
}
}
}
}
/**
* Check `data` entities in {{data.field}} or {{data.field('param')}} and resolve references
*
* @param array $braceReferences
* @param string $contents
* @return void
* @throws XmlException
*/
private function resolveDataEntityReferences($braceReferences, $contents)
{
foreach ($braceReferences as $reference) {
// trim `{{data.field}}` to `data`
preg_match('/{{([^.]+)/', $reference, $entityName);
// Double check that {{data.field}} isn't an argument for an ActionGroup
$entity = $this->findEntity($entityName[1]);
preg_match_all(self::ACTIONGROUP_ARGUMENT_REGEX_PATTERN, $contents, $possibleArgument);
if (array_search($entityName[1], $possibleArgument[1]) !== false) {
continue;
}
if ($entity !== null) {
$this->allEntities[$entity->getName()] = $entity;
}
}
}
/**
* Resolve entity references
*
* @param array $references
* @return void
* @throws XmlException
*/
private function resolveEntityReferences($references)
{
foreach ($references as $reference) {
$entity = $this->findEntity($reference);
if ($entity !== null) {
$this->allEntities[$entity->getName()] = $entity;
}
}
}
/**
* Find violating references
*
* @param string $moduleName
* @return array
*/
private function findViolatingReferences($moduleName)
{
// Find Violations
$violatingReferences = [];
$currentModule = $this->moduleNameToComposerName[$moduleName];
$modulesReferencedInTest = $this->getModuleDependenciesFromReferences($this->allEntities);
$moduleDependencies = $this->flattenedDependencies[$moduleName];
foreach ($modulesReferencedInTest as $entityName => $files) {
$valid = false;
foreach ($files as $module) {
if (array_key_exists($module, $moduleDependencies) || $module == $currentModule) {
$valid = true;
break;
}
}
if (!$valid) {
$violatingReferences[$entityName] = $files;
}
}
return $violatingReferences;
}
/**
* Builds and returns error output for violating references
*
* @param array $violatingReferences
* @param string $path
* @return mixed
*/
private function setErrorOutput($violatingReferences, $path)
{
$testErrors = [];
if (!empty($violatingReferences)) {
// Build error output
$errorOutput = "\nFile \"{$path->getRealPath()}\"";
$errorOutput .= "\ncontains entity references that violate dependency constraints:\n\t\t";
foreach ($violatingReferences as $entityName => $files) {
$errorOutput .= "\n\t {$entityName} from module(s): " . implode(", ", $files);
}
$testErrors[$path->getRealPath()][] = $errorOutput;
}
return $testErrors;
}
/**
* Builds and returns array of FullModuleNae => composer name
* @param array $array
* @return array
*/
private function buildModuleNameToComposerName($array)
{
$returnList = [];
foreach ($array as $moduleName => $path) {
$composerData = json_decode(file_get_contents($path . DIRECTORY_SEPARATOR . "composer.json"));
$returnList[$moduleName] = $composerData->name;
}
return $returnList;
}
/**
* Builds and returns flattened dependency list based on composer dependencies
* @return array
*/
private function buildComposerDependencyList()
{
$flattenedDependencies = [];
foreach ($this->moduleNameToPath as $moduleName => $pathToModule) {
$composerData = json_decode(file_get_contents($pathToModule . DIRECTORY_SEPARATOR . "composer.json"), true);
$this->allDependencies[$moduleName] = $composerData['require'];
}
foreach ($this->allDependencies as $moduleName => $dependencies) {
$this->alreadyExtractedDependencies = [];
$flattenedDependencies[$moduleName] = $this->extractSubDependencies($moduleName);
}
return $flattenedDependencies;
}
/**
* Recursive function to fetch dependencies of given dependency, and its child dependencies
* @param string $subDependencyName
* @return array
*/
private function extractSubDependencies($subDependencyName)
{
$flattenedArray = [];
if (array_search($subDependencyName, $this->alreadyExtractedDependencies) !== false) {
return $flattenedArray;
}
if (isset($this->allDependencies[$subDependencyName])) {
$subDependencyArray = $this->allDependencies[$subDependencyName];
$flattenedArray = array_merge($flattenedArray, $this->allDependencies[$subDependencyName]);
// Keep track of dependencies that have already been used, prevents circular dependency problems
$this->alreadyExtractedDependencies[] = $subDependencyName;
foreach ($subDependencyArray as $composerDependencyName => $version) {
$subDependencyFullName = array_search($composerDependencyName, $this->moduleNameToComposerName);
$flattenedArray = array_merge(
$flattenedArray,
$this->extractSubDependencies($subDependencyFullName)
);
}
}
return $flattenedArray;
}
/**
* Finds unique array ofcomposer dependencies of given testObjects
* @param array $array
* @return array
*/
private function getModuleDependenciesFromReferences($array)
{
$filenames = [];
foreach ($array as $item) {
// Should it append ALL filenames, including merges?
$allFiles = explode(",", $item->getFilename());
foreach ($allFiles as $file) {
$modulePath = dirname(dirname(dirname(dirname($file))));
$fullModuleName = array_search($modulePath, $this->moduleNameToPath);
$composerModuleName = $this->moduleNameToComposerName[$fullModuleName];
$filenames[$item->getName()][] = $composerModuleName;
}
}
return $filenames;
}
/**
* Attempts to find any MFTF entity by its name. Returns null if none are found.
* @param string $name
* @return mixed
* @throws XmlException
*/
private function findEntity($name)
{
if ($name == '_ENV' || $name == '_CREDS') {
return null;
}
if (DataObjectHandler::getInstance()->getObject($name)) {
return DataObjectHandler::getInstance()->getObject($name);
} elseif (PageObjectHandler::getInstance()->getObject($name)) {
return PageObjectHandler::getInstance()->getObject($name);
} elseif (SectionObjectHandler::getInstance()->getObject($name)) {
return SectionObjectHandler::getInstance()->getObject($name);
}
try {
return ActionGroupObjectHandler::getInstance()->getObject($name);
} catch (TestReferenceException $e) {
}
try {
return TestObjectHandler::getInstance()->getObject($name);
} catch (TestReferenceException $e) {
}
return null;
}
}