mocker 组件自定义对象以及方法,网络请求 time.sleep 不需要进行测试 测试的只是程序的运行!
from pytest import mark
@mark.django_db
def test_node_summaries(mocker, node_data):
# 自定义函数返回值!
# antilles.cluster.tasks.node_summary.cache.get 的返回值为 node_data
mocker.patch(
'antilles.cluster.tasks.node_summary.cache.get',
return_value=node_data
)
# 第二种自定义 方式!
mock = mocker.patch('antilles.cluster.tasks.summary.cache')
mock.get.return_value = [ResultSet(query_response["results"][0])]
def test_form_condition(mocker, monkeypatch):
# 自定义对象!
stub = mocker.Mock()
host_stub = mocker.Mock()
# 对象自定义个属性 hostname
host_stub.hostname = 'head'
# 自定义方法的返回值
stub.count.return_value = 2
# 自定义方法的返回值
stub.iterator.return_value = [host_stub, host_stub]
# 根据自定义的对象 代替 实际之中的对象!
assert summary._form_condition(stub) == ['head', 'head']
class MockAuthentication(BaseAuthentication):
def authenticate(self, request):
return User(username=username, role=ROLE_ADMIN, id=1), None
# 指定 authentication_classes 的认证类为 MockAuthentication
monkeypatch.setattr('rest_framework.views.APIView.authentication_classes',
[MockAuthentication])
client 模拟接口调用:
conftest.py 之中定义
# 在 conftest.py 之中定义的 fixture 对象首先加载!
@fixture(autouse=True)
def settings(settings, tmpdir):
# 在 conftest.py 之中定义 settings 是为了能够让整个模块都能加载
settings.ROOT_URLCONF = 'antilles.cluster.urls'
settings.CONFLUENT_USER = 'lico'
settings.CONFLUENT_PASS = 'Paa'
settings.CONFLUENT_PORT = 4005
return settings
接口测试实例:
@mark.django_db
def test_nodes_list_view(client, mocker):
args = {
"offset": 0,
"length": 10,
"filters": [],
"sort": {
"prop": "hostname",
"order": "ascending"}
}
# 调用接口 /nodes/?args={0}
# 在请求之中 增加header 信息
token_head = 'token {0}'.format("1111111111111")
response = client.get('/nodes/?args={0}'.format(json.dumps(args)),HTTP_AUTHORIZATION=token_head)
组件也可以在 非 test_ 来头的函数之中传递:
1,开发时要将代码进行测试规划, 不能到最后才加单元测试代码!这样也不好加!
def mock_cache(mocker, category, query_result):
if category == 'network':
mocker.patch(
"django.core.cache.cache.get",
return_value=[query_result, query_result]
)
else:
mocker.patch("django.core.cache.cache.get", return_value=query_result)
@mark.django_db
def test_node_history(client, mocker, nodes, node_category, query_result):
# 为 特殊的 接口进行 区别对待!
mock_cache(mocker, node_category, query_result)
pass
使用 yield处理后续 工作!
@fixture(autouse=True)
def nodes_create():
node_1 = {
"hostname": 'lico_head', "type": 'compute', "machinetype": 'ibm',
"mgt_ipv4": '172.20.0.1', "bmc_ipv4": '10.240.212.13',
"rack_id": 1, "service": 'compute', "id": 0
}
node1 = Node.objects.create(**node_1)
run_jobs = {
"job_id": 1, "node": node1, "core_num": 0, "gpu_num": 0
}
run1 = RunningJob.objects.create(**run_jobs)
yield node1, run1
run1.delete()
node1.delete()