FileValidatorTest.php 9.21 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
		}
		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
173 174
		$this->assertTrue($m->hasErrors('attr_files_empty'));
		$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty')));
Qiang Xue committed
175 176 177 178 179 180 181

		// single File with skipOnEmpty=false
		$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
182 183 184
		$this->assertTrue($m->hasErrors('attr_files_empty'));
		$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty')));
		$m = $this->createModelForAttributeTest();
Qiang Xue committed
185

Suralc committed
186
		// too big
Alexander Makarov committed
187
		$val = new FileValidator(['maxSize' => 128]);
Suralc committed
188 189
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
Qiang Xue committed
190
		$this->assertTrue(stripos(current($m->getErrors('attr_files')), 'too big') !== false);
Suralc committed
191 192
		// to Small
		$m = $this->createModelForAttributeTest();
Alexander Makarov committed
193
		$val = new FileValidator(['minSize' => 2048]);
Suralc committed
194 195
		$val->validateAttribute($m, 'attr_files');
		$this->assertTrue($m->hasErrors('attr_files'));
Qiang Xue committed
196
		$this->assertTrue(stripos(current($m->getErrors('attr_files')), 'too small') !== false);
Suralc committed
197 198 199 200 201
		// 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
202
		$this->assertTrue(stripos(current($m->getErrors('attr_err_ini')), 'too big') !== false);
Suralc committed
203 204 205 206 207 208 209 210
		// 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
211 212
	public function testValidateAttributeType()
	{
Alexander Makarov committed
213
		$val = new FileValidator(['types' => 'jpeg, jpg']);
Suralc committed
214
		$m = FakedValidationModel::createWithAttributes(
Alexander Makarov committed
215 216 217 218
			[
				'attr_jpg' => $this->createTestFiles([['name' => 'one.jpeg']]),
				'attr_exe' => $this->createTestFiles([['name' => 'bad.exe']]),
			]
Suralc committed
219 220 221 222 223 224 225 226 227
		);
		$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
228 229 230
	protected function createModelForAttributeTest()
	{
		return FakedValidationModel::createWithAttributes(
Alexander Makarov committed
231 232 233 234 235 236 237 238 239 240 241
			[
				'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
242 243 244 245 246 247 248 249 250 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
		);
	}

	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
280
}