|
| 1 | +// Copyright 2022 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +const {getFunction} = require('@google-cloud/functions-framework/testing'); |
| 16 | +require('..'); |
| 17 | + |
| 18 | +describe('functions_cloudevent_pubsub', () => { |
| 19 | + const assert = require('assert'); |
| 20 | + const uuid = require('uuid'); |
| 21 | + const sinon = require('sinon'); |
| 22 | + |
| 23 | + const stubConsole = function () { |
| 24 | + sinon.stub(console, 'error'); |
| 25 | + sinon.stub(console, 'log'); |
| 26 | + }; |
| 27 | + |
| 28 | + const restoreConsole = function () { |
| 29 | + console.log.restore(); |
| 30 | + console.error.restore(); |
| 31 | + }; |
| 32 | + |
| 33 | + beforeEach(stubConsole); |
| 34 | + afterEach(restoreConsole); |
| 35 | + |
| 36 | + it('should print a name from the pubsub message', () => { |
| 37 | + // Create mock Pub/Sub event |
| 38 | + const cloudEvent = {data: {message: {}}}; |
| 39 | + const name = uuid.v4(); |
| 40 | + cloudEvent.data.message = { |
| 41 | + data: Buffer.from(name).toString('base64'), |
| 42 | + }; |
| 43 | + |
| 44 | + // Call tested function and verify its behavior |
| 45 | + const helloPubSub = getFunction('helloPubSub'); |
| 46 | + helloPubSub(cloudEvent); |
| 47 | + assert.ok(console.log.calledWith(`Hello, ${name}!`)); |
| 48 | + }); |
| 49 | + |
| 50 | + it('helloPubSub: should print hello world', () => { |
| 51 | + // Create mock Pub/Sub event, in the event where a |
| 52 | + // PubSub message is empty but message has an attribute |
| 53 | + const cloudEvent = {data: {message: {data: null}}}; |
| 54 | + |
| 55 | + // Call tested function and verify its behavior |
| 56 | + const helloPubSub = getFunction('helloPubSub'); |
| 57 | + helloPubSub(cloudEvent); |
| 58 | + assert.ok(console.log.calledWith('Hello, World!')); |
| 59 | + }); |
| 60 | +}); |
0 commit comments