Including Tests and verifications for errors

This commit is contained in:
Bruno F. Fontes 2019-06-27 20:03:10 -03:00
parent e4f2bd04be
commit aaabb91039
Signed by: brunofontes
GPG Key ID: EE3447CE80048495
10 changed files with 221 additions and 9 deletions

View File

@ -15,4 +15,15 @@ class BaseApi
{ {
$this->fetchApi = $fetchApi; $this->fetchApi = $fetchApi;
} }
protected function hasError(string $jsonResponse): bool
{
return isset(json_decode($jsonResponse, true)['errorCode']);
}
protected function getError(string $jsonResponse): string
{
return json_decode($jsonResponse, true)['errorDescription'];
}
} }

View File

@ -31,12 +31,17 @@ class BilingualFile extends \BrunoFontes\Memsource\BaseApi
public function download(string $projectUid, array $jobUids, string $filename): array public function download(string $projectUid, array $jobUids, string $filename): array
{ {
$url = "/api2/v1/projects/{$projectUid}/jobs/bilingualFile"; $url = "/api2/v1/projects/{$projectUid}/jobs/bilingualFile";
$filenames = [];
$groupedJobUids = array_chunk($jobUids, 100); $groupedJobUids = array_chunk($jobUids, 100);
for ($i = 0; $i < count($groupedJobUids); $i++) { for ($i = 0; $i < count($groupedJobUids); $i++) {
$apiReadyArray = $this->_convertUidArrayToApiRequest($groupedJobUids[$i]); $apiReadyArray = $this->_convertUidArrayToApiRequest($groupedJobUids[$i]);
$filenames[$i] = count($groupedJobUids) > 1 ? "{$i}_{$filename}" : $filename; $filenames[$i] = count($groupedJobUids) > 1 ? "{$i}_{$filename}" : $filename;
$filecontent = $this->fetchApi->fetch('jsonPost', $url, $apiReadyArray); $filecontent = $this->fetchApi->fetch('jsonPost', $url, $apiReadyArray);
if ($this->hasError($filecontent)) {
$errorMsg = $this->getError($filecontent);
throw new \Exception("Error downloading file: {$errorMsg}", 1);
}
$this->_saveIntoFile($filenames[$i], $filecontent); $this->_saveIntoFile($filenames[$i], $filecontent);
} }
return $filenames; return $filenames;
@ -80,10 +85,17 @@ class BilingualFile extends \BrunoFontes\Memsource\BaseApi
public function upload(string $filename, array $params): string public function upload(string $filename, array $params): string
{ {
$urlParams = http_build_query($params); $urlParams = http_build_query($params);
$fileContent = file_get_contents($filename); try {
if ($fileContent === false) { $fileContent = file_get_contents($filename);
throw new \Exception('File for upload inexistent or invalid', 1); } catch (\Exception $e) {
throw new \Exception('File for upload inexistent or invalid: ' . $filename, 1);
} }
return $this->fetchApi->fetch('put', $this->_url . "?{$urlParams}", [$fileContent]);
$response = $this->fetchApi->fetch('put', $this->_url . "?{$urlParams}", [$fileContent]);
if ($this->hasError($response)) {
throw new \Exception("Error uploading file {$filename}: " . $this->getError($response), 1);
}
return $response;
} }
} }

View File

