Skip to content

Commit 09f4528

Browse files
author
Ace Nassri
authored
feat(functions): add Pub/Sub test examples (GoogleCloudPlatform#1297)
1 parent 82a3b1e commit 09f4528

File tree

2 files changed

+215
-0
lines changed

2 files changed

+215
-0
lines changed
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
2+
/**
3+
* Copyright 2020 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the 'License');
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an 'AS IS' BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
declare(strict_types=1);
19+
20+
// [START functions_pubsub_integration_test]
21+
22+
namespace Google\Cloud\Samples\Functions\HelloworldPubsub;
23+
24+
use Google\CloudFunctions\CloudEvent;
25+
use GuzzleHttp\Client;
26+
use PHPUnit\Framework\TestCase;
27+
use Symfony\Component\Process\Process;
28+
use Symfony\Component\Process\PhpExecutableFinder;
29+
30+
/**
31+
* Class SampleIntegrationTest.
32+
*
33+
* Integration tests for the 'Helloworld Pubsub' Cloud Function.
34+
*/
35+
class SampleIntegrationTest extends TestCase
36+
{
37+
/** @var Process */
38+
private static $process;
39+
40+
/** @var Client */
41+
private static $client;
42+
43+
public function dataProvider()
44+
{
45+
return [
46+
[
47+
'cloudevent' => CloudEvent::fromArray([
48+
'id' => uniqid(),
49+
'source' => 'pubsub.googleapis.com',
50+
'specversion' => '1.0',
51+
'type' => 'google.cloud.pubsub.topic.v1.messagePublished',
52+
]),
53+
'data' => [
54+
'data' => base64_encode('John')
55+
],
56+
'expected' => 'Hello, John!'
57+
],
58+
];
59+
}
60+
61+
/**
62+
* Start a local PHP server running the Functions Framework.
63+
*
64+
* @beforeClass
65+
*/
66+
public static function startFunctionFramework(): void
67+
{
68+
$port = getenv('PORT') ?: '8080';
69+
$php = (new PhpExecutableFinder())->find();
70+
$uri = 'localhost:' . $port;
71+
72+
// https://symfony.com/doc/current/components/process.html#usage
73+
self::$process = new Process([$php, '-S', $uri, 'vendor/bin/router.php'], null, [
74+
'FUNCTION_SIGNATURE_TYPE' => 'cloudevent',
75+
'FUNCTION_TARGET' => 'helloworldPubsub',
76+
]);
77+
self::$process->start();
78+
79+
// Initialize an HTTP client to drive requests.
80+
self::$client = new Client(['base_uri' => 'http://' . $uri]);
81+
82+
// Short delay to ensure PHP server is ready.
83+
sleep(1);
84+
}
85+
86+
/**
87+
* Stop the local PHP server.
88+
*
89+
* @afterClass
90+
*/
91+
public static function stopFunctionFramework(): void
92+
{
93+
if (!self::$process->isRunning()) {
94+
echo self::$process->getErrorOutput();
95+
throw new RuntimeException('Function Framework PHP process not running by end of test');
96+
}
97+
self::$process->stop(3, SIGTERM);
98+
}
99+
100+
/**
101+
* @dataProvider dataProvider
102+
*/
103+
public function testHelloPubsub(
104+
CloudEvent $cloudevent,
105+
array $data,
106+
string $expected
107+
): void {
108+
// Send an HTTP request using CloudEvent metadata.
109+
$resp = self::$client->post('/', [
110+
'body' => json_encode($data),
111+
'headers' => [
112+
// Instruct the function framework to parse the body as JSON.
113+
'content-type' => 'application/json',
114+
115+
// Prepare the HTTP headers for a CloudEvent.
116+
'ce-id' => $cloudevent->getId(),
117+
'ce-source' => $cloudevent->getSource(),
118+
'ce-specversion' => $cloudevent->getSpecVersion(),
119+
'ce-type' => $cloudevent->getType()
120+
],
121+
]);
122+
123+
// The Cloud Function logs all data to stderr.
124+
$actual = self::$process->getIncrementalErrorOutput();
125+
126+
// Verify the function's results are correctly logged.
127+
$this->assertStringContainsString($expected, $actual);
128+
}
129+
}
130+
131+
// [END functions_pubsub_integration_test]
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
2+
/**
3+
* Copyright 2020 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the 'License');
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an 'AS IS' BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
declare(strict_types=1);
19+
20+
// [START functions_pubsub_unit_test]
21+
22+
namespace Google\Cloud\Samples\Functions\HelloworldPubsub\Test;
23+
24+
use Google\CloudFunctions\CloudEvent;
25+
use PHPUnit\Framework\TestCase;
26+
27+
/**
28+
* Class SampleUnitTest.
29+
*
30+
* Unit test for 'Helloworld Pub/Sub' Cloud Function.
31+
*/
32+
class SampleUnitTest extends TestCase
33+
{
34+
/**
35+
* Include the Cloud Function code before running any tests.
36+
*
37+
* @see https://phpunit.readthedocs.io/en/latest/fixtures.html
38+
*/
39+
public static function setUpBeforeClass(): void
40+
{
41+
require_once __DIR__ . '/index.php';
42+
}
43+
44+
public function dataProvider()
45+
{
46+
return [
47+
[
48+
'cloudevent' => CloudEvent::fromArray([
49+
'id' => uniqid(),
50+
'source' => 'pubsub.googleapis.com',
51+
'specversion' => '1.0',
52+
'type' => 'google.cloud.pubsub.topic.v1.messagePublished',
53+
'data' => [
54+
'data' => base64_encode('John')
55+
],
56+
]),
57+
'expected' => 'Hello, John!'
58+
],
59+
];
60+
}
61+
62+
/**
63+
* @dataProvider dataProvider
64+
*/
65+
public function testFunction(
66+
CloudEvent $cloudevent,
67+
string $expected
68+
): void {
69+
// Capture function output by overriding the function's logging behavior.
70+
// The 'LOGGER_OUTPUT' environment variable must be used in your function:
71+
//
72+
// $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
73+
// fwrite($log, 'Log Entry');
74+
putenv('LOGGER_OUTPUT=php://output');
75+
helloworldPubsub($cloudevent);
76+
// Provided by PHPUnit\Framework\TestCase.
77+
$actual = $this->getActualOutput();
78+
79+
// Test that output includes the expected value.
80+
$this->assertStringContainsString($expected, $actual);
81+
}
82+
}
83+
84+
// [END functions_pubsub_unit_test]

0 commit comments

Comments
 (0)