5

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.

user972959
  • 381
  • 3
  • 5

2 Answers2

3

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.

Yousha Aleayoub
  • 4,532
  • 4
  • 53
  • 64
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • No idea, actually. I've never used phpunit. There's some stuff here: http://stackoverflow.com/questions/3402765/how-can-i-write-tests-for-file-upload-in-php though not specifically for phpunit. – Marc B Oct 20 '11 at 17:41
  • @user972959 try isolating move_uploaded_file on other function, mock that function implementing copy + file_exists instead – Diogo Alves Mar 20 '19 at 13:21
1

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);
  }
}
Jaisen Mathai
  • 56
  • 1
  • 5