FileValidatorTest.php 9.26 KB
Newer Older
Suralc committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php

namespace yiiunit\framework\validators;


use yii\validators\FileValidator;
use yii\web\UploadedFile;
use Yii;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;

class FileValidatorTest extends TestCase
{
	public function setUp()
	{
		$this->mockApplication();
	}

	public function testAssureMessagesSetOnInit()
	{
		$val = new FileValidator();
Alexander Makarov committed
22
		foreach (['message', 'uploadRequired', 'tooMany', 'wrongType', 'tooBig', 'tooSmall'] as $attr) {
Suralc committed
23 24 25 26 27 28
			$this->assertTrue(is_string($val->$attr));
		}
	}

	public function testTypeSplitOnInit()
	{
Alexander Makarov committed
29 30 31 32 33 34 35 36
		$val = new FileValidator(['types' => 'jpeg, jpg, gif']);
		$this->assertEquals(['jpeg', 'jpg', 'gif'], $val->types);
		$val = new FileValidator(['types' => 'jpeg']);
		$this->assertEquals(['jpeg'], $val->types);
		$val = new FileValidator(['types' => '']);
		$this->assertEquals([], $val->types);
		$val = new FileValidator(['types' => []]);
		$this->assertEquals([], $val->types);
Suralc committed
37
		$val = new FileValidator();
Alexander Makarov committed
38 39 40
		$this->assertEquals([], $val->types);
		$val = new FileValidator(['types' => ['jpeg', 'exe']]);
		$this->assertEquals(['jpeg', 'exe'], $val->types);
Suralc committed
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
	}

	public function testGetSizeLimit()
	{
		$size = $this->sizeToBytes(ini_get('upload_max_filesize'));
		$val = new FileValidator();
		$this->assertEquals($size, $val->getSizeLimit());
		$val->maxSize = $size + 1; // set and test if value is overridden
		$this->assertEquals($size, $val->getSizeLimit());
		$val->maxSize = abs($size - 1);
		$this->assertEquals($size - 1, $val->getSizeLimit());
		$_POST['MAX_FILE_SIZE'] = $size + 1;
		$this->assertEquals($size - 1, $val->getSizeLimit());
		$_POST['MAX_FILE_SIZE'] = abs($size - 2);
		$this->assertSame($_POST['MAX_FILE_SIZE'], $val->getSizeLimit());
	}

	protected function sizeToBytes($sizeStr)
	{
		switch (substr($sizeStr, -1)) {
			case 'M':
			case 'm':
				return (int)$sizeStr * 1048576;
			case 'K':
			case 'k':
				return (int)$sizeStr * 1024;
			case 'G':
			case 'g':
				return (int)$sizeStr * 1073741824;
			default:
				return (int)$sizeStr;
		}
	}

	public function testValidateAttributeMultiple()
	{
Alexander Makarov committed
77 78
		$val = new FileValidator(['maxFiles' => 2]);
		$m = FakedValidationModel::createWithAttributes(['attr_files' => 'path']);
Suralc committed
79 80
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
Alexander Makarov committed
81
		$m = FakedValidationModel::createWithAttributes(['attr_files' => []]);
Suralc committed
82 83 84 85
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
		$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files')));
		$m = FakedValidationModel::createWithAttributes(
Alexander Makarov committed
86
			[
Suralc committed
87
				'attr_files' => $this->createTestFiles(
Alexander Makarov committed
88 89
					[
						[
Suralc committed
90 91
							'name' => 'test_up_1.txt',
							'size' => 1024,
Alexander Makarov committed
92 93
						],
						[
Suralc committed
94
							'error' => UPLOAD_ERR_NO_FILE,
Alexander Makarov committed
95 96
						],
					]
Suralc committed
97
				)
Alexander Makarov committed
98
			]
Suralc committed
99 100 101
		);
		$val->validateAttribute($m, 'attr_files');
		$this->assertFalse($m->hasErrors('attr_files'));
Alexander Makarov committed
102 103 104 105 106
		$m = FakedValidationModel::createWithAttributes([
			'attr_files' => $this->createTestFiles([
				[''], [''], ['']
			])
		]);
Suralc committed
107 108 109 110 111 112 113 114 115
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors());
		$this->assertTrue(stripos(current($m->getErrors('attr_files')), 'you can upload at most') !== false);
	}

	/**
	 * @param array $params
	 * @return UploadedFile[]
	 */
