AssetControllerTest.php 19.4 KB
Newer Older
1 2
<?php

3 4 5
namespace yiiunit\framework\console\controllers;

use yii\helpers\StringHelper;
6 7
use yiiunit\TestCase;
use yii\console\controllers\AssetController;
8
use Yii;
9 10

/**
11
 * Unit test for [[\yii\console\controllers\AssetController]].
12
 * @see AssetController
13 14
 *
 * @group console
15 16 17
 */
class AssetControllerTest extends TestCase
{
18 19 20 21 22 23 24 25 26 27 28 29
    /**
     * @var string path for the test files.
     */
    protected $testFilePath = '';
    /**
     * @var string test assets path.
     */
    protected $testAssetsBasePath = '';

    public function setUp()
    {
        $this->mockApplication();
Carsten Brandt committed
30
        $this->testFilePath = Yii::getAlias('@yiiunit/runtime') . DIRECTORY_SEPARATOR . str_replace('\\', '_', get_class($this)) . uniqid();
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
        $this->createDir($this->testFilePath);
        $this->testAssetsBasePath = $this->testFilePath . DIRECTORY_SEPARATOR . 'assets';
        $this->createDir($this->testAssetsBasePath);
    }

    public function tearDown()
    {
        $this->removeDir($this->testFilePath);
    }

    /**
     * Creates directory.
     * @param string $dirName directory full name.
     */
    protected function createDir($dirName)
    {
        if (!file_exists($dirName)) {
            mkdir($dirName, 0777, true);
        }
    }

    /**
     * Removes directory.
     * @param string $dirName directory full name
     */
    protected function removeDir($dirName)
    {
        if (!empty($dirName) && file_exists($dirName)) {
            exec("rm -rf {$dirName}");
        }
    }

    /**
     * Creates test asset controller instance.
65
     * @return AssetControllerMock
66 67 68 69
     */
    protected function createAssetController()
    {
        $module = $this->getMock('yii\\base\\Module', ['fake'], ['console']);
70
        $assetController = new AssetControllerMock('asset', $module);
71 72 73 74 75 76 77 78 79
        $assetController->interactive = false;
        $assetController->jsCompressor = 'cp {from} {to}';
        $assetController->cssCompressor = 'cp {from} {to}';

        return $assetController;
    }

    /**
     * Emulates running of the asset controller action.
Alexander Makarov committed
80
     * @param  string $actionID id of action to be run.
81 82 83
     * @param  array  $args     action arguments.
     * @return string command output.
     */
Alexander Makarov committed
84
    protected function runAssetControllerAction($actionID, array $args = [])
85 86
    {
        $controller = $this->createAssetController();
Alexander Makarov committed
87
        $controller->run($actionID, $args);
88
        return $controller->flushStdOutBuffer();
89 90 91 92 93 94 95 96 97
    }

    /**
     * Creates test compress config.
     * @param  array[] $bundles asset bundles config.
     * @return array   config array.
     */
    protected function createCompressConfig(array $bundles)
    {
98 99 100
        static $classNumber = 0;
        $classNumber++;
        $className = $this->declareAssetBundleClass(['class' => 'AssetBundleAll' . $classNumber]);
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
        $baseUrl = '/test';
        $config = [
            'bundles' => $bundles,
            'targets' => [
                $className => [
                    'basePath' => $this->testAssetsBasePath,
                    'baseUrl' => $baseUrl,
                    'js' => 'all.js',
                    'css' => 'all.css',
                ],
            ],
            'assetManager' => [
                'basePath' => $this->testAssetsBasePath,
                'baseUrl' => '',
            ],
        ];

        return $config;
    }

    /**
     * Creates test compress config file.
     * @param  string     $fileName output file name.
     * @param  array[]    $bundles  asset bundles config.
     * @throws \Exception on failure.
     */
    protected function createCompressConfigFile($fileName, array $bundles)
    {
        $content = '<?php return ' . var_export($this->createCompressConfig($bundles), true) . ';';
        if (file_put_contents($fileName, $content) <= 0) {
            throw new \Exception("Unable to create file '{$fileName}'!");
        }
    }

