2015-02-10 49 views
4

我想測試文件上傳的restful API測試。將文件發送到代碼中的Restful服務

我嘗試運行:

$I->sendPOST($this->endpoint, $postData, ['file' => 'example.jpg']); 

,我想它作爲用戶發送example.jpg文件中的文件輸入與名file行爲相同,但它似乎並沒有這樣的工作方式。我得到:

[PHPUnit_Framework_ExceptionWrapper]上傳的文件必須是一個數組或UploadedFile的一個實例。

是否有可能在codeception使用REST插件上傳文件?文檔非常有限,很難說如何去做。

我也在測試API使用Postman插件Google Chrome和我可以上傳文件沒有問題使用此插件。

回答

2

測試後,它似乎讓它工作,我們需要使用UploadedFile對象文件。

例如:

$path = codecept_data_dir(); 
$filename = 'example-image.jpg'; 

// copy original test file to have at the same place after test 
copy($path . 'example.jpg', $path . $filename); 

$mime = 'image/jpeg'; 

$uploadedFile = new \Symfony\Component\HttpFoundation\File\UploadedFile($path . $filename, $filename, $mime, 
    filesize($path . $filename)); 

$I->sendPOST($this->endpoint, $postData, ['file' => $uploadedFile]); 
+0

這是工作,但不可能得到與$請求 - 創建的文件>文件(「文件」);方法在控制器中。我可以通過$ request-> get('file')得到它,這不是一個正確的行爲。你如何管理呢? – Okipa 2016-03-09 10:19:16

9

我同樣的問題最近掙扎,發現有另一種方式來解決問題,而無需使用的Symfony的UploadedFile的類。您只需要以與$ _FILES數組相同的格式傳遞文件數據。例如,此代碼的工作非常適合我:

$I->sendPOST(
    '/my-awesome-api', 
    [ 
     'sample-field' => 'sample-value', 
    ], 
    [ 
     'myFile' => [ 
      'name' => 'myFile.jpg', 
      'type' => 'image/jpeg', 
      'error' => UPLOAD_ERR_OK, 
      'size' => filesize(codecept_data_dir('myFile.jpg')), 
      'tmp_name' => codecept_data_dir('myFile.jpg'), 
     ] 
    ] 
); 

希望這可以幫助別人,並從檢查框架的源代碼阻止(我是被迫這樣做,因爲文檔跳過這樣一個重要的細節)

+0

我覺得這個比接受的答案要好,因爲你不需要使用Symfony! – cwhsu 2016-03-17 09:32:45

+1

很可能docs不會再是一個問題了:) https://github.com/Codeception/Codeception/pull/4151 – igorsantos07 2017-04-20 03:11:40

1

['file' => 'example.jpg']格式也適用,但該值必須是現有文件的正確路徑。

$path = codecept_data_dir(); 
$filename = 'example-image.jpg'; 

// copy original test file to have at the same place after test 
copy($path . 'example.jpg', $path . $filename); 

$I->sendPOST($this->endpoint, $postData, ['file' => $path . $filename]); 
0

下工作了我自己,

在服務器:

$uploadedResume= $_FILES['resume_uploader']; 
$outPut = []; 

     if (isset($uploadedResume) && empty($uploadedResume['error'])) { 
      $uploadDirectory = 'uploads/users/' . $userId . '/documents/'; 
      if (!is_dir($uploadDirectory)) { 
       @mkdir($uploadDirectory, 0777, true); 
      } 

      $ext = explode('.', basename($uploadedResume['name'])); 
      $targetPath = $uploadDirectory . md5(uniqid()) . '.' . end($ext); 

      if (move_uploaded_file($uploadedResume['tmp_name'], $targetPath)) { 
       $outPut[] = ['success' => 'success', 'uploaded_path' => $targetPath]; 
      } 
     } 
return json_encode($output); 

對不起,長的描述代碼:P

在測試方面:

//resume.pdf is copied in to tests/_data directory 
$I->sendPOST('/student/resume', [], ['resume_uploader' => codecept_data_dir('resume.pdf') ]); 
0

@ Yaronius的答案WER爲我工作後,我刪除從我的試驗中,以下標題:

$I->haveHttpHeader('Content-Type', 'multipart/form-data');

相關問題