FileValidatorTest.php 14.1 KB
Newer Older
Suralc committed
1 2 3 4 5 6 7 8 9 10
<?php

namespace yiiunit\framework\validators;

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

11 12 13
/**
 * @group validators
 */
Suralc committed
14 15
class FileValidatorTest extends TestCase
{
16 17 18 19 20 21 22 23
    public function setUp()
    {
        $this->mockApplication();
    }

    public function testAssureMessagesSetOnInit()
    {
        $val = new FileValidator();
24
        foreach (['message', 'uploadRequired', 'tooMany', 'wrongExtension', 'tooBig', 'tooSmall', 'wrongMimeType'] as $attr) {
25 26 27 28 29 30
            $this->assertTrue(is_string($val->$attr));
        }
    }

    public function testTypeSplitOnInit()
    {
31 32
        $val = new FileValidator(['extensions' => 'jpeg, jpg, gif']);
        $this->assertEquals(['jpeg', 'jpg', 'gif'], $val->extensions);
Mark committed
33

34 35
        $val = new FileValidator(['extensions' => 'jpeg']);
        $this->assertEquals(['jpeg'], $val->extensions);
Mark committed
36

37 38
        $val = new FileValidator(['extensions' => '']);
        $this->assertEquals([], $val->extensions);
Mark committed
39

40 41
        $val = new FileValidator(['extensions' => []]);
        $this->assertEquals([], $val->extensions);
Mark committed
42

43
        $val = new FileValidator();
44
        $this->assertEquals([], $val->extensions);
Mark committed
45

46 47
        $val = new FileValidator(['extensions' => ['jpeg', 'exe']]);
        $this->assertEquals(['jpeg', 'exe'], $val->extensions);
48
    }
Suralc committed
49

Mark committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    public function testMimeTypeSplitOnInit()
    {
        $val = new FileValidator(['mimeTypes' => 'text/plain, image/png']);
        $this->assertEquals(['text/plain', 'image/png'], $val->mimeTypes);

        $val = new FileValidator(['mimeTypes' => 'text/plain']);
        $this->assertEquals(['text/plain'], $val->mimeTypes);

        $val = new FileValidator(['mimeTypes' => '']);
        $this->assertEquals([], $val->mimeTypes);

        $val = new FileValidator(['mimeTypes' => []]);
        $this->assertEquals([], $val->mimeTypes);

        $val = new FileValidator();
        $this->assertEquals([], $val->mimeTypes);

        $val = new FileValidator(['mimeTypes' => ['text/plain', 'image/png']]);
        $this->assertEquals(['text/plain', 'image/png'], $val->mimeTypes);
    }

71 72 73 74 75 76 77 78 79 80 81 82 83 84
    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());
    }
Suralc committed
85

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    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;
        }
    }
Suralc committed
102

103 104
    public function testValidateAttributeMultiple()
    {
Mark committed
105 106 107
        $val = new FileValidator([
            'maxFiles' => 2,
        ]);
108 109 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 136 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
        $m = FakedValidationModel::createWithAttributes(['attr_files' => 'path']);
        $val->validateAttribute($m, 'attr_files');
        $this->assertTrue($m->hasErrors('attr_files'));
        $m = FakedValidationModel::createWithAttributes(['attr_files' => []]);
        $val->validateAttribute($m, 'attr_files');
        $this->assertTrue($m->hasErrors('attr_files'));
        $this->assertSame($val->uploadRequired, current($m->getErrors('attr_files')));
        $m = FakedValidationModel::createWithAttributes(
            [
                'attr_files' => $this->createTestFiles(
                    [
                        [
                            'name' => 'test_up_1.txt',
                            'size' => 1024,
                        ],
                        [
                            'error' => UPLOAD_ERR_NO_FILE,
                        ],
                    ]
                )
            ]
        );
        $val->validateAttribute($m, 'attr_files');
        $this->assertFalse($m->hasErrors('attr_files'));
        $m = FakedValidationModel::createWithAttributes([
            'attr_files' => $this->createTestFiles([
                [''], [''], ['']
            ])
        ]);
        $val->validateAttribute($m, 'attr_files');
        $this->assertTrue($m->hasErrors());
        $this->assertTrue(stripos(current($m->getErrors('attr_files')), 'you can upload at most') !== false);
        $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);
