Search code examples
phpphpunitvfs

(PHPUnit) Is it possible to test mkdir, tempnam, realpath and move_uploaded_file?


I'm making a test for a File System and I wanted to know if is possible to test if some functions are functional.

I'm using vfsStream for the most of them, but this virtual file system doesn't work with some functionality of the File System.

I succeeded to test:

See an example:

public function unlink($file) {

        return unlink($file);
    }

The unit test:

public function setUp() {
        $this->fileSystem = new FileSystem();

        // Creates my Virtual File System 
        $tree = array('library' => array('test.txt' => 'conteudo do arquivo'));
        $home = vfsStream::setup("home", '', $tree);
    }

public function testUnlink() {
        $this->assertTrue($this->fileSystem->unlink(vfsStream::url('home/library/test.txt')));
    }

However, I still got 4 more functions that I need to test and I don't know if I actually can do this in PHPUnit.

As you can see, all of them are from PHP (like unlink( )), but I also modified them to handle some errors properly, even though my priority now is to test if the basic function of the PHP is functional in my code.

The functions I don't know how to test are:

Someone know how to make an unit test for any of the functions above?


Solution

  • 3 of the 4 you mentioned are easy enough to write simple tests for:

    /**
     * @test
     */
     public function mkdirWorksAsExpected()
     {
         $tmp_dir = 'mkdirtest';
    
         if (is_dir($tmp_dir)) {
             rmdir($tmp_dir);
         }
    
         mkdir($tmp_dir);
         $this->assertTrue(is_dir($tmp_dir));
     }
    
     /**
      * @test
      */
     public function tempnamWorksAsExpected()
     {
         $tmp_dir = 'tempnamtest';
         $filename = tempnam($tmp_dir, 'test');
    
         $this->assertTrue(file_exists($filename));
         unlink($filename);
     }
    
     /**
      * @test
      */
      public function realpathWorksAsExpected()
      {
          $filename = tempnam('/tmp', 'test');
          $this->assertEquals($filename, realpath($filename));
          unlink($filename);
      }
    

    Testing move_uploaded_file() would require you to actually simulate the uploading of a file using something like Guzzle and an end point. I don't think manipulating the contents of $_POST is enough, but I haven't tried it.

    Hope this helps.