CakePHP / phpunit: how to taunt file upload

I am trying to write tests for an endpoint that is expecting an email request with an attached CSV file. I know to simulate a mail request as follows:

$this->post('/foo/bar'); 

But I can not figure out how to add file data. I tried to manually install the $_FILES , but it did not work ...

 $_FILES = [ 'csvfile' => [ 'tmp_name' => '/home/path/to/tests/Fixture/csv/test.csv', 'name' => 'test.csv', 'type' => 'text/csv', 'size' => 335057, 'error' => 0, ], ]; $this->post('/foo/bar'); 

What is the right way to do this?

+5
source share
2 answers

From what I can tell, CakePHP magically combines the contents of $_FILES , $_POST , etc., so we get access to each of $this->request->data[...] . And you can pass information to this data array with an additional second parameter:

 $data = [ 'csvfile' => [ 'tmp_name' => '/home/path/to/tests/Fixture/csv/test.csv', 'name' => 'test.csv', 'type' => 'text/csv', 'size' => 45, 'error' => 0, ], ]; $this->post('/foo/bar', $data); 
0
source

Erupting the basic functions of PHP is a bit more complicated.

I think you have something similar in your message model.

 public function processFile($file) { if (is_uploaded_file($file)) { //process the file return true; } return false; } 

And you have an appropriate test like this.

 public function testProcessFile() { $actual = $this->Posts->processFile('noFile'); $this->assertTrue($actual); } 

Since you are not loading anything during the test process, the test always fails.

You must add a second namespace at the beginning of your PostsTableTest.php, even having more namespaces in a single file is bad practice.

 <?php namespace { // This allows us to configure the behavior of the "global mock" // by changing its value you switch between the core PHP function and // your implementation $mockIsUploadedFile = false; } 

Than you should have your original namespace declaration in curly braces.

 namespace App\Model\Table { 

And you can add a basic PHP method to overwrite

 function is_uploaded_file() { global $mockIsUploadedFile; if ($mockIsUploadedFile === true) { return true; } else { return call_user_func_array('\is_uploaded_file',func_get_args()); } } //other model methods } //this closes the second namespace declaration 

Read more about testing the CakePHP module here: http://www.apress.com/9781484212134

+1
source

All Articles