У меня есть следующий класс в файле, расположенном в ./src/PCMagas/Dropbox.php
.что мне нужно проверить это:
namespace PCMagas;
define("API_OAUTH_TOKEN_URL","https://api.dropboxapi.com/oauth2/token");
use \GuzzleHttp\Client;
use \GuzzleHttp\RequestOptions;
class Dropbox
{
/**
* @param String $appid The Dropbox Application Id.
* @param String $secret The dropbox Secret
* @param Client $httpClient The interface used to consume the Dropbox Rest API
*/
public function __construct($appId,$secret,Client $httpClient)
{
$this->appId=$appId;
$this->secret=$secret;
$this->httpClient=$httpClient;
}
/**
* Common Logic for Handling Http Error
* @param Integer $code
* @throws Exception
*/
private function httpErrorHandling($code)
{
switch($code){
case 400:
throw new Exception('Invalid HttpRequest to DropBoxApi');
case 401:
throw new Exception('Invalid Dropbox Token');
case 403:
throw new Exception('Access Denied');
case 429:
throw new Exception('Try again later (after a 10th cup of coffee)');
case 409:
throw new Exception('Api user provided error');
//Treat all 500 error code (seems kinda ugly)
case 500:
case 501:
case 502:
case 503:
case 504:
case 505:
case 506:
case 507:
case 508:
case 510:
case 511:
throw new Exception('Internal Dropbox Error');
}
}
/**
* @param String $code
* @return String
* @throws InvalidArgumentException In case that the code is not correctly Provided.
* @throws Exception if any error occured when token cannot be fetched
*/
public function getToken($code)
{
//If code get token from code
//Else get token from $session
//Not satisfiable thows Esception
session_start();
if(!empty($_SESSION['token'])){
return $_SESSION['token'];
}
if(empty($code)){
throw new \InvalidArgumentException('Please provide a code fetched from Dropbox Athorization.');
}
if(empty($_SESSION['redirect_url'])){
throw new \Exception('Cannot find the url that Dropbox Redirected From');
}
$response = $this->httpClient->request("POST",API_OAUTH_TOKEN_URL,[
RequestOptions::FORM_PARAMS =>[
'code'=>$code,
'grant_type'=>'authorization_code',
'redirect_uri'=>$_SESSION['redirect_url']
],
RequestOptions::AUTH=>[$this->appId,$this->secret]
]);
//Call method and let it blow up
$this->httpErrorHandling($response->getStatusCode());
$body=$response->getBody()->getContents();
$body=json_decode($body,true);
$_SESSION['token']=$body['access_token'];
return $_SESSION['token'];
}
}
Затем я пытаюсь провести модульное тестирование метода getToken
вот так (файл находится в ./tests/DropBoxTest.php
:
namespace PCMagas\Tests;
use PHPUnit\Framework\TestCase;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Client;
use PCMagas\Dropbox;
define('ERROR_CODES',[400,401,403,409,429,500,501,502,503,504,505,506,507,508,510,511]);
define('ERROR_CODE_LENGTH',count(ERROR_CODES));
final class DropBoxTest extends TestCase
{
private function mockErrorGuzzle()
{
$responses=array_map(function($statusCode){
return new Response($statusCode);
},ERROR_CODES);
$handler = new MockHandler($responses);
$client = new Client(['handler'=>$handler]);
return $client;
}
public function testHttpErrorOnTonenFetch()
{
$guzzle=$this->mockErrorGuzzle();
$dropBox=new Dropbox("dummyappId","dummySecret",$guzzle);
for($i=0;$i<ERROR_CODE_LENGTH;$i++) {
$this->expectException(\Exception::class);
$dropBox->getToken("dummyCode");
}
}
}
Моя файловая структура:
|- src
|-- PCMagas
|---- Dropvox.php
|- tests
|-- DropBoxTest.php
И мой phpunit.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupStaticAttributes="false"
bootstrap="./vendor/autoload.php"
cacheTokens="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
forceCoversAnnotation="false"
mapTestClassNameToCoveredClassName="false"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
verbose="false">
<testsuites>
<testsuite name="Application Unit Tests">
<directory>./tests</directory>
</testsuite>
</testsuites>
</phpunit>
В то время как мой composer.json
имеет следующий вход:
{
"require": {
"guzzlehttp/guzzle": "~6.0",
},
"require-dev": {
"phpunit/phpunit": "~6.0",
"laravel/homestead": "^7.20"
},
"autoload": {
"psr-4":{
"PCMagas\\": "src/PCMagas"
}
},
"autoload-dev": {
"psr-4": { "PCMagas\\Tests\\": "tests/" }
}
}
Но когда я пытаюсьЗапустив модульный тест, я получаю следующую ошибку:
Время: 621 мс, Память: 4,00 МБ
Произошла 1 ошибка:
1) PCMagas \ Tests\ DropBoxTest :: testHttpErrorOnTonenFetch session_start (): не удается запустить сеанс, когда заголовки уже отправлены
/ home / vagrant / code / src / PCMagas / Dropbox.php: 84 /home/vagrant/code/tests/DropBoxTest.php: 36
Знаете ли вы, как исправить эту ошибку?