Check file move_uploaded_file and is_uploaded_file with vfsStream

I tried to check the file 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 should I do it? Can I post vfsStreamFile (or any data) without a form, just using PHP code? Thank.

+5
source share
2 answers

No. move_uploaded_file and is_uploaded_file are specifically designed to handle uploaded files. They include additional security checks to ensure that the file has not been modified in the interval between the completion of the download and access control of the script file.

script .

+2

, , .

// 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);
  }
}
+1

All Articles