django-快速调试技巧

F.I.R.S.T. class test case

  1. Fast: the faster the tests, the more often they are run. Ideally, your tests should complete in a few seconds.
  2. Independent: Each test case must be independent of others and can be run in any order.
  3. 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.
  4. Small: Test cases must be as short as possible for speed and ease of understanding.
  5. Transparent: Avoid tricky implementations or ambiguous test cases.

中文

  1. 快:必须快,因为它们经常运行,一般来说,测试应该要几秒内完成.
  2. 独立: 每个测试一定要独立于其他,也就是说任何order运行都没运行.
  3. 重复: 结果一定要相同,不管运行多少次,必然要排除随机性等.
  4. 小: 测试用例一定要小,并且要容易看明.
  5. 透明性: 不要用聪明的测试方法,要够笨.

不要做的

  1. Do not (re)test the framework: Django is well tested. Don’t check for URL lookup, template rendering, and other framework-related functionality.
  2. 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.
  3. Test models most, templates least: Templates should have the least business logic, and they change more often.
  4. Avoid HTML output validation: Test views use their context variable’s output rather than its HTML-rendered output.
  5. Avoid using the web test client in unit tests: Web test clients invoke several components and are therefore, better suited for integration tests.
  6. Avoid interacting with external systems: Mock them if possible. Database is an exception since test database is in-memory and quite fast.

中文

  1. 不要测试框架.
  2. 不要测试内部实现.
  3. 测试models
  4. 避免检验html.
  5. 避免做用web test client?
  6. 避免以真实系统交互.

使用django-extensions

  1. 运行加强版 runserver_plus,为什么使用这个呢? 有几点能让它认为好的是异常显示后,

    1. 页面能查看源代码,
    2. 能在线调试源代码.
  2. 常使用 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.

参考

django-extensions

django-querycount

django-debug-toolbar

测试与调试

Loading Disqus comments...
Table of Contents