AssetControllerTest.php 9.45 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 9 10 11 12 13 14 15
 * @see AssetController
 */
class AssetControllerTest extends TestCase
{
	/**
	 * @var string path for the test files.
	 */
	protected $testFilePath = '';
16 17 18 19
	/**
	 * @var string test assets path.
	 */
	protected $testAssetsBasePath = '';
20 21 22

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

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

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

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

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

	/**
	 * Creates test bundle configuration.
114
	 * @param array[] $bundles asset bundles config.
115 116
	 * @return array bundle config.
	 */
117
	protected function createBundleConfig(array $bundles)
118
	{
119 120 121 122 123 124 125 126
		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'] = '';
			}
		}
127 128 129 130 131 132
		return $bundles;
	}

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

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

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
	/**
	 * 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 = array())
	{
		$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;
	}

187 188 189 190 191 192 193 194
	// Tests :

	public function testActionTemplate()
	{
		$configFileName = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php';
		$this->runAssetControllerAction('template', array($configFileName));
		$this->assertTrue(file_exists($configFileName), 'Unable to create config file template!');
	}
195

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

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

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

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

235
		// When :
236 237
		$this->runAssetControllerAction('compress', array($configFile, $bundleFile));

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

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

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

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

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

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