问题描述
我一直在构建一个将用户配置文件存储在数据库中的模块,我一直在编写测试,但我遇到了一个障碍,我似乎可以编写一个测试来检查是否调用了正确的方法,如果提供了正确的变量。
我已经能够在没有 IF 语句的情况下成功地为其他方法编写此测试,但是现在使用 IF 语句我被卡住了并且不确定如何执行此操作,我已经阅读了很多内容并且已经看到补丁可能成为其中之一,但我一直无法找到与我必须要做的事情类似的例子。
routes.py
@bp.route('/profiles')
@login_required
def all_identities():
ident = IdentityObject('')
idbase = IdentityBase()
resp = idbase.search(ident,'PERSONS','SEARCH','ALL')
return render_template('profiles/all_profiles.html',title='Search Users',identities=resp)
中间件.py
class IdentityObject:
def __init__(self,identity):
self.username = identity
class IdentityBase:
def search(self,identity,profile_type,req_type,req_range):
ident = self._get_req_type(profile_type,req_range)
return ident(identity)
def _get_req_type(self,req_range):
if profile_type == 'PERSONS' and req_type == 'SEARCH' and req_range == 'ALL':
return self._get_all_individuals
elif profile_type == 'ORGANISATION' and req_type == 'SEARCH' and req_range == 'ALL':
return self._get_all_organisations
else:
raise ValueError(profile_type,req_range)
def _get_all_individuals(self,identity):
resp = Identity.query.order_by(Identity.username).all()
return resp
def _get_all_organisations(self,identity):
pass
test_middleware.py
class IdentityBase_Unit(unittest.TestCase):
def test_0_search(self):
""" Calls the search() method and validates that it takes the supplied attributes and calls
the _get_req_type() method with those 3 attributes"""
identity = 'USER_1'
profile_type = 'PERSONS'
req_type = 'SEARCH'
req_range = 'ALL'
real = IdentityBase()
real._get_req_type = MagicMock()
real.search(identity,req_range)
real._get_req_type.assert_called_once_with(profile_type,req_range)
def test_1_get_req_type(self,mock_method):
identity = ''
profile_type = 'PERSONS'
req_type = 'SEARCH'
req_range = 'ALL'
real = IdentityBase()
real._get_all_individuals = MagicMock()
real._get_req_type(profile_type,req_range)
real._get_all_individuals.assert_called_once_with()
test_0 按预期工作,但我似乎无法让 test_1 工作,当我运行测试 1 时,如果 IF 语句我得到以下响应,试图只获得对 fist 选项的响应。
FAIL: test_1_get_req_type
(tests.test_unit_ident_middleware.IdentityBase_Unit)
Calls the search() method and validates that it takes the supplied
attributes
and calls the
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/Documents/code/tests/test_unit_ident_middleware.py",line
178,in test_1_get_req_type
real._get_all_individuals.assert_called_once_with()
File "/usr/lib/python3.8/unittest/mock.py",line 924,in
assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'mock' to be called once. Called 0 times
对此的任何帮助将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)