using CloudNative.CloudEvents;
using Google.Cloud.Functions.Testing;
using Google.Events;
using Google.Events.Protobuf.Cloud.Storage.V1;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace HelloWorld.Tests
{
public class HelloGcsUnitTest
{
[Fact]
public async Task FileNameIsLogged()
{
// Prepare the inputs
var data = new StorageObjectData { Name = "new-file.txt" };
var cloudEvent = new CloudEvent
{
Type = StorageObjectData.FinalizedCloudEventType,
Source = new Uri("//storage.googleapis.com", UriKind.RelativeOrAbsolute),
Id = "1234",
Data = data
};
var logger = new MemoryLogger<HelloGcs.Function>();
// Execute the function
var function = new HelloGcs.Function(logger);
await function.HandleAsync(cloudEvent, data, CancellationToken.None);
// Check the log results - just the entry starting with "File:".
var logEntry = Assert.Single(logger.ListLogEntries(), entry => entry.Message.StartsWith("File:"));
Assert.Equal("File: new-file.txt", logEntry.Message);
Assert.Equal(LogLevel.Information, logEntry.Level);
}
}
}
namespace Google\Cloud\Samples\Functions\HelloworldStorage\Test;
use CloudEvents\V1\CloudEventImmutable;
use CloudEvents\V1\CloudEventInterface;
use PHPUnit\Framework\TestCase;
/**
* Class SampleUnitTest.
*
* Unit test for 'Helloworld Storage' Cloud Function.
*/
class SampleUnitTest extends TestCase
{
/**
* Include the Cloud Function code before running any tests.
*
* @see https://phpunit.readthedocs.io/en/latest/fixtures.html
*/
public static function setUpBeforeClass(): void
{
require_once __DIR__ . '/index.php';
}
public function dataProvider()
{
return [
[
'cloudevent' => new CloudEventImmutable(
uniqId(), // id
'storage.googleapis.com', // source
'google.cloud.storage.object.v1.finalized', // type
[
'bucket' => 'some-bucket',
'metageneration' => '1',
'name' => 'folder/friendly.txt',
'timeCreated' => '2020-04-23T07:38:57.230Z',
'updated' => '2020-04-23T07:38:57.230Z',
] // data
),
'statusCode' => '200',
],
];
}
/**
* @dataProvider dataProvider
*/
public function testFunction(CloudEventInterface $cloudevent): void
{
// Capture function output by overriding the function's logging behavior.
// The 'LOGGER_OUTPUT' environment variable must be used in your function:
//
// $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
// fwrite($log, 'Log Entry');
putenv('LOGGER_OUTPUT=php://output');
helloGCS($cloudevent);
// Provided by PHPUnit\Framework\TestCase.
$actual = $this->getActualOutput();
// Test output includes the properties provided in the CloudEvent.
foreach ($cloudevent->getData() as $property => $value) {
$this->assertStringContainsString($value, $actual);
}
$this->assertStringContainsString($cloudevent->getId(), $actual);
$this->assertStringContainsString($cloudevent->getType(), $actual);
}
}