@ -39,30 +39,44 @@ class FetchApi
$setopt = []; $setopt = [];
switch ($method) { switch ($method) {
case 'get': case 'get':
$this->checkAccessToken();
$parameters = http_build_query($parameters); $parameters = http_build_query($parameters);
$url = $url . ($parameters ? '?'.$parameters : ''); $url = $url . ($parameters ? '?'.$parameters : '');
break; break;
case 'put': case 'put':
$this->checkAccessToken();
$setopt = $this->getPutParam()+$this->getPostParam(implode("", $parameters)); $setopt = $this->getPutParam()+$this->getPostParam(implode("", $parameters));
break; break;
case 'post': case 'post':
$this->checkAccessToken();
$parameters = http_build_query($parameters); $parameters = http_build_query($parameters);
$setopt = $setopt + $this->getPostParam($parameters); $setopt = $setopt + $this->getPostParam($parameters);
break; break;
case 'jsonPost': case 'jsonPost':
$this->checkAccessToken();
$setopt = $this->getJsonPostParam($parameters); $setopt = $this->getJsonPostParam($parameters);
break; break;
case 'download': case 'download':
$this->checkAccessToken();
if (empty($filename)) { if (empty($filename)) {
throw new Exception('You need to specify a filename to download a file.', 1); throw new Exception('You need to specify a filename to download a file.', 1);
} }
$setopt = $this->getDownloadFileParam($filename) $setopt = $this->getDownloadFileParam($filename)
+ $this->getJsonPostParam($parameters); + $this->getJsonPostParam($parameters);
break; break;
default:
throw new \Exception("Method {$method} is invalid on Fetch", 1);
} }
return $this->curl($url, $setopt); return $this->curl($url, $setopt);
} }
private function checkAccessToken()
{
if (empty($this->token)) {
throw new \Exception("Missing Access Token", 1);
}
}
private function getDownloadFileParam(string $filename) private function getDownloadFileParam(string $filename)
{ {
return [ return [
@ -98,10 +112,10 @@ class FetchApi
protected function curl(string $url, array $curl_extra_setopt = []) protected function curl(string $url, array $curl_extra_setopt = [])
{ {
if (empty($url)) { if (empty($url)) {
throw new Exception('URL not defined', 1); throw new \Exception('URL not defined', 1);
} }
$header = $this->token ? ["Authorization: Bearer {$this->token}"] : []; $header = ($this->token ? ["Authorization: Bearer {$this->token}"] : []);
$header = array_merge($header, $curl_extra_setopt[CURLOPT_HTTPHEADER]??[]); $header = array_merge($header, $curl_extra_setopt[CURLOPT_HTTPHEADER]??[]);
$curl_setopt = [ $curl_setopt = [
CURLOPT_URL => $this->base_url . $url, CURLOPT_URL => $this->base_url . $url,

View File

@ -23,6 +23,10 @@ class Jobs extends \BrunoFontes\Memsource\BaseApi
public function list(string $projectUid, array $parameters = []): string public function list(string $projectUid, array $parameters = []): string
{ {
$url = "/api2/v2/projects/{$projectUid}/jobs"; $url = "/api2/v2/projects/{$projectUid}/jobs";
return $this->fetchApi->fetch('get', $url, $parameters); $response = $this->fetchApi->fetch('get', $url, $parameters);
if ($this->hasError($response)) {
throw new \Exception("Error listing projects: " . $this->getError($response), 1);
}
return $response;
} }
} }

View File

@ -21,7 +21,11 @@ class Project extends \BrunoFontes\Memsource\BaseApi
*/ */
public function list(array $queryParams = []): string public function list(array $queryParams = []): string
{ {
return $this->fetchApi->fetch('get', $this->_url, $queryParams); $response = $this->fetchApi->fetch('get', $this->_url, $queryParams);
if ($this->hasError($response)) {
throw new \Exception("Error listing projects: " . $this->getError($response), 1);
}
return $response;
} }
/** /**
@ -33,6 +37,9 @@ class Project extends \BrunoFontes\Memsource\BaseApi
*/ */
public function get(string $projectUid): string public function get(string $projectUid): string
{ {
return $this->fetchApi->fetch('get', "{$this->_url}/{$projectUid}"); $response = $this->fetchApi->fetch('get', "{$this->_url}/{$projectUid}");
if ($this->hasError($response)) {
throw new \Exception("Error getting project {$projectUid}: " . $this->getError($response), 1);
}
} }
} }

View File

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class BilingualFileTest extends TestCase
{
public function testEmptyDownloadJobUidListShouldReturnEmptyFilenames()
{
$api = new Memsource('fakeToken');
$this->assertEquals(
[],
$api->bilingualFile()->download('uid', [], 'filename')
);
}
public function testInvalidDownloadUidsShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->bilingualFile()->download('uid', ['a'], 'filename');
}
public function testUploadInexistentFileShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->bilingualFile()->upload('myInvalidFile', []);
}
public function testUploadWithNoTokenShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->bilingualFile()->upload('tests/bilingualFileTest.php', []);
}
}

57
tests/fetchApiTest.php Normal file
View File

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource\FetchApi;
final class FetchApiTest extends TestCase
{
public function testEmptyFetchUrlShouldThrowError()
{
$fetch = new FetchApi('fakeToken', 'https://google.com');
$this->expectExceptionMessage('URL not defined');
$this->assertNotEmpty($fetch->fetch('get', ''));
}
public function testNotEmptyTokenOnFetchShouldNotThrowError()
{
$fetch = new FetchApi('fakeToken', 'https://google.com');
$this->assertNotEmpty($fetch->fetch('get', '/'));
}
public function testEmptyTokenOnFetchRawShouldNotThrowError()
{
$fetch = new FetchApi(null, 'http://google.com');
$this->assertNotEmpty($fetch->fetch('raw', '/'));
}
public function testEmptyTokenOnFetchGetShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('get', 'url');
}
public function testEmptyTokenOnFetchPutShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('put', 'url');
}
public function testEmptyTokenOnFetchPostShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('post', 'url');
}
public function testEmptyTokenOnFetchJsonPostShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('jsonPost', 'url');
}
public function testEmptyTokenOnFetchDownloadShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('download', 'url');
}
}

15
tests/jobsTest.php Normal file
View File

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class JobsTest extends TestCase
{
public function testInvalidProjectUidShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->jobs()->list('invalidProjectUid', []);
}
}

34
tests/oauthTest.php Normal file
View File

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class oauthTest extends TestCase
{
public function testOauthGetAuthorizationCodeUrl()
{
$customServerURL = 'http://myPersonalMemsource.com';
$api = new Memsource(null, $customServerURL);
$expected = $customServerURL . '/oauth/authorize?response_type=code&client_id=id&redirect_uri=http%3A%2F%2Furi&scope=openid';
$memsourceUrl = $api->oauth()->getAuthorizationCodeUrl('id', 'http://uri');
$this->assertEquals(
$expected,
$memsourceUrl
);
}
public function testGetAccessTokenExceptionOnFakeCode()
{
$api = new Memsource();
$this->expectException(\Exception::class);
$token = $api->oauth()->getAccessToken('fakeCode', 'fakeId', 'fakePass', 'http://any');
}
public function testGetAccessTokenExceptionOnEmptyCode()
{
$api = new Memsource();
$this->expectException(\Exception::class);
$token = $api->oauth()->getAccessToken('', '', '', '');
}
}

21
tests/projectTest.php Normal file
View File

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class ProjectTest extends TestCase
{
public function testNoTokenShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->project()->list();
}
public function testInvalidProjectUidShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->project()->get('invalidProjectUid');
}
}