我试着用mock.patch模拟表单并且不能.我有这个代码
forms.py
class CreatePostForm(object):
pass
Run Code Online (Sandbox Code Playgroud)
views.py:
from forms import CreatePostForm
def doit():
print CreatePostForm()
Run Code Online (Sandbox Code Playgroud)
我希望孤立地测试这个视图.我尝试使用mock.patch修补表单,我写了类似的东西:
tests.py:
from mock import patch
import views
with patch('forms.CreatePostForm') as Form:
views.doit()
Run Code Online (Sandbox Code Playgroud)
我试图谷歌寻求解决方案,什么也没发现
回答:感谢@dstanek提供了良好的答案和良好的代码示例
我有一个任务
def task():
a = worker()
a.do_some_work()
Run Code Online (Sandbox Code Playgroud)
Worker本身是一个单独的类,在单独的模块中,谁使用这样的Driver类,
class Worker(object):
def __init__(self):
self.driver = Driver(args)
...
Run Code Online (Sandbox Code Playgroud)
并且再次Driver是单独模块中的单独类
所以,当我尝试类似的东西
with patch('package.module.Driver', new=Mock(return_value=999)):
task()
Run Code Online (Sandbox Code Playgroud)
在任务中仍然有一个Driver类实例,但不是模拟.那是错的.如何解决?
UPD1:
Driver与Worker住在不同的模块和Worker进口Driver
我正在尝试使用 Python 模拟库来模拟 zipfile 模块的一些方法。
我想测试的示例源:
def zipStuff(listOfPathToFiles):
with ZipFile(fName, 'w') as archive:
for each in listOfPathToFiles:
archive.write(each, strippedfName)
return archive
Run Code Online (Sandbox Code Playgroud)
正常执行时上面的“存档”将被忽略,但在测试期间将是文件列表。
单元测试代码示例:
emptyList=[]
def mockWrite(fName):
emptyList.append(fName)
return
mockZip.__enter__ = Mock(return_value=emptyList)
mockZip.__exit__ = Mock(return_value=True)
Run Code Online (Sandbox Code Playgroud)
现在,我想模拟 archive.write,以便将其替换为 mockWrite 函数,而不是实际的写入调用,这样我就可以获得应该压缩的所有文件的列表。
我试过了:
mockZip.write = Mock(side_effect=mockWrite)
Run Code Online (Sandbox Code Playgroud)
但这并没有被调用。调试显示该函数正在调用mockZip。输入().write。如果我尝试:
mockZip.__enter__().write = Mock(side_effect=mockWrite)
Run Code Online (Sandbox Code Playgroud)
Python 发出“list”没有属性 write 的错误(这是正确的)。我是 Mock 和 Python 的新手,非常感谢任何指点。建议?
我正在尝试模拟 paramiko SFTPClient.open() 并返回一个文件来测试我的文件解析代码。但是,当我如下设置模拟时,它返回一个 magicmock 实例,而不是打开的文件,其 _mock_return_value 等于打开的文件。
我希望 paramiko.SSHClient.open_sftp.open 等于打开的测试文件。我觉得这应该发生,但事实并非如此。我错过了什么吗?谁能解释一下,我做错了什么以及我是如何误解模拟的?
这是我的代码:
@app.route('/ipmivlan/<girls_name>', methods=['POST'])
def find_the_girl(girls_name):
this_is_the_girl = None
remote_file = None
try:
client = paramiko.SSHClient()
# Auto add host key if not found/unknown
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
sftp_client = client.open_sftp()
remote_filename = '/usr/local/{0}'.format(girls_name.lower())
remote_file = sftp_client.open(remote_filename, mode='r')
print remote_file
pprint(remote_file.__dict__)
this_is_the_girl = parse_config(remote_file)
except paramiko.ssh_exception.AuthenticationException:
return_message = "Authentication has failed."
app.logger.info(return_message)
app.logger.info("Traceback: {0}".format(traceback.format_exc()))
return jsonify(return_code=1, message=return_message, traceback=traceback.format_exc())
except paramiko.ssh_exception.BadHostKeyException:
return_message = "Server hostkey could not be verified"
app.logger.info(return_message)
app.logger.info("Traceback: …Run Code Online (Sandbox Code Playgroud) 我写了一个python模块,它依赖于我的CI测试机上没有的第三方软件包,因此我无法远程测试我的模块,因为我无法通过该import dependency语句.
如果我们假设我无法在CI主机上手动安装依赖项(看起来很痛苦),那么伪造/模拟/删除任何缺少的第三方软件包的最简单方法是什么,以便我可以测试我的代码?
我只使用依赖项提供的单个类,所以我很乐意只是模拟该对象,如果有办法那样做,而不是整个模块.
我想测试的这个演示功能非常简单。
def is_email_deliverable(email):
try:
return external.verify(email)
except Exception:
logger.error("External failed failed")
return False
Run Code Online (Sandbox Code Playgroud)
此功能使用external我想模拟的服务。
但我无法弄清楚如何exception从external.verify(email) 即如何强制except执行该子句。
我的尝试:
@patch.object(other_module, 'external')
def test_is_email_deliverable(patched_external):
def my_side_effect(email):
raise Exception("Test")
patched_external.verify.side_effects = my_side_effect
# Or,
# patched_external.verify.side_effects = Exception("Test")
# Or,
# patched_external.verify.side_effects = Mock(side_effect=Exception("Test"))
assert is_email_deliverable("some_mail@domain.com") == False
Run Code Online (Sandbox Code Playgroud)
这个问题声称有答案,但对我不起作用。
class Foo:
def do_work:
client = Client()
client.widgets(self.widget_id).parts().get()``
Run Code Online (Sandbox Code Playgroud)
我有上面的代码。Client() 类在另一个包中定义。我正在尝试使用模拟对其进行单元测试,如下所示:
magic_mock = MagicMock()
api_client = Client()
magic_mock.api_client.widgets().parts().get.return_value = self.generate_mock
Run Code Online (Sandbox Code Playgroud)
不幸的是,它似乎不起作用。什么是更好的方法?
如何修补或模拟“任何未直接调用/使用的函数”?
我有一个简单的单元测试片段
# utils/functions.py
def get_user_agents():
# sends requests to a private network and pulls data
return pulled_data
# my_module/tasks.py
def create_foo():
from utils.functions import get_user_agents
value = get_user_agents()
# do something with value
return some_value
# test.py
class TestFooKlass(unittest.TestCase):
def setUp(self):
create_foo()
def test_foo(self):
...Run Code Online (Sandbox Code Playgroud)
在方法中,我通过调用间接setUp()调用get_user_agents()函数。在此执行过程中,由于尝试访问专用网络,我遇到了异常。那么,在测试过程中如何操作返回数据或整个函数呢?create_foo()socket.timeoutget_user_agents()get_user_agents
另外,有什么方法可以在整个测试套件执行期间保留这个模拟/补丁吗?
我试图测试一些处理推文的类。我使用 Sixohsix twitter 来处理 Twitter API。我有一个类作为 Twitter 类的外观,我的想法是模拟实际的 Sixohsix 类来模拟推文的到达,方法是随机生成新推文或从数据库中检索它们。
我的外观看起来像:
from twitter import TwitterStream
class TwitterFacade(object):
def __init__(self, dev='soom'):
self._auth = OAuth(dev_keys["ACCESS_TOKEN"], dev_keys["ACCESS_SECRET"], dev_keys["CONSUMER_KEY"], dev_keys["CONSUMER_SECRET"])
def tweets(self, callback=None, users=[], terms=[], locations=[], count=5):
t = TwitterStream(auth=self._auth)
args = {}
if users: args['follow'] = ",".join(users)
if terms: args['track'] = ",".join(terms)
if locations: args['locations'] = ",".join(str(l) for l in locations)
# this controls the general loop, it re-enters if there was an exception,
# otherwise the for loop should take care of …Run Code Online (Sandbox Code Playgroud) 我正在尝试模拟VKAuth类中的“ self.api.friends.get”方法:
import vk
class VKAuth(object):
def __init__(self, access_token, user):
self.session = vk.Session(access_token = access_token)
self.api = vk.API(self.session)
def follow(self):
vk_friends = self.api.friends.get()
Run Code Online (Sandbox Code Playgroud)
来自测试模块test_views.py:
from mock import patch
from ..auth_backends.vk_backend import VKAuth
class AddUsersToList(TestCase):
def test_auth_vk(self, mock_get):
... etc ...
auth_token = 'ceeecdfe0eb4bf68ceeecdfe0eb4bf68ceeecdfe0eb4bf68652530774ced6cbc8cba0'
token = user.auth_token.key
self.client.defaults['HTTP_AUTHORIZATION'] = 'Token {}'.format(token)
with patch.object(accounts.auth_backends.vk_backend.VKAuth, 'api'): #point where we're mocking
response = self.client.post(reverse('auth-social', kwargs=dict(backend='vk')), dict(access_token=auth_token), follow=True)
Run Code Online (Sandbox Code Playgroud)
在基于SNView基于类的视图中对“ auth-social”的上述调用期间创建了VKAuth类的实例:
class SNView(generics.GenericAPIView):
serializer_class = serializers.AuthSocialSerializer
permission_classes = (rest_permissions.IsAuthenticated)
def post(self, request, backend, *args, **kwargs):
s …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用unittest以 ( ) 开头的 python 3.6 脚本进行测试my_app.py:
import sys
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv, ['opt1', 'opt2', 'opt3'])
opt1 = args['opt1']
opt2 = args['opt2']
opt3 = args['opt3']
....
Run Code Online (Sandbox Code Playgroud)
所以在我的测试中我做了类似的事情:
import unittest
import datetime
from mock import patch
import my_app
class TestMyApp(unittest.TestCase):
@patch('awsglue.utils.getResolvedOptions')
def test_mock_stubs(self, patch_opts):
patch_opts.return_value = {}
....
Run Code Online (Sandbox Code Playgroud)
但测试很快就失败了import my_app:
ModuleNotFoundError: No module named 'awsglue'
因为本地没有awsglue安装。如何测试导入非本地安装的库并在测试中模拟它的模块?
所以,考虑我有一个简单的库,我正在尝试编写单元测试.该库与数据库通信,然后使用该数据调用SOAP API.我有三个模块,每个模块都有一个测试文件.
目录结构:
./mypkg
../__init__.py
../main.py
../db.py
../api.py
./tests
../test_main
../test_db
../test_api
Run Code Online (Sandbox Code Playgroud)
码:
#db.py
import mysqlclient
class Db(object):
def __init__(self):
self._client = mysqlclient.Client()
@property
def data(self):
return self._client.some_query()
#api.py
import soapclient
class Api(object):
def __init__(self):
self._client = soapclient.Client()
@property
def call(self):
return self._client.some_external_call()
#main.py
from db import Db
from api import Api
class MyLib(object):
def __init__(self):
self.db = Db()
self.api = Api()
def caller(self):
return self.api.call(self.db.data)
Run Code Online (Sandbox Code Playgroud)
单元测试:
#test_db.py
import mock
from mypkg.db import Db
@mock.patch('mypkg.db.mysqlclient')
def test_db(mysqlclient_mock):
mysqlclient_mock.Client.return_value.some_query = {'data':'data'} …Run Code Online (Sandbox Code Playgroud) python ×12
python-mock ×12
unit-testing ×8
mocking ×7
django ×2
python-2.7 ×1
python-3.5 ×1
testing ×1
twitter ×1