- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我一直在尝试为我的 ModelForm 编写单元测试,它有一个 ModelChoiceField。我正在使用模拟数据创建 Form 实例。
这是我的模型:
# models.py
class Menu(models.Model):
dish = models.ForeignKey(Dish, default=None)
price = models.DecimalField(max_digits=7, decimal_places=2)
# forms.py
class MenuForm(forms.ModelForm):
class Meta:
model = Menu
fields = ('dish', 'price',)
def clean(self):
cleaned_data = super(MenuForm, self).clean()
price = cleaned_data.get('price', None)
dish = cleaned_data.get('dish', None)
# Some validation below
if price < 70:
self.add_error('price', 'Min price threshold')
return cleaned_data
这是我的测试用例:
class MenuFormTest(TestCase):
def test_price_threshold(self):
mock_dish = mock.Mock(spec=Dish)
form_data = {
'dish': mock_dish,
'price': 80,
}
form = forms.MenuForm(data=form_data)
self.assertTrue(form.is_valid())
失败并出现以下错误:
<ul class="errorlist"><li>dish<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>
如何避免抛出该错误。 form.is_valid()
在那里应该是 True
。有什么方法可以修补 ModelChoiceField 的
queryset
?我尝试修补表单的 dish
字段 clean()
方法,如下所示:
form = forms.MenuForm(data=form_data)
dish_clean_patcher = mock.patch.object(form.fields['dish'], 'clean')
dish_clean_patch = dish_clean_patcher.start()
dish_clean_patch.return_value = mock_dish
self.assertTrue(form.is_valid())
然后看起来,在 _post_clean()
方法中将表单数据保存到模型实例时失败了。这是回溯:
Traceback (most recent call last):
File "/home/vagrant/venv/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/vagrant/myapp/tests/test_forms.py", line 51, in test_price_threshold
self.assertFalse(form.is_valid())
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 185, in is_valid
return self.is_bound and not self.errors
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 177, in errors
self.full_clean()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/forms.py", line 396, in full_clean
self._post_clean()
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 427, in _post_clean
self.instance = construct_instance(self, self.instance, opts.fields, construct_instance_exclude)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/forms/models.py", line 62, in construct_instance
f.save_form_data(instance, cleaned_data[f.name])
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 874, in save_form_data
setattr(instance, self.name, data)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 632, in __set__
instance._state.db = router.db_for_write(instance.__class__, instance=value)
File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/db/utils.py", line 300, in _route_db
if instance is not None and instance._state.db:
File "/home/vagrant/venv/local/lib/python2.7/site-packages/mock/mock.py", line 716, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute '_state'
我如何避免那部分?我根本不希望它查看 instance._state.db
。
我是否正确地测试了表单?或者我应该通过修补 super(MenuForm, self).clean( )
方法,并检查 form.errors
?
最佳答案
我会说调用 form.is_valid()
是测试表单的好方法。不过,我不确定是否要模拟模型。
Internally the form is calling get_limit_choices_to
on your dish
field (Django 当前正在为您创建)。
You would need to mock the dish
field's .queryset
or get_limit_choices_to
here ,(或调用堆栈中使此处的值变得毫无意义的其他地方)以某种方式实现您想要的。
或者,在您的测试中创建一个 Dish
并让 Django 的内部继续做他们正在做的事情会简单得多。
class MenuFormTest(TestCase):
def test_price_threshold(self):
dish = Dish.objects.create(
# my values here
)
form_data = {
'dish': dish.id,
'price': 80,
}
form = MenuForm(data=form_data)
self.assertTrue(form.is_valid())
如果您真的不想使用 Django 的测试数据库,一种策略可能是模拟 MenuForm.clean
和 MenuForm._post_clean
:
class MenuFormTest(TestCase):
def test_price_threshold(self):
mock_dish = mock.Mock(spec=Dish)
form_data = {
'dish': 1,
'price': 80,
}
form = MenuForm(data=form_data)
form.fields['dish'].clean = lambda _: mock_dish
form._post_clean = lambda : None
self.assertTrue(form.is_valid())
如果您要进行此测试,您需要问问自己您的目标是什么。
关于python - 具有 ModelChoiceField 和模拟数据的 UnitTest ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810471/
在开发 API 时,我经常在 main 函数中编写测试代码,但因为 D 已经集成了 unittest,所以我想开始使用它们。 我当前的工作流程如下,我有一个脚本可以监视任何 .d 文件中的文件更改,如
我无法使用 pub 包语法导入文件,如下所示: #import("package:unittest/unittest.dart"); 我收到以下编译时错误: 找不到引用的源:包:unittest/un
我想问一下我是否应该将我正在测试的函数包含在 unittest 文件中(这样我就会有一个文件 unittest.py),或者我应该只将它导入到 unittest 文件中(我会有两个文件、unittes
我正在尝试使用 C++/Codelite 进行单元测试。我从 codelite-plugins 包(Ubuntu 18.04)安装了 UnitTest++ 插件。我也可以看到这个: $ ls -la
我正在用 python 进行单元测试。我没有使用任何自动测试发现。我正在手动将 TestCases 组装到 TestSuite 中。 我可以用 unittest.TextTestRunner().ru
我正在尝试学习 Python 中的单元测试,特别是 unittest 模块。 考虑以下几行: import unittest class abc(unittest.TestCase): def
我正在开发一个修改测试套件的程序。 在最初的实现中,只支持 unittest 框架。我现在正在尝试添加对 Pytest 的支持。 使用默认的 unitest 模块,我可以将修改后的测试作为 AST 保
我有一个带有两种不同方法的单元测试测试用例。如果第一个方法失败,我希望跳过我的第二个方法。 我正在使用装饰器 @unittest.skipIf 但我找不到合适的条件。 class myTest(uni
根据文档,我可以在调用 unittest.main 时设置 python unittest 的详细级别,例如 unittest.main(verbosity=2) 如何在 unittest.TestC
有没有人遇到过这样的情况,他们将自己代码的单元测试写到一个名为unittest.py的文件中,发现它与NumPy的unittest.py模块冲突?换句话说,如果我将其写入本地目录中的 unittest
似乎有两种使用方式 unittest.mock.patch : 有更好的方法吗? 使用上下文管理器和 with 语句: class MyTest(TestCase): def test_som
在装有 PyCharm 的两台不同机器上,我有相同的项目。我有简单的代码: import unittest from tests import test unittest.makeSuite(test
我正在尝试执行我的以下测试套件: import unittest from Login_Page import LoginPageAndLogout def test_suite(): # g
当我正常运行应用程序并在浏览器中登录时,它可以正常工作。但是使用 Unittest 它不会让我登录....,它会再次返回登录页面。 “print rv.data”都只是打印登录页面的内容,但它应该打印
我仍在使用 Django 1.2.1,我认为对于较新的 Django,我们不会 import unittest然后做unittest.TestCase . 插图 import unittest cla
基于上一篇文章,这篇文章是关于使用coverage来实现代码覆盖的操作实例,源代码在上一篇已经给出相应链接。 本篇文章字用来实现代码覆盖的源代码,整个项目的测试框架如下: 就是在源代码的基础
当被测试的模块需要导入其他模块时,我们的 Python 3.10 单元测试会中断。当我们使用其他帖子和文章推荐的打包技术时,要么单元测试导入模块失败,要么直接调用运行应用程序导入模块失败。我们读过的其
我已经定义了一个自定义错误,但是如果我测试是否得到了自定义错误 提出来,它失败了。 我的models.py: class CustomError(Exception): """ Thi
我目前正在做一个项目,其结构是: my_package │ README.md | setup.py │ └───my_package | | __init__.py │ │
这是我的项目设置: my_project ./my_project ./__init__.py ./foo ./__init__
我是一名优秀的程序员,十分优秀!