Tests unitaires Cloud Pub/Sub (2e génération)
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Exemple de test unitaire pour une fonction déclenchée par Cloud Pub/Sub qui s'exécute dans Cloud Functions (2e génération).
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis webpage provides unit test examples for Cloud Pub/Sub-triggered functions running on Cloud Functions (2nd Gen) in C#, Go, and PHP.\u003c/p\u003e\n"],["\u003cp\u003eThe C# code demonstrates testing a function that processes messages with and without text data, using \u003ccode\u003eXunit\u003c/code\u003e for assertions and a \u003ccode\u003eMemoryLogger\u003c/code\u003e for logging checks.\u003c/p\u003e\n"],["\u003cp\u003eThe Go example showcases testing \u003ccode\u003ehelloPubSub\u003c/code\u003e function with varying input data, by capturing the log output, and it utilizes the \u003ccode\u003ecloudevents\u003c/code\u003e library to simulate CloudEvents.\u003c/p\u003e\n"],["\u003cp\u003eThe PHP unit tests use \u003ccode\u003ePHPUnit\u003c/code\u003e to test the \u003ccode\u003ehelloworldPubsub\u003c/code\u003e function by simulating a CloudEvent and asserting that the function's output contains the expected greeting, handling output capture by overriding the function's logging.\u003c/p\u003e\n"],["\u003cp\u003eSetting up Application Default Credentials is required for authenticating to Cloud Run functions during local development, and a link is provided for more details on the process.\u003c/p\u003e\n"]]],[],null,["Example unit test for a Cloud Pub/Sub-triggered function running on Cloud Functions (2nd Gen).\n\nCode sample \n\nC#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using CloudNative.CloudEvents;\n using Google.Cloud.Functions.Testing;\n using Google.Events.Protobuf.Cloud.PubSub.V1;\n using Microsoft.Extensions.Logging;\n using System;\n using System.Threading;\n using System.Threading.Tasks;\n using Xunit;\n\n namespace HelloWorld.Tests;\n\n public class HelloPubSubUnitTest\n {\n [Fact]\n public async Task MessageWithTextData()\n {\n var data = new MessagePublishedData { Message = new PubsubMessage { TextData = \"PubSub user\" } };\n var cloudEvent = new CloudEvent\n {\n Type = MessagePublishedData.MessagePublishedCloudEventType,\n Source = new Uri(\"//pubsub.googleapis.com\", UriKind.RelativeOrAbsolute),\n Id = Guid.NewGuid().ToString(),\n Time = DateTimeOffset.UtcNow,\n Data = data\n };\n\n var logger = new MemoryLogger\u003cHelloPubSub.Function\u003e();\n var function = new HelloPubSub.Function(logger);\n await function.HandleAsync(cloudEvent, data, CancellationToken.None);\n\n var logEntry = Assert.Single(logger.ListLogEntries());\n Assert.Equal(\"Hello PubSub user\", logEntry.Message);\n Assert.Equal(LogLevel.Information, logEntry.Level);\n }\n\n [Fact]\n public async Task MessageWithoutTextData()\n {\n var data = new MessagePublishedData\n {\n Message = new PubsubMessage { Attributes = { { \"key\", \"value\" } } }\n };\n var cloudEvent = new CloudEvent\n {\n Type = MessagePublishedData.MessagePublishedCloudEventType,\n Source = new Uri(\"//pubsub.googleapis.com\", UriKind.RelativeOrAbsolute),\n Id = Guid.NewGuid().ToString(),\n Time = DateTimeOffset.UtcNow\n };\n\n var logger = new MemoryLogger\u003cHelloPubSub.Function\u003e();\n var function = new HelloPubSub.Function(logger);\n await function.HandleAsync(cloudEvent, data, CancellationToken.None);\n\n var logEntry = Assert.Single(logger.ListLogEntries());\n Assert.Equal(\"Hello world\", logEntry.Message);\n Assert.Equal(LogLevel.Information, logEntry.Level);\n }\n }\n\nGo\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n package helloworld\n\n import (\n \t\"context\"\n \t\"io\"\n \t\"log\"\n \t\"os\"\n \t\"testing\"\n\n \t\"github.com/cloudevents/sdk-go/v2/event\"\n )\n\n func TestHelloPubSub(t *testing.T) {\n \ttests := []struct {\n \t\tdata string\n \t\twant string\n \t}{\n \t\t{want: \"Hello, World!\\n\"},\n \t\t{data: \"Go\", want: \"Hello, Go!\\n\"},\n \t}\n \tfor _, test := range tests {\n \t\tr, w, _ := os.Pipe()\n \t\tlog.SetOutput(w)\n \t\toriginalFlags := log.Flags()\n \t\tlog.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime))\n\n \t\tm := PubSubMessage{\n \t\t\tData: []byte(test.data),\n \t\t}\n \t\tmsg := MessagePublishedData{\n \t\t\tMessage: m,\n \t\t}\n \t\te := event.New()\n \t\te.SetDataContentType(\"application/json\")\n \t\te.SetData(e.DataContentType(), msg)\n\n \t\thelloPubSub(context.Background(), e)\n\n \t\tw.Close()\n \t\tlog.SetOutput(os.Stderr)\n \t\tlog.SetFlags(originalFlags)\n\n \t\tout, err := io.ReadAll(r)\n \t\tif err != nil {\n \t\t\tt.Fatalf(\"ReadAll: %v\", err)\n \t\t}\n \t\tif got := string(out); got != test.want {\n \t\t\tt.Errorf(\"HelloPubSub(%q) = %q, want %q\", test.data, got, test.want)\n \t\t}\n \t}\n }\n\nPHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n namespace Google\\Cloud\\Samples\\Functions\\HelloworldPubsub\\Test;\n\n use CloudEvents\\V1\\CloudEventImmutable;\n use CloudEvents\\V1\\CloudEventInterface;\n use PHPUnit\\Framework\\TestCase;\n\n /**\n * Class SampleUnitTest.\n *\n * Unit test for 'Helloworld Pub/Sub' Cloud Function.\n */\n class SampleUnitTest extends TestCase\n {\n /**\n * Include the Cloud Function code before running any tests.\n *\n * @see https://phpunit.readthedocs.io/en/latest/fixtures.html\n */\n public static function setUpBeforeClass(): void\n {\n require_once __DIR__ . '/index.php';\n }\n\n public function dataProvider()\n {\n return [\n [\n 'cloudevent' =\u003e new CloudEventImmutable(\n uniqId(), // id\n 'pubsub.googleapis.com', // source\n 'google.cloud.pubsub.topic.v1.messagePublished', // type\n [\n 'data' =\u003e base64_encode('John')\n ]\n ),\n 'expected' =\u003e 'Hello, John!'\n ],\n ];\n }\n\n /**\n * @dataProvider dataProvider\n */\n public function testFunction(\n CloudEventInterface $cloudevent,\n string $expected\n ): void {\n // Capture function output by overriding the function's logging behavior.\n // The 'LOGGER_OUTPUT' environment variable must be used in your function:\n //\n // $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');\n // fwrite($log, 'Log Entry');\n putenv('LOGGER_OUTPUT=php://output');\n helloworldPubsub($cloudevent);\n // Provided by PHPUnit\\Framework\\TestCase.\n $actual = $this-\u003egetActualOutput();\n\n // Test that output includes the expected value.\n $this-\u003eassertStringContainsString($expected, $actual);\n }\n }\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]