Alexander Makarov committed
116
	protected function createTestFiles($params = [])
Suralc committed
117 118 119 120 121 122 123 124 125
	{
		$rndString = function ($len = 10) {
			$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$randomString = '';
			for ($i = 0; $i < $len; $i++) {
				$randomString .= $characters[rand(0, strlen($characters) - 1)];
			}
			return $randomString;
		};
Alexander Makarov committed
126
		$files = [];
Suralc committed
127 128
		foreach ($params as $param) {
			if (empty($param) && count($params) != 1) {
Alexander Makarov committed
129
				$files[] = ['no instance of UploadedFile'];
Suralc committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
				continue;
			}
			$name = isset($param['name']) ? $param['name'] : $rndString();
			$tempName = \Yii::getAlias('@yiiunit/runtime/validators/file/tmp') . $name;
			if (is_readable($tempName)) {
				$size = filesize($tempName);
			} else {
				$size = isset($param['size']) ? $param['size'] : rand(
					1,
					$this->sizeToBytes(ini_get('upload_max_filesize'))
				);
			}
			$type = isset($param['type']) ? $param['type'] : 'text/plain';
			$error = isset($param['error']) ? $param['error'] : UPLOAD_ERR_OK;
			if (count($params) == 1) {
				$error = empty($param) ? UPLOAD_ERR_NO_FILE : $error;
Alexander Makarov committed
146
				return new UploadedFile([
147 148 149 150 151
					'name' => $name,
					'tempName' => $tempName,
					'type' => $type,
					'size' => $size,
					'error' => $error
Alexander Makarov committed
152
				]);
Suralc committed
153
			}
Alexander Makarov committed
154
			$files[] = new UploadedFile([
155 156 157 158 159
				'name' => $name,
				'tempName' => $tempName,
				'type' => $type,
				'size' => $size,
				'error' => $error
Alexander Makarov committed
160
			]);
Suralc committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
		}
		return $files;
	}

	public function testValidateAttribute()
	{
		// single File
		$val = new FileValidator();
		$m = $this->createModelForAttributeTest();
		$val->validateAttribute($m, 'attr_files');
		$this->assertFalse($m->hasErrors());
		$val->validateAttribute($m, 'attr_files_empty');
		$this->assertTrue($m->hasErrors('attr_files_empty'));
		$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty')));
		$m = $this->createModelForAttributeTest();
		// too big
Alexander Makarov committed
177
		$val = new FileValidator(['maxSize' => 128]);
Suralc committed
178 179 180 181 182
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
		$this->assertTrue(
			stripos(
				current($m->getErrors('attr_files')),
Alexander Makarov committed
183
				str_ireplace(['{file}', '{limit}'], [$m->attr_files->name, 128], $val->tooBig)
Suralc committed
184 185 186 187
			) !== false
		);
		// to Small
		$m = $this->createModelForAttributeTest();
Alexander Makarov committed
188
		$val = new FileValidator(['minSize' => 2048]);
Suralc committed
189 190 191 192 193
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
		$this->assertTrue(
			stripos(
				current($m->getErrors('attr_files')),
Alexander Makarov committed
194
				str_ireplace(['{file}', '{limit}'], [$m->attr_files->name, 2048], $val->tooSmall)
Suralc committed
195 196 197 198 199 200 201 202 203 204 205
			) !== false
		);
		// UPLOAD_ERR_INI_SIZE/UPLOAD_ERR_FORM_SIZE
		$m = $this->createModelForAttributeTest();
		$val = new FileValidator();
		$val->validateAttribute($m, 'attr_err_ini');
		$this->assertTrue($m->hasErrors('attr_err_ini'));
		$this->assertTrue(
			stripos(
				current($m->getErrors('attr_err_ini')),
				str_ireplace(
Alexander Makarov committed
206 207
					['{file}', '{limit}'],
					[$m->attr_err_ini->name, $val->getSizeLimit()],
Suralc committed
208 209 210 211 212 213 214 215 216 217 218 219
					$val->tooBig
				)
			) !== false
		);
		// UPLOAD_ERR_PARTIAL
		$m = $this->createModelForAttributeTest();
		$val = new FileValidator();
		$val->validateAttribute($m, 'attr_err_part');
		$this->assertTrue($m->hasErrors('attr_err_part'));
		$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_part')));
	}