    /**
     * Creates test asset file.
     * @param  string     $fileRelativeName file name relative to [[testFilePath]]
     * @param  string     $content          file content
     * @throws \Exception on failure.
     */
    protected function createAssetSourceFile($fileRelativeName, $content)
    {
        $fileFullName = $this->testFilePath . DIRECTORY_SEPARATOR . $fileRelativeName;
        $this->createDir(dirname($fileFullName));
        if (file_put_contents($fileFullName, $content) <= 0) {
            throw new \Exception("Unable to create file '{$fileFullName}'!");
        }
    }

    /**
     * Creates a list of asset source files.
     * @param array $files assert source files in format: file/relative/name => fileContent
     */
    protected function createAssetSourceFiles(array $files)
    {
        foreach ($files as $name => $content) {
            $this->createAssetSourceFile($name, $content);
        }
    }

    /**
     * Invokes the asset controller method even if it is protected.
     * @param  string $methodName name of the method to be invoked.
     * @param  array  $args       method arguments.
     * @return mixed  method invoke result.
     */
    protected function invokeAssetControllerMethod($methodName, array $args = [])
    {
        $controller = $this->createAssetController();
        $controllerClassReflection = new \ReflectionClass(get_class($controller));
        $methodReflection = $controllerClassReflection->getMethod($methodName);
        $methodReflection->setAccessible(true);
        $result = $methodReflection->invokeArgs($controller, $args);
        $methodReflection->setAccessible(false);

        return $result;
    }

    /**
     * Composes asset bundle class source code.
     * @param  array  $config asset bundle config.
     * @return string class source code.
     */
    protected function composeAssetBundleClassSource(array &$config)
    {
        $config = array_merge(
            [
                'namespace' => StringHelper::dirname(get_class($this)),
                'class' => 'AppAsset',
                'basePath' => $this->testFilePath,
                'baseUrl' => '',
                'css' => [],
                'js' => [],
                'depends' => [],
            ],
            $config
        );
        foreach ($config as $name => $value) {
            if (is_array($value)) {
                $config[$name] = var_export($value, true);
            }
        }

        $source = <<<EOL
205 206 207 208 209 210
namespace {$config['namespace']};

use yii\web\AssetBundle;

class {$config['class']} extends AssetBundle
{
211 212 213 214 215
    public \$basePath = '{$config['basePath']}';
    public \$baseUrl = '{$config['baseUrl']}';
    public \$css = {$config['css']};
    public \$js = {$config['js']};
    public \$depends = {$config['depends']};
216 217
}
EOL;
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

        return $source;
    }

    /**
     * Declares asset bundle class according to given configuration.
     * @param  array  $config asset bundle config.
     * @return string new class full name.
     */
    protected function declareAssetBundleClass(array $config)
    {
        $sourceCode = $this->composeAssetBundleClassSource($config);
        eval($sourceCode);

        return $config['namespace'] . '\\' . $config['class'];
    }

    // Tests :

    public function testActionTemplate()
    {
        $configFileName = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php';
        $this->runAssetControllerAction('template', [$configFileName]);
        $this->assertTrue(file_exists($configFileName), 'Unable to create config file template!');
242 243
        $config = require($configFileName);
        $this->assertTrue(is_array($config), 'Invalid config created!');
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
    }

    public function testActionCompress()
    {
        // Given :
        $cssFiles = [
            'css/test_body.css' => 'body {
                padding-top: 20px;
                padding-bottom: 60px;
            }',
            'css/test_footer.css' => '.footer {
                margin: 20px;
                display: block;
            }',
        ];
        $this->createAssetSourceFiles($cssFiles);

        $jsFiles = [
            'js/test_alert.js' => "function test() {
                alert('Test message');
            }",
            'js/test_sum_ab.js' => "function sumAB(a, b) {
                return a + b;
            }",
        ];
        $this->createAssetSourceFiles($jsFiles);
        $assetBundleClassName = $this->declareAssetBundleClass([
            'css' => array_keys($cssFiles),
            'js' => array_keys($jsFiles),
        ]);

        $bundles = [
            $assetBundleClassName
        ];
        $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php';

280
        $configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config2.php';
281 282 283 284 285 286 287
        $this->createCompressConfigFile($configFile, $bundles);

        // When :
        $this->runAssetControllerAction('compress', [$configFile, $bundleFile]);

        // Then :
        $this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