Suralc committed
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        $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());
Suralc committed
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        $m = FakedValidationModel::createWithAttributes(
            [
                'attr_image' => $this->createTestFiles(
                    [
                        [
                            'name' => 'text.txt',
                            'size' => 1024,
                        ],
                    ]
                )
            ]
        );
        $m->setScenario('validateFile');
        $this->assertFalse($m->validate());
    }
203

204 205 206 207 208 209 210 211 212 213 214 215
    /**
     * @param  array          $params
     * @return UploadedFile[]
     */
    protected function createTestFiles($params = [])
    {
        $rndString = function ($len = 10) {
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $randomString = '';
            for ($i = 0; $i < $len; $i++) {
                $randomString .= $characters[rand(0, strlen($characters) - 1)];
            }
Alexander Pletnev committed
216

217 218 219 220 221 222 223 224 225
            return $randomString;
        };
        $files = [];
        foreach ($params as $param) {
            if (empty($param) && count($params) != 1) {
                $files[] = ['no instance of UploadedFile'];
                continue;
            }
            $name = isset($param['name']) ? $param['name'] : $rndString();
Mark committed
226
            $tempName = \Yii::getAlias('@yiiunit/runtime/validators/file/tmp/') . $name;
227 228 229 230 231 232 233 234 235 236 237 238
            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;
Suralc committed
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
                return new UploadedFile([
                    'name' => $name,
                    'tempName' => $tempName,
                    'type' => $type,
                    'size' => $size,
                    'error' => $error
                ]);
            }
            $files[] = new UploadedFile([
                'name' => $name,
                'tempName' => $tempName,
                'type' => $type,
                'size' => $size,
                'error' => $error
            ]);
        }
Suralc committed
256

257 258
        return $files;
    }
Qiang Xue committed
259

260 261 262 263 264 265 266 267 268 269
    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')));
Qiang Xue committed
270

271 272 273 274 275 276 277 278 279
        // 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');
        $this->assertTrue($m->hasErrors('attr_files_empty'));
        $this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty')));
        $m = $this->createModelForAttributeTest();
Suralc committed
280

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        // too big
        $val = new FileValidator(['maxSize' => 128]);
        $val->validateAttribute($m, 'attr_files');
        $this->assertTrue($m->hasErrors('attr_files'));
        $this->assertTrue(stripos(current($m->getErrors('attr_files')), 'too big') !== false);
        // to Small
        $m = $this->createModelForAttributeTest();
        $val = new FileValidator(['minSize' => 2048]);
        $val->validateAttribute($m, 'attr_files');
        $this->assertTrue($m->hasErrors('attr_files'));
        $this->assertTrue(stripos(current($m->getErrors('attr_files')), 'too small') !== 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')), 'too big') !== 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
305

306 307
    public function testValidateAttributeType()
    {
Mark committed
308
        $val = new FileValidator([
309 310
            'extensions' => 'jpeg, jpg',
            'checkExtensionByMimeType' => false,
Mark committed
311
        ]);
312 313 314 315 316 317 318 319 320 321 322 323
        $m = FakedValidationModel::createWithAttributes(
            [
                'attr_jpg' => $this->createTestFiles([['name' => 'one.jpeg']]),
                'attr_exe' => $this->createTestFiles([['name' => 'bad.exe']]),
            ]
        );
        $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
324

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    protected function createModelForAttributeTest()
    {
        return FakedValidationModel::createWithAttributes(
            [
                '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
341

342 343 344 345 346 347 348 349
    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')));
    }
Suralc committed
350

351 352 353 354 355 356 357 358
    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')));
    }
Suralc committed
359

360 361 362 363 364 365 366 367
    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')));
    }
Suralc committed
368

369 370 371 372 373 374 375 376
    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
377
}