在我的单元测试中,我正在用我的代码猴子化一个函数。在代码中,我一次调用了该函数。替换代码中的函数的Mock对象返回call_count == 0!
它正在代码中调用函数,而不是模拟对象! (请参阅下面的控制台输出。它不应显示“ elasticsearch_connect被调用”)
问题: 如何修复代码,以使其正确修补elasticsearch_connect函数,call_count == 1并通过断言?
======================
test_handler.py
import sys, os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
parentdir = "%s\\health_check"%os.path.dirname(parentdir)
sys.path.insert(0,parentdir)
print(parentdir)
import json
import pytest
import health_check
import app
import my_elastic_search
import mock
from mock import Mock
def test_lambda_handler(apigw_event, monkeypatch):
# arrange
elasticsearch_connect_mock = Mock()
monkeypatch.setattr('health_check.app.elasticsearch_connect', elasticsearch_connect_mock)
print("*************")
# act
ret = app.lambda_handler(apigw_event, "")
print("call count: %s"%elasticsearch_connect_mock.call_count)
# assert
elasticsearch_connect_mock.assert_called_with('hostname', 'user', 'password')
# print(elasticsearch_connect_mock.assert_called_with('{"hostname": "myhostname", "user": "myuser", "password": "mypass"}'))
app.py
import jon
import sys
import ssl
import boto3
import requests
from elasticsearch import Elasticsearch
from elasticsearch.connection import create_ssl_context
import elasticsearch
def lambda_handler(event, context):
# Connect to Elasicsearch
es = elasticsearch_connect("myhostname", "myuser", "mypass")
def elasticsearch_connect(hostname, user, password):
print("elasticsearch_connect was called")
输出==>通话次数:0(错误)
*************
elasticsearch_connect was called
call count: 0
,断言也失败(错误)
AssertionError: Expected call: mock('hostname', 'user', 'password')
E Not called