288 289 290 291 292 293 294 295 296
        $compressedBundleConfig = require($bundleFile);
        $this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!');
        $this->assertCount(2, $compressedBundleConfig, 'Output bundle config contains wrong bundle count!');

        $this->assertArrayHasKey($assetBundleClassName, $compressedBundleConfig, 'Source bundle is lost!');
        $compressedAssetBundleConfig = $compressedBundleConfig[$assetBundleClassName];
        $this->assertEmpty($compressedAssetBundleConfig['css'], 'Compressed bundle css is not empty!');
        $this->assertEmpty($compressedAssetBundleConfig['js'], 'Compressed bundle js is not empty!');
        $this->assertNotEmpty($compressedAssetBundleConfig['depends'], 'Compressed bundle dependency is invalid!');
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

        $compressedCssFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.css';
        $this->assertTrue(file_exists($compressedCssFileName), 'Unable to compress CSS files!');
        $compressedJsFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.js';
        $this->assertTrue(file_exists($compressedJsFileName), 'Unable to compress JS files!');

        $compressedCssFileContent = file_get_contents($compressedCssFileName);
        foreach ($cssFiles as $name => $content) {
            $this->assertContains($content, $compressedCssFileContent, "Source of '{$name}' is missing in combined file!");
        }
        $compressedJsFileContent = file_get_contents($compressedJsFileName);
        foreach ($jsFiles as $name => $content) {
            $this->assertContains($content, $compressedJsFileContent, "Source of '{$name}' is missing in combined file!");
        }
    }

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
    /**
     * @depends testActionCompress
     *
     * @see https://github.com/yiisoft/yii2/issues/5194
     */
    public function testCompressExternalAsset()
    {
        // Given :
        $externalAssetConfig = [
            'class' => 'ExternalAsset',
            'sourcePath' => null,
            'basePath' => null,
            'js' => [
                '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
            ],
            'css' => [
                '//ajax.googleapis.com/css/libs/jquery/2.1.1/jquery.ui.min.css'
            ],
        ];
        $externalAssetBundleClassName = $this->declareAssetBundleClass($externalAssetConfig);

        $cssFiles = [
            'css/test.css' => 'body {
                padding-top: 20px;
                padding-bottom: 60px;
            }',
        ];
        $this->createAssetSourceFiles($cssFiles);
        $jsFiles = [
            'js/test.js' => "function test() {
                alert('Test message');
            }",
        ];
        $this->createAssetSourceFiles($jsFiles);
        $regularAssetBundleClassName = $this->declareAssetBundleClass([
            'class' => 'RegularAsset',
            'css' => array_keys($cssFiles),
            'js' => array_keys($jsFiles),
            'depends' => [
                $externalAssetBundleClassName
            ],
        ]);
        $bundles = [
            $regularAssetBundleClassName
        ];
        $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php';

        $configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php';
        $this->createCompressConfigFile($configFile, $bundles);

        // When :
        $this->runAssetControllerAction('compress', [$configFile, $bundleFile]);

        // Then :
        $this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
        $compressedBundleConfig = require($bundleFile);
        $this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!');
        $this->assertArrayHasKey($externalAssetBundleClassName, $compressedBundleConfig, 'External bundle is lost!');

        $compressedExternalAssetConfig = $compressedBundleConfig[$externalAssetBundleClassName];
        $this->assertEquals($externalAssetConfig['js'], $compressedExternalAssetConfig['js'], 'External bundle js is lost!');
        $this->assertEquals($externalAssetConfig['css'], $compressedExternalAssetConfig['css'], 'External bundle css is lost!');

        $compressedRegularAssetConfig = $compressedBundleConfig[$regularAssetBundleClassName];
        $this->assertContains($externalAssetBundleClassName, $compressedRegularAssetConfig['depends'], 'Dependency on external bundle is lost!');
    }

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
    /**
     * Data provider for [[testAdjustCssUrl()]].
     * @return array test data.
     */
    public function adjustCssUrlDataProvider()
    {
        return [
            [
                '.published-same-dir-class {background-image: url(published_same_dir.png);}',
                '/test/base/path/assets/input',
                '/test/base/path/assets/output',
                '.published-same-dir-class {background-image: url(../input/published_same_dir.png);}',
            ],
            [
                '.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}',
                '/test/base/path/assets/input',
                '/test/base/path/assets/output',
                '.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}',
            ],
            [
                '.static-same-dir-class {background-image: url(\'static_same_dir.png\');}',
                '/test/base/path/css',
                '/test/base/path/assets/output',
                '.static-same-dir-class {background-image: url(\'../../css/static_same_dir.png\');}',
            ],
            [
                '.static-relative-dir-class {background-image: url("../img/static_relative_dir.png");}',
                '/test/base/path/css',
                '/test/base/path/assets/output',
                '.static-relative-dir-class {background-image: url("../../img/static_relative_dir.png");}',
            ],
            [
                '.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}',
                '/test/base/path/assets/input',
                '/test/base/path/assets/output',
                '.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}',
            ],
            [
                '.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}',
                '/test/base/path/assets/input',
                '/test/base/path/assets/output',
                '.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}',
            ],
            [
                "@font-face {
                src: url('../fonts/glyphicons-halflings-regular.eot');
                src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype');
                }",
                '/test/base/path/assets/input/css',
                '/test/base/path/assets/output',
                "@font-face {
                src: url('../input/fonts/glyphicons-halflings-regular.eot');
                src: url('../input/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype');
                }",
            ],
