如何单元测试Django视图? [英] How do I unit test Django Views?

查看:144
本文介绍了如何单元测试Django视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开始将单元测试整合到我的Django项目中,我发现单元测试的一个视图是棘手的,因为Django使用函数实现视图。



例如,每个函数是Django中的视图/页面,如果该函数具有URL。



我单位测试Django视图?

解决方案

我不知道如何测试视图是棘手的。
$ b

您只需使用测试客户端



代码覆盖很简单。您要理解URL请求如何映射到代码路径并进行适当的URL请求。



如果需要,您可以通过创建手动调用视图功能一个Request对象并检查Response对象,但这是太多的工作。



如果您对代码覆盖有疑问,那是一件好事。这意味着您有代码,您无法轻松地映射到URL(这是所有用户可以看到的Web应用程序。)如果您的代码不映射到URL,则应该(a)删除代码或(b)将其重构为单独的模块。



我们在查看功能之外有很多模块。我们的视图功能导入这些模块。我们使用普通的单元测试来测试这些外部视图功能模块。






这是一个典型的结构。 b
$ b

  some_big_product / 
| - __init__.py
| - settings.py
| - urls。 py
| - logging.ini
| - other_global_files.py
| - an_app_1 /
| | - __init__.py
| | - urls.py
| | - models.py
| | - views.py
| | - tests.py< - 通用Django测试
| | - app_specific_module.py
| | - app_specific_package /
| | | - __init__.py
| | - test_app_specific_module.py< - unittest
| | - test_app_specific_package.py
| - generic_module.py
| - generic_package /
| | - __init__.py
| - tests /
| | - test_this.py
| | - test_that.py
| | - test_all.py< - 不总是实用
| - 脚本/
| - run_tests.sh


I want to begin integrating unit tests into my Django projects and I've discovered unit testing a view to be tricky because of the way Django implements views with functions.

For example, each function is a view/page in Django if the function has a URL.

How do I unit test Django views?

解决方案

I'm not sure how testing a view is tricky.

You just use the test client.

Code coverage is easy. You reason how how a URL request maps to a code path and make the appropriate URL requests.

You can, if you want, call the view functions "manually" by creating a Request object and examining the Response object, but this is too much work.

If you have doubts about your code coverage, that's a good thing. It means you have code you can't easily map to a URL (which is all a user can ever see of a web application.) If you have code that doesn't map to a URL, you should probably either (a) delete the code or (b) refactor it into a separate module.

We have lots of modules outside our view functions. Our view functions import these modules. We test these "outside the view function" modules with ordinary unittest.


Here's a typical structure.

some_big_product/
|-- __init__.py
|-- settings.py
|-- urls.py
|-- logging.ini
|-- other_global_files.py
|-- an_app_1/
|   |-- __init__.py
|   |-- urls.py
|   |-- models.py
|   |-- views.py
|   |-- tests.py <-- the generic Django testing 
|   |-- app_specific_module.py
|   |-- app_specific_package/
|   |   |-- __init__.py
|   |-- test_app_specific_module.py <-- unittest 
|   |-- test_app_specific_package.py
|-- generic_module.py
|-- generic_package/
|   |-- __init__.py
|-- tests/
|   |-- test_this.py
|   |-- test_that.py
|   |-- test_all.py <-- not always practical
|-- scripts/
    |-- run_tests.sh 

这篇关于如何单元测试Django视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