django-快速调试技巧
F.I.R.S.T. class test case
- Fast: the faster the tests, the more often they are run. Ideally, your tests should complete in a few seconds.
- Independent: Each test case must be independent of others and can be run in any order.
- Repeatable: The results must be the same every time a test is run. Ideally, all random and varying factors must be controlled or set to known values before a test is run.
- Small: Test cases must be as short as possible for speed and ease of understanding.
- Transparent: Avoid tricky implementations or ambiguous test cases.
中文
- 快:必须快,因为它们经常运行,一般来说,测试应该要几秒内完成.
- 独立: 每个测试一定要独立于其他,也就是说任何order运行都没运行.
- 重复: 结果一定要相同,不管运行多少次,必然要排除随机性等.
- 小: 测试用例一定要小,并且要容易看明.
- 透明性: 不要用聪明的测试方法,要够笨.
不要做的
- Do not (re)test the framework: Django is well tested. Don’t check for URL lookup, template rendering, and other framework-related functionality.
- Do not test implementation details: Test the interface and leave the minor implementation details. It makes it easier to refactor this later without breaking the tests.
- Test models most, templates least: Templates should have the least business logic, and they change more often.
- Avoid HTML output validation: Test views use their context variable’s output rather than its HTML-rendered output.
- Avoid using the web test client in unit tests: Web test clients invoke several components and are therefore, better suited for integration tests.
- Avoid interacting with external systems: Mock them if possible. Database is an exception since test database is in-memory and quite fast.
中文
- 不要测试框架.
- 不要测试内部实现.
- 测试models
- 避免检验html.
- 避免做用web test client?
- 避免以真实系统交互.
使用django-extensions
-
运行加强版 runserver_plus,为什么使用这个呢? 有几点能让它认为好的是异常显示后,
- 页面能查看源代码,
- 能在线调试源代码.
-
常使用 shell_plus,使用这个好处是 自动加载models,和一些常用的库.
使用django-querycount 检查每个请求查询情况.
使用django-debug-toolbar查询每次请求
注意出现条件
The toolbar isn’t displayed!
The Debug Toolbar will only display when DEBUG = True in your project’s settings. It will also only display if the mimetype of the response is either text/html or application/xhtml+xml and contains a closing </body> tag.
Be aware of middleware ordering and other middleware that may intercept requests and return responses. Putting the debug toolbar middleware after the Flatpage middleware, for example, means the toolbar will not show up on flatpages.