AssetControllerTest.php 10.8 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 18 19 20 21
 */
class AssetControllerTest extends TestCase
{
	/**
	 * @var string path for the test files.
	 */
	protected $testFilePath = '';
22 23 24 25
	/**
	 * @var string test assets path.
	 */
	protected $testAssetsBasePath = '';
26 27 28

	public function setUp()
	{
Qiang Xue committed
29
		$this->mockApplication();
30 31
		$this->testFilePath = Yii::getAlias('@yiiunit/runtime') . DIRECTORY_SEPARATOR . get_class($this);
		$this->createDir($this->testFilePath);
32 33
		$this->testAssetsBasePath = $this->testFilePath . DIRECTORY_SEPARATOR . 'assets';
		$this->createDir($this->testAssetsBasePath);
34 35 36 37 38 39 40 41 42
	}

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

	/**
	 * Creates directory.
43
	 * @param string $dirName directory full name.
44 45 46 47 48 49 50 51 52 53
	 */
	protected function createDir($dirName)
	{
		if (!file_exists($dirName)) {
			mkdir($dirName, 0777, true);
		}
	}

	/**
	 * Removes directory.
54
	 * @param string $dirName directory full name
55 56 57 58 59 60 61 62 63 64 65 66 67 68
	 */
	protected function removeDir($dirName)
	{
		if (!empty($dirName) && file_exists($dirName)) {
			exec("rm -rf {$dirName}");
		}
	}

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

