From f2242152f4e090c7774fba459642f6ef32c75e61 Mon Sep 17 00:00:00 2001 From: nickbahson Date: Mon, 6 Mar 2023 09:24:51 +0300 Subject: [PATCH] added tests for some upload files util methods --- README.md | 104 ++++++++++++++------------ composer.json | 8 +- example.phpunit.xml | 15 ++++ src/Clients/BackblazeClient.php | 106 ++++++++++++++------------- src/Clients/HttpClient.php | 6 +- tests/Unit/BackblazeClientTest.php | 113 +++++++++++++++++++++++++++++ tests/Unit/HttpClientTest.php | 22 ++++++ 7 files changed, 273 insertions(+), 101 deletions(-) create mode 100644 example.phpunit.xml create mode 100644 tests/Unit/BackblazeClientTest.php create mode 100644 tests/Unit/HttpClientTest.php diff --git a/README.md b/README.md index 37c9b6a..87bdf0e 100644 --- a/README.md +++ b/README.md @@ -31,56 +31,68 @@ $this->b2Client = new BackblazeClient($b2_configs); * Uploading small files. ```php - // Steps - // Authorize requests - // Get the upload url + the authorizationToken - // Upload the file (b2_upload_file) - $b2_auth = $this->b2Client->b2AuthorizeAccount(); - // Required from b2_auth - $auth_token = $b2_auth->authorizationToken; - $api_url = $b2_auth->apiUrl; - - $file_name = '51863901_1591128994364639_5533062884642328214_n.jpg'; - $key = 'tasks/'. $file_name; - // Assuming your files are stored in the '/uploads/', change to fit your folders. - $local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name; - - $upload_details = $this->b2Client->b2GetUploadUrl($api_url, $auth_token); - $upload_file = $this->b2Client->b2UploadFile($key, $local_file, $upload_details->uploadUrl, $upload_details->authorizationToken); - var_dump($upload_details); - var_dump($upload_file); - die('HERE TOO'); +// Steps + +// Authorize requests + +// Get the upload url + the authorizationToken + +// Upload the file (b2_upload_file) + +$b2_auth = $this->b2Client->b2AuthorizeAccount(); + +// Required from b2_auth + +$auth_token = $b2_auth->authorizationToken; + +$api_url = $b2_auth->apiUrl; + + +$file_name = '51863901_1591128994364639_5533062884642328214_n.jpg'; + +$key = 'a-file-folder/'. $file_name; +// Assuming your files are stored in the '/uploads/', change to fit your folders. + +$local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name; + + +$upload_details = $this->b2Client->b2GetUploadUrl($api_url, $auth_token); + +$upload_file = $this->b2Client->b2UploadFile($key, $local_file, $upload_details->uploadUrl, $upload_details->authorizationToken); + +var_dump($upload_details); + +var_dump($upload_file); + +die('HERE TOO'); ``` * Uploading large files (multipart). ```php - // Steps - // - // - // - $b2_auth = $this->b2Client->b2AuthorizeAccount(); - // Required from b2_auth - $auth_token = $b2_auth->authorizationToken; - $api_url = $b2_auth->apiUrl; - - $file_name = 'BULLET TRAIN - Official Trailer (HD).mp4'; - $key = 'tasks/'. $file_name; - // Assuming your files are stored in the '/uploads/', change to fit your folders. - $local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name; - - $start_upload_file = $this->b2Client->b2StartLargeFile($api_url, $auth_token, $key); - $fileId = $start_upload_file->fileId; - - // From here, you can save the values required in b2UploadChunks($local_file, $auth_token, $api_url, $fileId); - // below, and later fire that action via a cron job, to make content editing easier (take less time) maybe. - - // upload chuncks - $large_upload_res = $this->b2Client->b2UploadChunks($local_file, $auth_token, $api_url, $fileId); - // Delete local file maybe - // unlink( $local_file ); - - var_dump($large_upload_res); - die('DONE for a large file'); +// Steps +// +// +// +$b2_auth = $this->b2Client->b2AuthorizeAccount(); +// Required from b2_auth +$auth_token = $b2_auth->authorizationToken; +$api_url = $b2_auth->apiUrl; + +$file_name = 'BULLET TRAIN - Official Trailer (HD).mp4'; +$key = 'a-folder/'. $file_name; +// Assuming your files are stored in the '/uploads/', change to fit your folders. +$local_file = dirname(__DIR__, 1) . '/uploads/'. $file_name; + +$start_upload_file = $this->b2Client->b2StartLargeFile($api_url, $auth_token, $key); +$fileId = $start_upload_file->fileId// From here, you can save the values required in b2UploadChunks($local_file, $auth_token, $api_url, $fileId); +// below, and later fire that action via a cron job, to make content editing easier (take less time) maybe. + +// upload chunks +$large_upload_res = $this->b2Client->b2UploadChunks($local_file, $auth_token, $api_url, $fileId); +// Delete local file maybe +// unlink( $local_file ); +var_dump($large_upload_res); +die('DONE for a large file'); ``` \ No newline at end of file diff --git a/composer.json b/composer.json index c7d7c0c..8744aae 100644 --- a/composer.json +++ b/composer.json @@ -13,6 +13,11 @@ "Flaircore\\Backblaze\\": "src/" } }, + "autoload-dev": { + "psr-4": { + "Flaircore\\Backblaze\\Tests": "tests/" + } + }, "authors": [ { "name": "Nicholas Njogu", @@ -25,6 +30,7 @@ "ext-json": "*" }, "require-dev": { - "monolog/monolog": "^3.3" + "monolog/monolog": "^3.3", + "phpunit/phpunit": "^10.0" } } diff --git a/example.phpunit.xml b/example.phpunit.xml new file mode 100644 index 0000000..37496aa --- /dev/null +++ b/example.phpunit.xml @@ -0,0 +1,15 @@ + + + + + tests/Unit + + + + + + + + \ No newline at end of file diff --git a/src/Clients/BackblazeClient.php b/src/Clients/BackblazeClient.php index c58a18f..bc491df 100644 --- a/src/Clients/BackblazeClient.php +++ b/src/Clients/BackblazeClient.php @@ -50,8 +50,8 @@ final public function b2ListUnfinishedLargeFiles($api_url, $account_auth_token){ * @throws \Exception */ final public function b2AuthorizeAccount(){ - $application_key_id = B2_API_KEY; - $application_key = B2_API_SECRET; + $application_key_id = $this->b2Configs['B2_API_KEY']; + $application_key = $this->b2Configs['B2_API_SECRET']; $credentials = base64_encode($application_key_id . ":" . $application_key); $url = self::BASE_URL ."b2_authorize_account"; @@ -78,51 +78,6 @@ final public function b2AuthorizeAccount(){ } } - /** - * @param $api_url - * @param $auth_token - * @param $key - * The file name of the file to be uploaded - * - * @return mixed - * @throws \Exception - */ - final public function b2StartLargeFile($api_url, $auth_token, $key) { - // The content type of the file. See b2_start_large_file documentation for more information. - $content_type = "b2/x-auto"; - - // Provided by b2_create_bucket, b2_list_buckets - $bucket_id = $this->b2Configs['B2_BUCKET_ID']; - - // Construct the JSON to post - $data = array("fileName" => $key, "bucketId" => $bucket_id, "contentType" => $content_type); - $post_fields = json_encode($data); - $headers = [ - 'Accept' => 'application/json', - 'Authorization' => [$auth_token] - ]; - - try { - $client = $this->client(); - $res = $client->postAsync($api_url . "/b2api/v2/b2_start_large_file", [ - 'headers' => $headers, - 'body' => $post_fields, - ] - )->wait(); - - if ($res->getStatusCode() == 200) { - - return json_decode($res->getBody()); - } else { - throw new \Exception("Error making request ". $res->getBody()); - } - - } catch (\Throwable $ex) { - throw new \Exception("Error making request ". $ex->getMessage()); - } - - } - /** * Gets an URL to use for uploading files. * https://www.backblaze.com/b2/docs/b2_get_upload_url.html @@ -208,7 +163,7 @@ final public function b2GetUploadPartUrl($api_url, $auth_token, $file_id) { * * @return mixed */ - final public function b2UploadFile($file_name, $local_file, $upload_url, $upload_auth_token, ) { + final public function b2UploadFile($file_name, $local_file, $upload_url, $upload_auth_token ) { $client = $this->client(); @@ -241,6 +196,56 @@ final public function b2UploadFile($file_name, $local_file, $upload_url, $upload } + /** + * @param $api_url + * @param $auth_token + * @param $key + * The file name of the file to be uploaded + * + * @return mixed + * @throws \Exception + */ + final public function b2StartLargeFile($api_url, $auth_token, $key) { + // The content type of the file. See b2_start_large_file documentation for more information. + $content_type = "b2/x-auto"; + + // Provided by b2_create_bucket, b2_list_buckets + $bucket_id = $this->b2Configs['B2_BUCKET_ID']; + + // Construct the JSON to post + $data = [ + "fileName" => $key, + "bucketId" => $bucket_id, + "contentType" => $content_type + ]; + + $post_fields = json_encode($data); + $headers = [ + 'Accept' => 'application/json', + 'Authorization' => [$auth_token] + ]; + + try { + $client = $this->client(); + $res = $client->postAsync($api_url . "/b2api/v2/b2_start_large_file", [ + 'headers' => $headers, + 'body' => $post_fields, + ] + )->wait(); + + if ($res->getStatusCode() == 200) { + + return json_decode($res->getBody()); + } else { + throw new \Exception("Error making request ". $res->getBody()); + } + + } catch (\Throwable $ex) { + throw new \Exception("Error making request ". $ex->getMessage()); + } + + } + /** * Uploads chucks as well as finish the upload. * https://www.backblaze.com/b2/docs/b2_upload_part.html @@ -331,10 +336,10 @@ final public function b2UploadChunks($local_file, $auth_token, $api_url, $file_i // Finish the upload - $data = array( + $data = [ "fileId" => $file_id, "partSha1Array" => $sha1_of_parts - ); + ]; $headers = [ 'Accept' => 'application/json', @@ -364,4 +369,5 @@ private function curlReadFile($curl_rsrc, $file_pointer, $length) { return fread($file_pointer, $length); } + } \ No newline at end of file diff --git a/src/Clients/HttpClient.php b/src/Clients/HttpClient.php index 9348761..7bc9ec5 100644 --- a/src/Clients/HttpClient.php +++ b/src/Clients/HttpClient.php @@ -12,8 +12,6 @@ trait HttpClient { private $MAX_RETRIES = 5; - private $BASE_URL = 'https://api.backblazeb2.com/b2api/v2/'; - /** * @var Client */ @@ -46,8 +44,8 @@ public function __construct() { $stack->push(Middleware::retry($decider, $delay)); $this->httpClient = new Client([ - 'base_uri' => 'https://api.backblazeb2.com/b2api/v2/', - //'handler' => $stack, + //'base_uri' => 'https://api.backblazeb2.com/b2api/v2/', + 'handler' => $stack, ]); } diff --git a/tests/Unit/BackblazeClientTest.php b/tests/Unit/BackblazeClientTest.php new file mode 100644 index 0000000..8806cf8 --- /dev/null +++ b/tests/Unit/BackblazeClientTest.php @@ -0,0 +1,113 @@ +b2Client = $this->createMock(BackblazeClient::class); + } + + protected function tearDown(): void { + parent::tearDown(); // TODO: Change the autogenerated stub + } + + public function testb2AuthorizeAccount(){ + $mockResponse = json_encode([ + 'authorizationToken' => 'A token', + 'apiUrl' => 'https://an-api-url', + ]); + + // Create a mock and queue just a response. + $mock = new MockHandler([ + function ($request) use ($mockResponse) { + // Assert method and headers + $this->assertEquals('GET', $request->getMethod()); + $this->assertArrayHasKey('Authorization', $request->getHeaders()); + return new Response( + 200, + [], + $mockResponse + ); + }, + ]); + + $handlerStack = HandlerStack::create($mock); + + $client = new Client(['handler' => $handlerStack]); + + $this->b2Client->method('client')->willReturn($client); + $this->b2Client->b2AuthorizeAccount(); + + } + + public function testb2GetUploadUrl(){ + $mockResponse = json_encode([ + 'authorizationToken' => 'A token', + 'apiUrl' => 'https://an-api-url', + ]); + + // Create a mock and queue just a response. + $mock = new MockHandler([ + function ($request) use ($mockResponse) { + // Assert method, headers and data posted bt b2GetUploadUrl method. + $this->assertEquals('POST', $request->getMethod()); + $this->assertArrayHasKey('Authorization', $request->getHeaders()); + $this->assertArrayHasKey('bucketId', json_decode($request->getBody(), true)); + return new Response( + 200, + [], + $mockResponse + ); + }, + ]); + + $handlerStack = HandlerStack::create($mock); + $client = new Client(['handler' => $handlerStack]); + $this->b2Client->method('client')->willReturn($client); + $this->b2Client->b2GetUploadUrl('the_api_url', 'the_auth_token'); + + } + + public function testb2GetUploadPartUrl(){ + $fileId = 'the_file_id'; + $mockResponse = json_encode([ + 'authorizationToken' => 'A token', + 'apiUrl' => 'https://an-api-url', + ]); + + // Create a mock and queue just a response. + $mock = new MockHandler([ + function ($request) use ($mockResponse, $fileId) { + // Assert method, headers and data posted bt b2GetUploadPartUrl method. + $this->assertEquals('POST', $request->getMethod()); + $this->assertArrayHasKey('Authorization', $request->getHeaders()); + $this->assertEquals(json_decode($request->getBody())->fileId, $fileId); + return new Response( + 200, + [], + $mockResponse + ); + }, + ]); + + $handlerStack = HandlerStack::create($mock); + $client = new Client(['handler' => $handlerStack]); + $this->b2Client->method('client')->willReturn($client); + $this->b2Client->b2GetUploadPartUrl('the_api_url', 'the_auth_token', $fileId); + + } +} \ No newline at end of file diff --git a/tests/Unit/HttpClientTest.php b/tests/Unit/HttpClientTest.php new file mode 100644 index 0000000..45ae2d4 --- /dev/null +++ b/tests/Unit/HttpClientTest.php @@ -0,0 +1,22 @@ +getObjectForTrait(HttpClient::class); + + self::assertIsObject($trait->client()); + self::assertInstanceOf(Client::class, $trait->client()); + } +} \ No newline at end of file