Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 在视图中测试模块的最佳方法是什么?_Django_Python 3.x_Django Views - Fatal编程技术网

Django 在视图中测试模块的最佳方法是什么?

Django 在视图中测试模块的最佳方法是什么?,django,python-3.x,django-views,Django,Python 3.x,Django Views,我已经看过了这篇文章,但它并没有包含任何相关的答案。 我使用的是Django 1.11,我的views.py是模块化的(不是基于类的) 我想在django的python shell中测试shell中的视图模块(函数) >>> python manage.py shell 通过直接导入视图,如: >>> from my_app import views 这是可行的,但这似乎不是我喜欢的方式 有没有更好的方法,或者我应该在shell中从django导入视图还是

我已经看过了这篇文章,但它并没有包含任何相关的答案。 我使用的是
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在编写和运行测试方面有一些很好的文档:


关于测试客户机以及其他一些测试工具的信息:

因此,您最好只为视图编写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在编写和运行测试方面有一些很好的文档:

和关于测试客户端的信息以及其他一些测试工具,请参见: