AssetControllerTest.php 9.36 KB
Newer Older
1 2 3 4 5 6
<?php

use yiiunit\TestCase;
use yii\console\controllers\AssetController;

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

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

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

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

	/**
	 * Removes directory.
50
	 * @param string $dirName directory full name
51 52 53 54 55 56 57 58 59 60 61 62 63 64
	 */
	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
65
		$module = $this->getMock('yii\\base\\Module', ['fake'], ['console']);
66
		$assetController = new AssetController('asset', $module);
67
		$assetController->interactive = false;
68 69 70 71 72 73 74 75 76 77 78
		$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
79
	protected function runAssetControllerAction($actionId, array $args = [])
80 81 82 83
	{
		$controller = $this->createAssetController();
		ob_start();
		ob_implicit_flush(false);
Qiang Xue committed
84
		$controller->run($actionId, $args);
85 86 87
		return ob_get_clean();
	}

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

	/**
	 * Creates test bundle configuration.
116
	 * @param array[] $bundles asset bundles config.
117 118
	 * @return array bundle config.
	 */
119
	protected function createBundleConfig(array $bundles)
120
	{
121 122 123 124 125 126 127 128
		foreach ($bundles as $name => $config) {
			if (!array_key_exists('basePath', $config)) {
				$bundles[$name]['basePath'] = $this->testFilePath;
			}
			if (!array_key_exists('baseUrl', $config)) {
				$bundles[$name]['baseUrl'] = '';
			}
		}
129 130 131 132 133 134
		return $bundles;
	}

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

146 147 148 149
	/**
	 * Creates test asset file.
	 * @param string $fileRelativeName file name relative to [[testFilePath]]
	 * @param string $content file content
150
	 * @throws Exception on failure.
151
	 */
152
	protected function createAssetSourceFile($fileRelativeName, $content)
153
	{
154
		$fileFullName = $this->testFilePath . DIRECTORY_SEPARATOR . $fileRelativeName;
155
		$this->createDir(dirname($fileFullName));
156
		if (file_put_contents($fileFullName, $content) <= 0) {
157 158 159 160 161 162 163 164
			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
	 */
165
	protected function createAssetSourceFiles(array $files)
166 167 168 169
	{
		foreach ($files as $name => $content) {
			$this->createAssetSourceFile($name, $content);
		}
170 171
	}

172 173 174 175 176 177
	/**
	 * 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
178
	protected function invokeAssetControllerMethod($methodName, array $args = [])
179 180 181 182 183 184 185 186 187 188
	{
		$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;
	}

189 190 191 192 193
	// Tests :

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

198
	public function atestActionCompress()
199
	{
200
		// Given :
Alexander Makarov committed
201
		$cssFiles = [
202
			'css/test_body.css' => 'body {
203 204
				padding-top: 20px;
				padding-bottom: 60px;
205 206 207 208 209
			}',
			'css/test_footer.css' => '.footer {
				margin: 20px;
				display: block;
			}',
Alexander Makarov committed
210
		];
211
		$this->createAssetSourceFiles($cssFiles);
212

Alexander Makarov committed
213
		$jsFiles = [
214
			'js/test_alert.js' => "function test() {
215
				alert('Test message');
216 217 218 219
			}",
			'js/test_sum_ab.js' => "function sumAB(a, b) {
				return a + b;
			}",
Alexander Makarov committed
220
		];
221
		$this->createAssetSourceFiles($jsFiles);
222

Alexander Makarov committed
223 224
		$bundles = [
			'app' => [
225 226
				'css' => array_keys($cssFiles),
				'js' => array_keys($jsFiles),
Alexander Makarov committed
227
				'depends' => [
228
					'yii',
Alexander Makarov committed
229 230 231
				],
			],
		];
232
		$bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php';
233 234 235

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

237
		// When :
Alexander Makarov committed
238
		$this->runAssetControllerAction('compress', [$configFile, $bundleFile]);
239

240
		// Then :
241
		$this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
242
		$this->assertTrue(is_array(require($bundleFile)), 'Output bundle file has incorrect format!');
243

244
		$compressedCssFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.css';
245
		$this->assertTrue(file_exists($compressedCssFileName), 'Unable to compress CSS files!');
246
		$compressedJsFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.js';
247
		$this->assertTrue(file_exists($compressedJsFileName), 'Unable to compress JS files!');
248 249 250 251 252 253 254 255 256

		$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!");
		}
257
	}
258 259 260 261 262 263 264

	/**
	 * Data provider for [[testAdjustCssUrl()]].
	 * @return array test data.
	 */
	public function adjustCssUrlDataProvider()
	{
Alexander Makarov committed
265 266
		return [
			[
Qiang Xue committed
267
				'.published-same-dir-class {background-image: url(published_same_dir.png);}',
268 269
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
270
				'.published-same-dir-class {background-image: url(../input/published_same_dir.png);}',
Alexander Makarov committed
271 272
			],
			[
Qiang Xue committed
273
				'.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}',
274 275
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
276
				'.published-relative-dir-class {background-image: url(../img/published_relative_dir.png);}',
Alexander Makarov committed
277 278
			],
			[
Qiang Xue committed
279
				'.static-same-dir-class {background-image: url(\'static_same_dir.png\');}',
280 281
				'/test/base/path/css',
				'/test/base/path/assets/output',
Qiang Xue committed
282
				'.static-same-dir-class {background-image: url(\'../../css/static_same_dir.png\');}',
Alexander Makarov committed
283 284
			],
			[
Qiang Xue committed
285
				'.static-relative-dir-class {background-image: url("../img/static_relative_dir.png");}',
286 287
				'/test/base/path/css',
				'/test/base/path/assets/output',
Qiang Xue committed
288
				'.static-relative-dir-class {background-image: url("../../img/static_relative_dir.png");}',
Alexander Makarov committed
289 290
			],
			[
Qiang Xue committed
291
				'.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}',
292 293
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
294
				'.absolute-url-class {background-image: url(http://domain.com/img/image.gif);}',
Alexander Makarov committed
295 296
			],
			[
Qiang Xue committed
297
				'.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}',
298 299
				'/test/base/path/assets/input',
				'/test/base/path/assets/output',
Qiang Xue committed
300
				'.absolute-url-secure-class {background-image: url(https://secure.domain.com/img/image.gif);}',
Alexander Makarov committed
301 302
			],
		];
303 304 305 306 307 308 309 310 311 312 313 314
	}

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

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