435 436 437 438 439 440 441 442 443 444 445 446
            [
                "@font-face {
                src: url('../fonts/glyphicons-halflings-regular.eot');
                src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype');
                }",
                '/test/base/path/assets/input/css',
                '/test/base/path/assets',
                "@font-face {
                src: url('input/fonts/glyphicons-halflings-regular.eot');
                src: url('input/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype');
                }",
            ],
447 448 449 450 451 452 453 454 455 456
            [
                "@font-face {
                src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT==) format('truetype');
                }",
                '/test/base/path/assets/input/css',
                '/test/base/path/assets/output',
                "@font-face {
                src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT==) format('truetype');
                }",
            ],
457 458 459 460 461 462
            [
                '.published-same-dir-class {background-image: url(published_same_dir.png);}',
                'C:\test\base\path\assets\input',
                'C:\test\base\path\assets\output',
                '.published-same-dir-class {background-image: url(../input/published_same_dir.png);}',
            ],
463 464 465 466 467 468
            [
                '.static-root-relative-class {background-image: url(\'/images/static_root_relative.png\');}',
                '/test/base/path/css',
                '/test/base/path/assets/output',
                '.static-root-relative-class {background-image: url(\'/images/static_root_relative.png\');}',
            ],
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        ];
    }

    /**
     * @dataProvider adjustCssUrlDataProvider
     *
     * @param $cssContent
     * @param $inputFilePath
     * @param $outputFilePath
     * @param $expectedCssContent
     */
    public function testAdjustCssUrl($cssContent, $inputFilePath, $outputFilePath, $expectedCssContent)
    {
        $adjustedCssContent = $this->invokeAssetControllerMethod('adjustCssUrl', [$cssContent, $inputFilePath, $outputFilePath]);

        $this->assertEquals($expectedCssContent, $adjustedCssContent, 'Unable to adjust CSS correctly!');
    }
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

    /**
     * Data provider for [[testFindRealPath()]]
     * @return array test data
     */
    public function findRealPathDataProvider()
    {
        return [
            [
                '/linux/absolute/path',
                '/linux/absolute/path',
            ],
            [
                '/linux/up/../path',
                '/linux/path',
            ],
            [
                '/linux/twice/up/../../path',
                '/linux/path',
            ],
            [
                '/linux/../mix/up/../path',
                '/mix/path',
            ],
            [
                'C:\\windows\\absolute\\path',
                'C:\\windows\\absolute\\path',
            ],
            [
                'C:\\windows\\up\\..\\path',
                'C:\\windows\\path',
            ],
        ];
    }

    /**
     * @dataProvider findRealPathDataProvider
     *
     * @param string $sourcePath
     * @param string $expectedRealPath
     */
    public function testFindRealPath($sourcePath, $expectedRealPath)
    {
        $expectedRealPath = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $expectedRealPath);
        $realPath = $this->invokeAssetControllerMethod('findRealPath', [$sourcePath]);
        $this->assertEquals($expectedRealPath, $realPath);
    }
533
}
534 535 536 537 538 539 540 541

/**
 * Mock class for [[\yii\console\controllers\AssetController]]
 */
class AssetControllerMock extends AssetController
{
    use StdOutBufferControllerTrait;
}