Suralc committed
220 221
	public function testValidateAttributeType()
	{
Alexander Makarov committed
222
		$val = new FileValidator(['types' => 'jpeg, jpg']);
Suralc committed
223
		$m = FakedValidationModel::createWithAttributes(
Alexander Makarov committed
224 225 226 227
			[
				'attr_jpg' => $this->createTestFiles([['name' => 'one.jpeg']]),
				'attr_exe' => $this->createTestFiles([['name' => 'bad.exe']]),
			]
Suralc committed
228 229 230 231 232 233 234 235 236
		);
		$val->validateAttribute($m, 'attr_jpg');
		$this->assertFalse($m->hasErrors('attr_jpg'));
		$val->validateAttribute($m, 'attr_exe');
		$this->assertTrue($m->hasErrors('attr_exe'));
		$this->assertTrue(stripos(current($m->getErrors('attr_exe')), 'Only files with these extensions ') !== false);
	}


Suralc committed
237 238 239
	protected function createModelForAttributeTest()
	{
		return FakedValidationModel::createWithAttributes(
Alexander Makarov committed
240 241 242 243 244 245 246 247 248 249 250
			[
				'attr_files' => $this->createTestFiles([
					['name' => 'abc.jpg', 'size' => 1024, 'type' => 'image/jpeg'],
				]),
				'attr_files_empty' => $this->createTestFiles([[]]),
				'attr_err_ini' => $this->createTestFiles([['error' => UPLOAD_ERR_INI_SIZE]]),
				'attr_err_part' => $this->createTestFiles([['error' => UPLOAD_ERR_PARTIAL]]),
				'attr_err_tmp' => $this->createTestFiles([['error' => UPLOAD_ERR_NO_TMP_DIR]]),
				'attr_err_write' => $this->createTestFiles([['error' => UPLOAD_ERR_CANT_WRITE]]),
				'attr_err_ext' => $this->createTestFiles([['error' => UPLOAD_ERR_EXTENSION]]),
			]
Suralc committed
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
		);
	}

	public function testValidateAttributeErrPartial()
	{
		$m = $this->createModelForAttributeTest();
		$val = new FileValidator();
		$val->validateAttribute($m, 'attr_err_part');
		$this->assertTrue($m->hasErrors('attr_err_part'));
		$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_part')));
		$log = Yii::$app->getLog()->toArray();
	}

	public function testValidateAttributeErrCantWrite()
	{
		$m = $this->createModelForAttributeTest();
		$val = new FileValidator();
		$val->validateAttribute($m, 'attr_err_write');
		$this->assertTrue($m->hasErrors('attr_err_write'));
		$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_write')));
		$log = Yii::$app->getLog()->toArray();
	}

	public function testValidateAttributeErrExtension()
	{
		$m = $this->createModelForAttributeTest();
		$val = new FileValidator();
		$val->validateAttribute($m, 'attr_err_ext');
		$this->assertTrue($m->hasErrors('attr_err_ext'));
		$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_ext')));
		$log = Yii::$app->getLog()->toArray();
	}

	public function testValidateAttributeErrNoTmpDir()
	{
		$m = $this->createModelForAttributeTest();
		$val = new FileValidator();
		$val->validateAttribute($m, 'attr_err_tmp');
		$this->assertTrue($m->hasErrors('attr_err_tmp'));
		$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_tmp')));
		$log = Yii::$app->getLog()->toArray();
	}
Qiang Xue committed
293
}