我想对云函数进行单元测试,但是函数本身是一个事件触发函数,包含一些辅助函数。我也想测试这些辅助函数。这是代码示例
import os
from google.cloud import vision
from google.cloud import storage
def face_detection(uri):
"""
This function detects the faces in the file
located in Google Cloud Storage or the web
Args:
uri: the file located in Google Cloud Storage or the web
returns:
None: Prints the likelihood of the face expressions
or returns an errors resonse in string format
"""
def trigger_event(event, context):
"""
Background Cloud Function to be triggered by Cloud Storage.
This generic function logs relevant data when a file is changed.
Args:
event (dict): The dictionary with data specific to this type of event.
The `data` field contains a description of the event in
the Cloud Storage `object` format described here:
https://cloud.google.com/storage/docs/json_api/v1/objects#resource
context (google.cloud.functions.Context): Metadata of triggering event.
Returns:
None; the output is written to Stackdriver Logging
"""
bucket_name = event["bucket"]
source_img = event["name"]
tmp_download_path = f"/tmp/{source_img}"
try:
download_image(bucket_name, source_img, tmp_download_path)
print(f"Image {source_img} downloaded to {tmp_download_path}")
# currenlty this makes sure there's one person
# in the frame and prints a few other details
face_detection(tmp_download_path)
except Exception:
pass
finally:
if os.path.isfile(tmp_download_path):
os.remove(tmp_download_path)
else:
print("Error: %s file not found" % tmp_download_path)
def download_image(bucket_name, source_blob_name, destination_file_name):
"""Downloads the specified image from cloud storage
Args:
bucket_name = "your-bucket-name"
source_blob_name = "image-name"
destination_file_name = "local/path/to/file"
Returns:
Local path to downloaded image
"""
def upload_processed_images(bucket_name, source_file_folder):
"""Uploads images to the bucket.
Args:
bucket_name = "your-bucket-name"
source_file_folder = Path to the folder that contains
all the processed images
Returns:
None;
"""
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
for file_name in os.listdir(source_file_folder):
blob = bucket.blob(file_name)
blob.upload_from_filename(os.path.join(source_file_folder, file_name))
print("File {} uploaded to {}.".format(file_name, bucket_name))
例如,如果我想测试函数upload_processed_images 是否实际工作。我希望它是一个单元测试。我应该在本地测试吗?如果在本地测试该函数,它是否会使用正确的 storage.Client() 连接到 GCP?还是需要在 GCP 平台上测试?
感谢您的帮助。
答案 0 :(得分:0)
我实际上找到了一种测试方法。我使用函数框架进行测试。你可以找到答案https://github.com/neu-self-image-experiments/sie-backend#test-guidelines