Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test move_uploaded_file and is_uploaded_file with vfsStream

I've tried to test move_uploaded_file and is_uploaded_file with PHPUnit and vfsStream. They always return false.

public function testShouldUploadAZipFileAndMoveIt()
{
    $_FILES = array('fieldName' => array(
        'name'     => 'file.zip',
        'type'     => 'application/zip',
        'tmp_name' => 'vfs://root/file.zip',
        'error'    => 0,
        'size'     => 0,
    ));

    vfsStream::setup();
    $vfsStreamFile = vfsStream::newFile('file.zip');
    vfsStreamWrapper::getRoot()
        ->addChild($vfsStreamFile);

    $vfsStreamDirectory = vfsStream::newDirectory('/destination');
    vfsStreamWrapper::getRoot()
        ->addChild($vfsStreamDirectory);

    $fileUpload = new File_Upload();
    $fileUpload->upload(
        vfsStream::url('root/file.zip'),
        vfsStream::url('root/destination/file.zip')
    );

    $this->assertFileExists(vfsStream::url('root/destination/file.zip'));
}

Is it possible? How do I do that? Can I post a vfsStreamFile (or any data) without a form, just using PHP code? Thank you.

like image 786
user972959 Avatar asked Oct 09 '22 17:10

user972959


2 Answers

No. move_uploaded_file and is_uploaded_file are specifically designed to handle uploaded files. They include extra security checks to ensure that the file's not been tampered with in the time between the upload completing and the controlling script accessing the file.

Note: changing the file from within the script counts as tampering.

like image 151
Marc B Avatar answered Oct 12 '22 07:10

Marc B


Assuming you're using classes you can create a parent class.

// this is the class you want to test
class File {
  public function verify($file) {
    return $this->isUploadedFile($file);
  }
  public function isUploadedFile($file) {
    return is_uploaded_file($file);
  }
}

// for the unit test create a wrapper that overrides the isUploadedFile method
class FileWrapper extends File {
  public function isUploadedFile($file) {
    return true;
  }
}

// write your unit test using the wrapper class
class FileTest extends PHPUnit_Framework_TestCase {
  public function setup() {
    $this->fileObj = new FileWrapper;
  }

  public function testFile() {
    $result = $this->fileObj->verify('/some/random/path/to/file');
    $this->assertTrue($result);
  }
}
like image 38
Jaisen Mathai Avatar answered Oct 12 '22 05:10

Jaisen Mathai