This repository was archived by the owner on May 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathUtil.php
565 lines (497 loc) · 17.6 KB
/
Util.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
<?php
/**
* PHP Unit test suite for Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
*
* @category EcomDev
* @package EcomDev_PHPUnit
* @copyright Copyright (c) 2013 EcomDev BV (http://www.ecomdev.org)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @author Ivan Chepurnyi <[email protected]>
*/
use EcomDev_PHPUnit_Helper as TestHelper;
class EcomDev_PHPUnit_Test_Case_Util
{
const XML_PATH_DEFAULT_FIXTURE_MODEL = 'phpunit/suite/fixture/model';
const XML_PATH_DEFAULT_EXPECTATION_MODEL = 'phpunit/suite/expectation/model';
const XML_PATH_DEFAULT_YAML_LOADER_MODEL = 'phpunit/suite/yaml/model';
/**
* List of replaced registry keys for current test case run
*
* @var array
*/
protected static $replacedRegistry = array();
/**
* Original store before first setCurrentStore() call
*
* @var int|string|Mage_Core_Model_Store|null
*/
protected static $originalStore = null;
/**
* Current expectation model alias
*
* @var string
*/
protected static $expectationModelAlias = null;
/**
* Current fixture model alias
*
* @var string
*/
protected static $fixtureModelAlias = null;
/**
* Current yaml loader model alias
*
* @var string
*/
protected static $yamlLoaderModelAlias = null;
/**
* Module name by class name
*
* @var string[]
*/
protected static $moduleNameByClassName = array();
/**
* Returns app for test case, created for type hinting
* in the test case code
*
* @return EcomDev_PHPUnit_Model_App
*/
public static function app()
{
return Mage::app();
}
/**
* Returns yaml loader model instance
*
* @param string|null $testCaseClass
* @return EcomDev_PHPUnit_Model_Yaml_Loader
*/
public static function getYamlLoader($testCaseClass = null)
{
if ($testCaseClass !== null) {
self::$yamlLoaderModelAlias = self::getLoadableClassAlias(
$testCaseClass,
'yaml',
self::XML_PATH_DEFAULT_YAML_LOADER_MODEL
);
} elseif (self::$yamlLoaderModelAlias === null) {
self::$yamlLoaderModelAlias = self::getLoadableClassAlias(
get_called_class(), // Just fallback to current test util
'yaml',
self::XML_PATH_DEFAULT_YAML_LOADER_MODEL
);
}
return Mage::getSingleton(self::$yamlLoaderModelAlias);
}
/**
* Loads YAML file based on loaders logic
*
* @param string $className class name for looking fixture files
* @param string $type type of YAML data (fixtures,expectations,providers)
* @param string $name the file name for loading
* @return string|boolean
*/
public static function getYamlFilePath($className, $type, $name)
{
return self::getYamlLoader($className)->resolveFilePath($className, $type, $name);
}
/**
* Retrieves fixture model singleton
*
* @param string|null $testCaseClass
* @return EcomDev_PHPUnit_Model_Fixture
* @throws RuntimeException
*/
public static function getFixture($testCaseClass = null)
{
if ($testCaseClass !== null) {
self::$fixtureModelAlias = self::getLoadableClassAlias(
$testCaseClass,
'fixture',
self::XML_PATH_DEFAULT_FIXTURE_MODEL
);
} elseif (self::$fixtureModelAlias === null) {
self::$fixtureModelAlias = self::getLoadableClassAlias(
get_called_class(), // Just fallback to current test util
'fixture',
self::XML_PATH_DEFAULT_FIXTURE_MODEL
);
}
$fixture = Mage::getSingleton(self::$fixtureModelAlias);
if (!$fixture instanceof EcomDev_PHPUnit_Model_Fixture_Interface) {
throw new RuntimeException('Fixture model should implement EcomDev_PHPUnit_Model_Fixture_Interface interface');
}
$storage = Mage::registry(EcomDev_PHPUnit_Model_App::REGISTRY_PATH_SHARED_STORAGE);
if (!$storage instanceof Varien_Object) {
throw new RuntimeException('Fixture storage object was not initialized during test application setup');
}
$fixture->setStorage(
Mage::registry(EcomDev_PHPUnit_Model_App::REGISTRY_PATH_SHARED_STORAGE)
);
return $fixture;
}
/**
* Returns expectation model singleton
*
* @param string|null $testCaseClass
* @return EcomDev_PHPUnit_Model_Expectation
*/
public static function getExpectation($testCaseClass = null)
{
if ($testCaseClass !== null) {
self::$expectationModelAlias = self::getLoadableClassAlias(
$testCaseClass,
'expectation',
self::XML_PATH_DEFAULT_EXPECTATION_MODEL
);
} elseif (self::$expectationModelAlias === null) {
self::$expectationModelAlias = self::getLoadableClassAlias(
get_called_class(), // Just fallback to current test util
'expectation',
self::XML_PATH_DEFAULT_EXPECTATION_MODEL
);
}
return Mage::getSingleton(self::$expectationModelAlias);
}
/**
* Shortcut for expectation data object retrieval
* Can be called with arguments array or in usual method
*
* @param PHPUnit_Framework_TestCase $testCase
* @param string|array $firstArgument
* @optional @param mixed $arg1
* @optional @param mixed $arg2
* @return Varien_Object
*/
public static function expected(PHPUnit_Framework_TestCase $testCase, $firstArgument = null)
{
if (!self::getExpectation(get_class($testCase))->isLoaded()) {
self::getExpectation()->loadByTestCase($testCase);
self::getExpectation()->apply();
}
if (!is_array($firstArgument)) {
$arguments = func_get_args();
array_shift($arguments); // Remove test case from arguments
} else {
$arguments = $firstArgument;
}
$pathFormat = null;
if ($arguments) {
$pathFormat = array_shift($arguments);
}
return self::getExpectation()
->getDataObject($pathFormat, $arguments);
}
/**
* Loads data provider based on test class name and test name
*
* @param string $className
* @param string $testName
*
* @return array
* @throws RuntimeException
*/
public static function dataProvider($className, $testName)
{
$dataProviderFiles = array();
if ($annotations = self::getAnnotationByNameFromClass($className, 'dataProviderFile', array('class', 'method'), $testName)) {
foreach ($annotations as $name) {
$filePath = self::getYamlLoader($className)
->resolveFilePath($className, EcomDev_PHPUnit_Model_Yaml_Loader::TYPE_PROVIDER, $name);
if (!$filePath) {
throw new RuntimeException(sprintf('Unable to load data provider for path %s', $name));
}
$dataProviderFiles[] = $filePath;
}
} else {
$filePath = self::getYamlLoader($className)
->resolveFilePath($className, EcomDev_PHPUnit_Model_Yaml_Loader::TYPE_PROVIDER, $testName);
if (!$filePath) {
throw new RuntimeException('Unable to load data provider for the current test');
}
$dataProviderFiles[] = $filePath;
}
$providerData = array();
foreach ($dataProviderFiles as $file) {
$providerData = array_merge_recursive($providerData, self::getYamlLoader()->load($file));
}
return $providerData;
}
/**
* Retrieves loadable class alias from annotation or configuration node
* E.g. class alias for fixture model can be specified via @fixtureModel annotation
*
* @param string $className
* @param string $type
* @param string $configPath
* @return string
*/
public static function getLoadableClassAlias($className, $type, $configPath)
{
$annotationValue = self::getAnnotationByNameFromClass(
$className,
$type .'Model'
);
if (current($annotationValue)) {
$classAlias = current($annotationValue);
} else {
$classAlias = (string) self::app()->getConfig()->getNode($configPath);
}
return $classAlias;
}
/**
* Retrieves the module name for current test case
*
* @param PHPUnit_Framework_TestCase $testCase
* @return string
* @throws RuntimeException if module name was not found for the passed class name
*/
public static function getModuleName(PHPUnit_Framework_TestCase $testCase)
{
return self::getModuleNameByClassName($testCase);
}
/**
* Retrieves annotation by its name from different sources (class, method) based on meta information
*
* @param string $className
* @param string $name annotation name
* @param array|string $sources
* @param string $testName test method name
* @return array
*/
public static function getAnnotationByNameFromClass($className, $name, $sources = 'class', $testName = '')
{
if (is_string($sources)) {
$sources = array($sources);
}
$allAnnotations = PHPUnit_Util_Test::parseTestMethodAnnotations(
$className, $testName
);
$annotation = array();
// Walkthrough sources for annotation retrieval
foreach ($sources as $source) {
if (isset($allAnnotations[$source][$name])) {
$annotation = array_merge(
$allAnnotations[$source][$name],
$annotation
);
}
}
return $annotation;
}
/**
* Retrieves module name from call stack objects
*
* @return string
* @throws RuntimeException if assertion is called in not from EcomDev_PHPUnit_Test_Case
*/
public static function getModuleNameFromCallStack()
{
$backTrace = debug_backtrace(true);
foreach ($backTrace as $call) {
if (isset($call['object']) && $call['object'] instanceof PHPUnit_Framework_TestCase) {
return self::getModuleName($call['object']);
}
}
throw new RuntimeException('Unable to retrieve module name from call stack, because assertion is not called from PHPUnit_Framework_Test_Case based class method');
}
/**
* Set current store scope for test
*
* @param int|string|Mage_Core_Model_Store $store
* @return void
*/
public static function setCurrentStore($store)
{
if (!self::$originalStore) {
self::$originalStore = self::app()->getStore();
}
self::app()->setCurrentStore(
self::app()->getStore($store)
);
}
/**
* Set associated module name for a class name,
* Usually used for making possible dependency injection in the test cases
*
*
* @param string $className
* @param string $moduleName
* @return array
*/
public static function setModuleNameForClassName($className, $moduleName)
{
self::$moduleNameByClassName[$className] = $moduleName;
}
/**
* Returns module name for a particular object
*
* @param string|object $className
* @throws RuntimeException if module name was not found for the passed class name
* @return string
*/
public static function getModuleNameByClassName($className)
{
if (is_object($className)) {
$className = get_class($className);
}
if (!isset(self::$moduleNameByClassName[$className])) {
// Try to find the module name by class name
$moduleName = false;
foreach (Mage::getConfig()->getNode('modules')->children() as $module) {
if (strpos($className, $module->getName() . '_') === 0) {
$moduleName = $module->getName();
break;
}
}
if (!$moduleName) {
throw new RuntimeException('Cannot to find the module name for class name: ' . $className);
}
self::setModuleNameForClassName($className, $moduleName);
}
return self::$moduleNameByClassName[$className];
}
/**
* Replaces Magento resource by mock object
*
* @param string $type
* @param string $classAlias
* @param PHPUnit_Framework_MockObject_MockObject|PHPUnit_Framework_MockObject_MockBuilder $mock
* @return void
*
* @throws InvalidArgumentException
*/
public static function replaceByMock($type, $classAlias, $mock)
{
if ($mock instanceof EcomDev_PHPUnit_Mock_Proxy) {
$mock = $mock->getMockInstance();
} elseif ($mock instanceof PHPUnit_Framework_MockObject_MockBuilder) {
$mock = $mock->getMock();
} elseif (!$mock instanceof PHPUnit_Framework_MockObject_MockObject) {
throw PHPUnit_Util_InvalidArgumentHelper::factory(
1, 'PHPUnit_Framework_MockObject_MockObject'
);
}
// Remove addition of /data suffix if version is more than 1.6.x
if (version_compare(Mage::getVersion(), '1.6.0.0', '<') && $type == 'helper' && strpos($classAlias, '/') === false) {
$classAlias .= '/data';
}
if (in_array($type, array('model', 'resource_model'))) {
self::app()->getConfig()->replaceInstanceCreation($type, $classAlias, $mock);
$type = str_replace('model', 'singleton', $type);
} elseif ($type == 'block') {
self::app()->getLayout()->replaceBlockCreation($classAlias, $mock);
}
if (in_array($type, array('singleton', 'resource_singleton', 'helper'))) {
$registryPath = '_' . $type . '/' . $classAlias;
self::replaceRegistry($registryPath, $mock);
}
}
/**
* Replaces value in Magento system registry
*
* @param string $key
* @param mixed $value
* @return void
*/
public static function replaceRegistry($key, $value)
{
$oldValue = Mage::registry($key);
self::app()->replaceRegistry($key, $value);
self::$replacedRegistry[$key] = $oldValue;
}
/**
* Returns class name by grouped class alias
*
* @param string $type block/model/helper/resource_model
* @param string $classAlias
* @return string
*/
public static function getGroupedClassName($type, $classAlias)
{
if ($type === 'resource_model') {
return self::app()->getConfig()->getResourceModelClassName($classAlias);
} elseif ($type === 'helper') {
return self::app()->getConfig()->getHelperClassName($classAlias);
}
return self::app()->getConfig()->getGroupedClassName($type, $classAlias);
}
/**
* Retrieve mock builder for grouped class alias
*
* @param PHPUnit_Framework_TestCase $testCase
* @param string $type block|model|helper
* @param string $classAlias
* @return EcomDev_PHPUnit_Mock_Proxy
*/
public static function getGroupedClassMockBuilder(PHPUnit_Framework_TestCase $testCase, $type, $classAlias)
{
$className = self::getGroupedClassName($type, $classAlias);
return new EcomDev_PHPUnit_Mock_Proxy($testCase, $className);
}
/**
* Called for each test case
*
*/
public static function setUp()
{
self::app()->resetDispatchedEvents();
}
/**
* Called for each test case
*
*/
public static function tearDown()
{
if (self::$originalStore) {
self::app()->setCurrentStore(self::$originalStore);
self::$originalStore = null;
}
self::app()->getConfig()->flushReplaceInstanceCreation();
self::app()->getLayout()->flushReplaceBlockCreation();
foreach (self::$replacedRegistry as $registryPath => $originalValue) {
self::app()->replaceRegistry($registryPath, $originalValue);
}
}
/**
* Implementation of __call method functionality that can be used from a test case
*
* @param string $method
* @param array $args
*
* @throws ErrorException
* @return bool
*/
public static function call($method, $args)
{
if (TestHelper::has($method)) {
return TestHelper::invokeArgs($method, $args);
}
if (version_compare(PHP_VERSION, '5.4', '>=')) {
$backTraceCalls = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3);
} else {
// We cannot limit number of arguments on php before 5.4, php rises an exception :(
$backTraceCalls = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
}
$previousCall = $backTraceCalls[2];
throw new ErrorException(
sprintf(
'Call to undefined function %s%s%s()',
$previousCall['class'],
$previousCall['type'],
$previousCall['function']
),
0,
E_USER_ERROR,
$previousCall['file'],
$previousCall['line']
);
}
}