我已经浏览了这篇文章,但它没有包含任何相关的答案。我正在使用Django 1.11
,并且我的views.py
是模块化的(不是基于类的)。
我想在 django 的 python shell 中测试 shell 中的视图模块(函数)。
>>> python manage.py shell
通过直接导入视图,如:
>>> from my_app import views
它有效,但这似乎不是我的首选方式。
有没有首选的方法,或者我应该在 shell 中从 django 导入视图还是直接复制函数?这方面的最佳做法是什么?
因此,只为视图编写 Django 测试而不是尝试从 shell 运行它们会更好,因为它们将是相同的代码,但您将能够轻松地多次运行测试。
因此,要为单个视图创建测试,您需要在 django 应用程序中创建一个 tests.py 并使用 django 的测试客户端为该视图编写测试。这个测试客户端是一个虚拟的 web 浏览器,可用于发出 http 请求。一个简单的 tests.py 看起来像这样:
from django.tests import TestCase, Client
class MyViewsTestCase(TestCase):
def setUp(self):
self.client = Client() #This sets up the test client
def test_my_view(self):
# A simple test that the view returns a 200 status code
# In reality your test needs to check more than this depending on what your view is doing
response = self.client.get('the/view/url')
self.assertEqual(response.status_code, 200)
然后您将使用命令python manage.py test
或django-admin test
从您的终端运行它
同样,您可以从 shell 执行此操作,但从长远来看,使用测试框架会更好
Django 有一些关于编写和运行测试的好文档:https : //docs.djangoproject.com/en/2.0/topics/testing/overview/
和有关测试客户端的信息以及其他一些测试工具:https : //docs.djangoproject.com/en/2.0/topics/testing/tools/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句