5

I have the following uploadform 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've 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, That keeps telling me the field hasn't been filled in. How can I properly unit test the extension rules?

5
  • +1. what is the document field supposed to be? and why haven't you set the $test field? Commented Apr 29, 2012 at 7:28
  • is document field a string? Commented Apr 29, 2012 at 8:02
  • woeps, bad copy paste. test = document. Commented Apr 29, 2012 at 9:26
  • ok. will try and get back to you with a solution Commented Apr 29, 2012 at 9:43
  • can you tell me the exact output of phpunit? Commented Apr 29, 2012 at 10:39

1 Answer 1

5

As we know that Yii uses CUploadedFile, for file uploads, we have to use it to initialize the file attribute of the model.

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

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

The CFileValidator takes into account the file extension for determining type, so to test your validator you'll have to keep changing the name of the $testFile, i.e $testFile['name']='correctname.rar'.

So finally we do not really need a file anywhere, just the info of the file is enough to test.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.