Yii - Unittesting Model Download Forms

I have the following upload model

class TestUploadForm extends CFormModel { public $test; public function rules() { return array( array(test, 'file', 'types' => 'zip, rar'), ); } 

My question is: how can I unit test this? I tried something like:

 public $testFile = 'fixtures/files/yii-1.1.0-validator-cheatsheet.pdf'; public function testValidators() { $testUpload = new TestUploadForm; $testUpload->test = $this->testFile ; assertTrue($testUpload ->validate()); $errors= $testUpload ->errors; assertEmpty($errors); } 

However, this tells me that the field is blank. How to unit test extension rules?

+6
source share
1 answer

As we know, Yii uses CUploadedFile to upload files, we must use it to initialize the model file attribute.

We can use the constructor to initialize the file attribute new CUploadedFile($names, $tmp_names, $types, $sizes, $errors);

Therefore, we can do this:

 public ValidatorTest extends CTestCase{ public $testFile = array( 'name'=>'yii-1.1.0-validator-cheatsheet.pdf', 'tmp_name'=>'/private/var/tmp/phpvVRwKT', 'type'=>'application/pdf', 'size'=>100, 'error'=>0 ); public function testValidators() { $testUpload = new TestUploadForm; $testUpload->test = new CUploadedFile($this->testFile['name'],$this->testFile['tmp_name'],$this->testFile['type'],$this->testFile['size'],$this->testFile['error']); $this->assertTrue($testUpload->validate()); $errors= $testUpload->errors; $this->assertEmpty($errors); } } 

CFileValidator takes into account the extension for determining the type , so to check your validator you will need to continue to change the name of $testFile , i.e. $testFile['name']='correctname.rar' .

So, we really do not need the file anywhere, just the file information is enough for testing.

+5
source

Source: https://habr.com/ru/post/914445/


All Articles