如何在本地无GCP项目权限时,模拟GCP Endpoint编写功能测试?
问题描述
我编写了如下Python函数my_function:
from google.cloud.aiplatform import Endpoint def my_function(existing_endpoint: Endpoint)-> str: return existing_endpoint._gca_resource.name
该函数接收Google Cloud AI Platform的Endpoint对象,返回其_gca_resource.name属性。我希望在本地电脑上为该函数编写功能测试,无需访问具体GCP项目,测试代码大致如下:
def test_my_function_should_work(): ## something to simulate an existing endpoint assert my_function(fake_endpoint) == "projects/12345/locations/europe-west1/endpoints/12345"
请问如何创建模拟现有Endpoint资源的对象?
解决方案
方法1:使用unittest.mock模拟层级对象
Python标准库的unittest.mock可以快速构建需要的模拟对象,只聚焦于测试所需的属性:
from unittest.mock import Mock from your_module import my_function # 替换为实际存放my_function的模块名 def test_my_function_should_work(): # 模拟_gca_resource对象,设置name属性 fake_gca_resource = Mock() fake_gca_resource.name = "projects/12345/locations/europe-west1/endpoints/12345" # 模拟Endpoint对象,绑定_gca_resource属性 fake_endpoint = Mock() fake_endpoint._gca_resource = fake_gca_resource assert my_function(fake_endpoint) == "projects/12345/locations/europe-west1/endpoints/12345"
这种方式无需依赖GCP SDK的具体实现,灵活且轻量化。
方法2:手动创建极简模拟类
如果需要更直观的结构展示,可以手动定义匹配层级的模拟类:
from your_module import my_function # 替换为实际存放my_function的模块名 class FakeGCAResource: def __init__(self, name): self.name = name class FakeEndpoint: def __init__(self, gca_resource): self._gca_resource = gca_resource def test_my_function_should_work(): fake_gca = FakeGCAResource("projects/12345/locations/europe-west1/endpoints/12345") fake_endpoint = FakeEndpoint(fake_gca) assert my_function(fake_endpoint) == "projects/12345/locations/europe-west1/endpoints/12345"
这种方式结构清晰,适合需要明确对象关系的测试场景。
内容的提问来源于stack exchange,提问作者Maxime Oriol
相关产品推荐
相关产品推荐