	/**
	 * Emulates running of the asset controller action.
	 * @param string $actionId id of action to be run.
	 * @param array $args action arguments.
	 * @return string command output.
	 */
Alexander Makarov committed
83
	protected function runAssetControllerAction($actionId, array $args = [])
84 85 86 87
	{
		$controller = $this->createAssetController();
		ob_start();
		ob_implicit_flush(false);
Qiang Xue committed
88
		$controller->run($actionId, $args);
89 90 91
		return ob_get_clean();
	}

92 93
	/**
	 * Creates test compress config.
94
	 * @param array[] $bundles asset bundles config.
95 96
	 * @return array config array.
	 */
97
	protected function createCompressConfig(array $bundles)
98
	{
99
		$className = $this->declareAssetBundleClass(['class' => 'AssetBundleAll']);
100
		$baseUrl = '/test';
Alexander Makarov committed
101
		$config = [
102
			'bundles' => $bundles,
Alexander Makarov committed
103
			'targets' => [
104
				$className => [
105
					'basePath' => $this->testAssetsBasePath,
106
					'baseUrl' => $baseUrl,
107 108
					'js' => 'all.js',
					'css' => 'all.css',
Alexander Makarov committed
109 110 111
				],
			],
			'assetManager' => [
112
				'basePath' => $this->testAssetsBasePath,
113
				'baseUrl' => '',
Alexander Makarov committed
114 115
			],
		];
116 117 118 119 120 121
		return $config;
	}

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

133 134 135 136
	/**
	 * Creates test asset file.
	 * @param string $fileRelativeName file name relative to [[testFilePath]]
	 * @param string $content file content
137
	 * @throws \Exception on failure.
138
	 */
139
	protected function createAssetSourceFile($fileRelativeName, $content)
140
	{
141
		$fileFullName = $this->testFilePath . DIRECTORY_SEPARATOR . $fileRelativeName;
142
		$this->createDir(dirname($fileFullName));
143
		if (file_put_contents($fileFullName, $content) <= 0) {
144 145 146 147 148 149 150 151
			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
	 */
152
	protected function createAssetSourceFiles(array $files)
153 154 155 156
	{
		foreach ($files as $name => $content) {
			$this->createAssetSourceFile($name, $content);
		}
157 158
	}

159 160 161 162 163 164
	/**
	 * 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.
	 */
Alexander Makarov committed
165
	protected function invokeAssetControllerMethod($methodName, array $args = [])
166 167
	{
		$controller = $this->createAssetController();
168
		$controllerClassReflection = new \ReflectionClass(get_class($controller));
169 170 171 172 173 174 175
		$methodReflection = $controllerClassReflection->getMethod($methodName);
		$methodReflection->setAccessible(true);
		$result = $methodReflection->invokeArgs($controller, $args);
		$methodReflection->setAccessible(false);
		return $result;
	}

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
	/**
	 * 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
namespace {$config['namespace']};

use yii\web\AssetBundle;

class {$config['class']} extends AssetBundle
{
	public \$basePath = '{$config['basePath']}';
	public \$baseUrl = '{$config['baseUrl']}';
	public \$css = {$config['css']};
	public \$js = {$config['js']};
	public \$depends = {$config['depends']};
}
EOL;
		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'];
	}

230 231 232 233 234
	// Tests :

	public function testActionTemplate()
	{
		$configFileName = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php';
Alexander Makarov committed
235
		$this->runAssetControllerAction('template', [$configFileName]);
236 237
		$this->assertTrue(file_exists($configFileName), 'Unable to create config file template!');
	}
238

239
	public function testActionCompress()
240
	{
241
		// Given :
Alexander Makarov committed
242
		$cssFiles = [
243
			'css/test_body.css' => 'body {
244 245
				padding-top: 20px;
				padding-bottom: 60px;
246 247 248 249 250
			}',
			'css/test_footer.css' => '.footer {
				margin: 20px;
				display: block;
			}',
Alexander Makarov committed
251
		];
252
		$this->createAssetSourceFiles($cssFiles);
253

Alexander Makarov committed
254
		$jsFiles = [
255
			'js/test_alert.js' => "function test() {
256
				alert('Test message');
257 258 259 260
			}",
			'js/test_sum_ab.js' => "function sumAB(a, b) {
				return a + b;
			}",
Alexander Makarov committed
261
		];
262
		$this->createAssetSourceFiles($jsFiles);
263 264 265 266
		$assetBundleClassName = $this->declareAssetBundleClass([
			'css' => array_keys($cssFiles),
			'js' => array_keys($jsFiles),
		]);
267

Alexander Makarov committed
268
		$bundles = [
269
			$assetBundleClassName
Alexander Makarov committed
270
		];
271
		$bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php';
272 273 274

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

276
		// When :
Alexander Makarov committed
277
		$this->runAssetControllerAction('compress', [$configFile, $bundleFile]);
278

279
		// Then :
280
		$this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
281
		$this->assertTrue(is_array(require($bundleFile)), 'Output bundle file has incorrect format!');
282

283
		$compressedCssFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.css';
284
		$this->assertTrue(file_exists($compressedCssFileName), 'Unable to compress CSS files!');
285
		$compressedJsFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.js';
286
		$this->assertTrue(file_exists($compressedJsFileName), 'Unable to compress JS files!');
287 288 289 290 291 292 293 294 295

		$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!");
		}
296
	}
297 298 299 300 301 302 303

	/**
	 * Data provider for [[testAdjustCssUrl()]].
	 * @return array test data.
	 */
	public function adjustCssUrlDataProvider()
	{
Alexander Makarov committed
304 305
		return [
			[
Qiang Xue committed
306
				'.published-same-dir-class {background-image: url(published_same_dir.png);}',
307 308
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
309
				'.published-same-dir-class {background-image: url(../input/published_same_dir.png);}',
Alexander Makarov committed
310 311
			],
			[
Qiang Xue committed
312
				'.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}',
313 314
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
315
				'.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}',
Alexander Makarov committed
316 317
			],
			[
Qiang Xue committed
318
				'.static-same-dir-class {background-image: url(\'static_same_dir.png\');}',
319 320
				'/test/base/path/css',
				'/test/base/path/assets/output',
Qiang Xue committed
321
				'.static-same-dir-class {background-image: url(\'../../css/static_same_dir.png\');}',
Alexander Makarov committed
322 323
			],
			[
Qiang Xue committed
324
				'.static-relative-dir-class {background-image: url("../img/static_relative_dir.png");}',
325 326
				'/test/base/path/css',
				'/test/base/path/assets/output',
Qiang Xue committed
327
				'.static-relative-dir-class {background-image: url("../../img/static_relative_dir.png");}',
Alexander Makarov committed
328 329
			],
			[
Qiang Xue committed
330
				'.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}',
331 332
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
333
				'.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}',
Alexander Makarov committed
334 335
			],
			[
Qiang Xue committed
336
				'.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}',
337 338
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
339
				'.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}',
Alexander Makarov committed
340
			],
341 342 343 344 345 346 347 348 349 350 351 352
			[
				"@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');
				}",
			],
Alexander Makarov committed
353
		];
354 355 356 357 358 359 360 361 362 363 364 365
	}

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

		$this->assertEquals($expectedCssContent, $adjustedCssContent, 'Unable to adjust CSS correctly!');
	}
370
}