![](/img/trans.png)
[英]How to run a GCP Cloud Function written in Golang to run a Dataflow job to import text file to Spanner?
[英]How do I test a function written in a GCP function file
GCP 功能的全新功能。 尝试测试文件中写入的函数和代码,以确保它不会恢复。 在测试文件中包含 index.js 文件不提供对文件中函数的访问,但是我不知道如何测试这些。
举一个简单的例子,我有一个 function ,它只是转换日期 object 的助手,因为我们需要以特定方式对其进行格式化。 GCP Function 文件中的 function 称为formatDateValue
。
我想编写一个测试,只在那里发送一个字符串并验证预期的返回。 但它一直告诉我formatDateValue
未定义。
我尝试像这样从 index.js 中导出它: exports.formatDateValue = formatDateValue;
,但这并没有改变任何东西。
引用测试文件的文件位于../index.js
并且在测试文件中是必需的。
我需要做什么才能访问这个 function 来测试它?
function 代码(为了节省空间,省略了其他功能)
index.js
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START functions_hello_bigquery]
// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();
const functions = require('@google-cloud/functions-framework');
const mysql = require('mysql');
const crypto = require("crypto");
// We need these in the global scope of this file
var hasError = false;
const currentSyncDbDateValue = new Date();
/**
*
* Helper functions that could be moved into some kind of util area
*
*/
// The challenge here is toISOString converts the time by adding on 5 hours.
function formatDateValue(dateStr, date) {
let formattedDate;
if(date != null) {
const dateArr = dateStr.split(' ');
const year = dateArr[3]; // Format: 2022
const day = dateArr[2]; // Format: 15, 02
const time = dateArr[4]; // Format: 15:17:42
const month = date.toISOString().split('-')[1]; // Format: 09 - We need to get the month from this, but NOT THE TIME
formattedDate = `${year}-${month}-${day} ${time}`
} else {
formattedDate = null;
}
return formattedDate;
}
...
/**
* HTTP Cloud Function that returns BigQuery query results
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
functions.http('assetSync', async (req, res) => {
// Get the tenantId from the req params
const tenantId = `${req.query.tenantId}`;
// Get the new asset sync date
const currentSync =
currentSyncDbDateValue.toISOString().replace(/T/, ' ').replace(/\..+/, ''); // replace T with a space, delete the dot and everything after to format the date correctly for the queries
// returns the last asset sync date formatted, or null if this is the first sync
const lastAssetSync = await getLastAssetSync(tenantId).then((value) => {return value;});
try {
// This is the query to create new lists in the DB. Returns either the query string or null
const newListQueryStr = await getNewListsQueryStr(tenantId, currentSync, currentSyncDbDateValue, lastAssetSync);
const lastAssetSyncQueryStr = await getLastAssetSyncQueryStr(tenantId, currentSync);
const queriesArr = buildQueriesArr([newListQueryStr, lastAssetSyncQueryStr]);
const transactionStatus = runTransaction(queriesArr, res);
res.status(200).send(`Transactions have run successfully`);
} catch (err) {
console.error("ERROR : " + err);
res.status(500).send(`Error querying BigQuery: ${err}`);
}
});
exports.formatDateValue = formatDateValue;
测试.js
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const supertest = require('supertest');
const {getTestServer} = require('@google-cloud/functions-
framework/testing');
require('../index.js');
describe('Creates correct Dates', () => {
it('constructs the correct date format', async () => {
const dateStr = 'Fri Sep 16 2022 15:17:42 GMT-0500 (Central Daylight Time)'; // Current test asset sync value
const formattedDateStr = formatDateValue(currentTestSync);
const expectedFormattedDateStr = '2022-09-16 15:17:42';
assert.equal(formattedDateStr, expectedFormattedDateStr);
})
})
为了解决这个问题,我必须像这样在 index.js 文件中导出 function:
exports.formatDateValue = formatDateValue;
然后我可以像这样在测试文件中导入它:
const {formatDateValue} = require('../index.js');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.