Skip to content

Commit 8b62476

Browse files
authored
fix: better error handling and cleaner testing for imagemagick sample (GoogleCloudPlatform#1341)
1 parent b651c69 commit 8b62476

File tree

4 files changed

+31
-56
lines changed

4 files changed

+31
-56
lines changed

functions/imagemagick/index.php

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,15 @@
2020
use Google\Cloud\Storage\StorageClient;
2121
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
2222
use Google\Cloud\Vision\V1\Likelihood;
23+
use Google\Rpc\Code;
2324

2425
// [END functions_imagemagick_setup]
2526

2627
// [START functions_imagemagick_analyze]
2728
function blurOffensiveImages(CloudEvent $cloudevent): void
2829
{
2930
$log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
31+
3032
$storage = new StorageClient();
3133
$data = $cloudevent->getData();
3234

@@ -38,19 +40,21 @@ function blurOffensiveImages(CloudEvent $cloudevent): void
3840
$storage = new StorageClient();
3941

4042
try {
41-
$request = $annotator->safeSearchDetection($filePath);
42-
$response = $request->getSafeSearchAnnotation();
43+
$response = $annotator->safeSearchDetection($filePath);
4344

44-
// Handle missing files
45-
// (This is uncommon, but can happen if race conditions occur)
46-
if ($response === null) {
47-
fwrite($log, 'Could not find ' . $filePath . PHP_EOL);
45+
// Handle error
46+
if ($response->hasError()) {
47+
$code = Code::name($response->getError()->getCode());
48+
$message = $response->getError()->getMessage();
49+
fwrite($log, sprintf('%s: %s' . PHP_EOL, $code, $message));
4850
return;
4951
}
5052

53+
$annotation = $response->getSafeSearchAnnotation();
54+
5155
$isInappropriate =
52-
$response->getAdult() === Likelihood::VERY_LIKELY ||
53-
$response->getViolence() === Likelihood::VERY_LIKELY;
56+
$annotation->getAdult() === Likelihood::VERY_LIKELY ||
57+
$annotation->getViolence() === Likelihood::VERY_LIKELY;
5458

5559
if ($isInappropriate) {
5660
fwrite($log, 'Detected ' . $data['name'] . ' as inappropriate.' . PHP_EOL);

functions/imagemagick/test/DeployTest.php

Lines changed: 12 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
namespace Google\Cloud\Samples\Functions\ImageMagick\Test;
2121

2222
use Google\Cloud\Storage\StorageClient;
23-
use Google\Cloud\Logging\LoggingClient;
2423
use Google\Cloud\TestUtils\CloudFunctionDeploymentTrait;
2524
use PHPUnit\Framework\TestCase;
2625

@@ -40,31 +39,15 @@ class DeployTest extends TestCase
4039
use CloudFunctionDeploymentTrait;
4140
use TestCasesTrait;
4241

43-
/** @var string */
44-
private static $entryPoint = 'blurOffensiveImages';
45-
46-
/** @var string */
47-
private static $functionSignatureType = 'cloudevent';
48-
49-
/** @var string */
50-
// The test starts by copying images from this bucket.
42+
// The test uses this bucket to copy images.
5143
private const FIXTURE_SOURCE_BUCKET = 'cloud-devrel-public';
5244

53-
/** @var string */
54-
// This is the bucket the deployed function monitors.
55-
// The test copies image from FIXTURE_SOURCE_BUCKET to this one.
45+
/**
46+
* This is the bucket the deployed function monitors.
47+
* The test copies image from FIXTURE_SOURCE_BUCKET to this one.
48+
*/
5649
private static $monitoredBucket;
5750

58-
/** @var string */
59-
// The function saves any blurred images to this bucket.
60-
private static $blurredBucket;
61-
62-
/** @var StorageClient */
63-
private static $storageClient;
64-
65-
/** @var LoggingClient */
66-
private static $loggingClient;
67-
6851
/**
6952
* @dataProvider cases
7053
*/
@@ -75,16 +58,13 @@ public function testFunction(
7558
$expected,
7659
$statusCode
7760
): void {
78-
// Upload target file.
79-
$fixtureBucket = self::$storageClient->bucket(self::FIXTURE_SOURCE_BUCKET);
80-
$object = $fixtureBucket->object($fileName);
61+
// Trigger the cloud storage event by copying the image over
62+
$storageClient = new StorageClient();
63+
$fixtureBucket = $storageClient->bucket(self::FIXTURE_SOURCE_BUCKET);
8164

65+
$object = $fixtureBucket->object($fileName);
8266
$object->copy(self::$monitoredBucket, ['name' => $fileName]);
8367

84-
// Give event and log systems a head start.
85-
// If log retrieval fails to find logs for our function within retry limit, increase sleep time.
86-
sleep(5);
87-
8868
$fiveMinAgo = date(\DateTime::RFC3339, strtotime('-5 minutes'));
8969
$this->processFunctionLogs($fiveMinAgo, function (\Iterator $logs) use ($expected, $label) {
9070
// Concatenate all relevant log messages.
@@ -108,20 +88,11 @@ public function testFunction(
10888
private static function doDeploy()
10989
{
11090
// Initialize variables
111-
if (empty(self::$monitoredBucket)) {
112-
self::$monitoredBucket = self::requireEnv('GOOGLE_STORAGE_BUCKET');
113-
}
114-
if (empty(self::$blurredBucket)) {
115-
self::$blurredBucket = self::requireEnv('BLURRED_BUCKET_NAME');
116-
}
117-
118-
if (empty(self::$storageClient)) {
119-
self::$storageClient = new StorageClient();
120-
}
91+
self::$monitoredBucket = self::requireEnv('GOOGLE_STORAGE_BUCKET');
92+
$blurredBucket = self::requireEnv('BLURRED_BUCKET_NAME');
12193

12294
// Forward required env variables to Cloud Functions.
123-
$envVars = 'GOOGLE_STORAGE_BUCKET=' . self::$monitoredBucket . ',';
124-
$envVars .= 'BLURRED_BUCKET_NAME=' . self::$blurredBucket;
95+
$envVars = sprintf('BLURRED_BUCKET_NAME=%s', $blurredBucket);
12596

12697
self::$fn->deploy(
12798
['--update-env-vars' => $envVars],

functions/imagemagick/test/IntegrationTest.php

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,6 @@ class IntegrationTest extends TestCase
3333
use CloudFunctionLocalTestTrait;
3434
use TestCasesTrait;
3535

36-
/** @var string */
37-
private static $entryPoint = 'blurOffensiveImages';
38-
39-
/** @var string */
40-
private static $functionSignatureType = 'cloudevent';
41-
4236
/**
4337
* @dataProvider cases
4438
* @dataProvider integrationCases

functions/imagemagick/test/TestCasesTrait.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ trait TestCasesTrait
2525
{
2626
use TestTrait;
2727

28+
/** @var string */
29+
private static $entryPoint = 'blurOffensiveImages';
30+
31+
/** @var string */
32+
private static $functionSignatureType = 'cloudevent';
33+
2834
public static function getDataForFile($fileName): array
2935
{
3036
return [
@@ -90,7 +96,7 @@ public static function integrationCases(): array
9096
'label' => 'Labels missing images as safe',
9197
'filename' => 'does-not-exist.jpg',
9298
'expected' => sprintf(
93-
'Could not find gs://%s/does-not-exist.jpg',
99+
'NOT_FOUND: Error opening file: gs://%s/does-not-exist.jpg',
94100
$bucketName
95101
),
96102
'statusCode' => '200'

0 commit comments

Comments
 (0)