FileValidatorTest.php 10.5 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
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors());
		$this->assertTrue(stripos(current($m->getErrors('attr_files')), 'you can upload at most') !== false);
Alexander Pletnev committed
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
		$m = FakedValidationModel::createWithAttributes(
			[
				'attr_images' => $this->createTestFiles(
					[
						[
							'name' => 'image.png',
							'size' => 1024,
							'type' => 'image/png'
						],
						[
							'name' => 'image.png',
							'size' => 1024,
							'type' => 'image/png'
						],
						[
								'name' => 'text.txt',
								'size' => 1024
						],
					]
				)
			]
		);
		$m->setScenario('validateMultipleFiles');
		$this->assertFalse($m->validate());
		$this->assertTrue(stripos(current($m->getErrors('attr_images')),
			'Only files with these extensions are allowed') !== false);
136

Alexander Pletnev committed
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
		$m = FakedValidationModel::createWithAttributes(
			[
				'attr_images' => $this->createTestFiles(
					[
						[
							'name' => 'image.png',
							'size' => 1024,
							'type' => 'image/png'
						],
						[
							'name' => 'image.png',
							'size' => 1024,
							'type' => 'image/png'
						],
					]
				)
			]
		);
		$m->setScenario('validateMultipleFiles');
		$this->assertTrue($m->validate());

		$m = FakedValidationModel::createWithAttributes(
			[
				'attr_image' => $this->createTestFiles(
					[
						[
							'name' => 'text.txt',
							'size' => 1024,
						],
					]
				)
			]
		);
		$m->setScenario('validateFile');
		$this->assertFalse($m->validate());
Suralc committed
172 173 174 175 176 177
	}

	/**
	 * @param array $params
	 * @return UploadedFile[]
	 */
Alexander Makarov committed
178
	protected function createTestFiles($params = [])
Suralc committed
179 180 181 182 183 184 185 186 187
	{
		$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
188
		$files = [];
Suralc committed
189 190
		foreach ($params as $param) {
			if (empty($param) && count($params) != 1) {
Alexander Makarov committed
191
				$files[] = ['no instance of UploadedFile'];
Suralc committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
				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
208
				return new UploadedFile([
209 210 211 212 213
					'name' => $name,
					'tempName' => $tempName,
					'type' => $type,
					'size' => $size,
					'error' => $error
Alexander Makarov committed
214
				]);
Suralc committed
215
			}
Alexander Makarov committed
216
			$files[] = new UploadedFile([
217 218 219 220 221
				'name' => $name,
				'tempName' => $tempName,
				'type' => $type,
				'size' => $size,
				'error' => $error
Alexander Makarov committed
222
			]);
Suralc committed
223 224 225 226 227 228 229 230 231 232 233 234
		}
		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');
Qiang Xue committed
235 236
		$this->assertTrue($m->hasErrors('attr_files_empty'));
		$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty')));
Qiang Xue committed
237

Luciano Baraglia committed
238
		// single File with skipOnEmpty = false
Qiang Xue committed
239 240 241 242 243
		$val = new FileValidator(['skipOnEmpty' => false]);
		$m = $this->createModelForAttributeTest();
		$val->validateAttribute($m, 'attr_files');
		$this->assertFalse($m->hasErrors());
		$val->validateAttribute($m, 'attr_files_empty');
Suralc committed
244 245 246
		$this->assertTrue($m->hasErrors('attr_files_empty'));
		$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty')));
		$m = $this->createModelForAttributeTest();
Qiang Xue committed
247

Suralc committed
248
		// too big
Alexander Makarov committed
249
		$val = new FileValidator(['maxSize' => 128]);
Suralc committed
250 251
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
Qiang Xue committed
252
		$this->assertTrue(stripos(current($m->getErrors('attr_files')), 'too big') !== false);
Suralc committed
253 254
		// to Small
		$m = $this->createModelForAttributeTest();
Alexander Makarov committed
255
		$val = new FileValidator(['minSize' => 2048]);
Suralc committed
256 257
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
Qiang Xue committed
258
		$this->assertTrue(stripos(current($m->getErrors('attr_files')), 'too small') !== false);
Suralc committed
259 260 261 262 263
		// 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'));
Qiang Xue committed
264
		$this->assertTrue(stripos(current($m->getErrors('attr_err_ini')), 'too big') !== false);
Suralc committed
265 266 267 268 269 270 271 272
		// 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
273 274
	public function testValidateAttributeType()
	{
Alexander Makarov committed
275
		$val = new FileValidator(['types' => 'jpeg, jpg']);
Suralc committed
276
		$m = FakedValidationModel::createWithAttributes(
Alexander Makarov committed
277 278 279 280
			[
				'attr_jpg' => $this->createTestFiles([['name' => 'one.jpeg']]),
				'attr_exe' => $this->createTestFiles([['name' => 'bad.exe']]),
			]
Suralc committed
281 282 283 284 285 286 287 288 289
		);
		$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
290 291 292
	protected function createModelForAttributeTest()
	{
		return FakedValidationModel::createWithAttributes(
Alexander Makarov committed
293 294 295 296 297 298 299 300 301 302 303
			[
				'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
304 305 306 307 308 309 310 311 312 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
		);
	}

	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')));
	}

	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')));
	}

	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')));
	}

	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')));
	}
Qiang Xue committed
342
}