Doing BDD with Behave on a Django project

嘗試了按照 Behave 文檔中的指導在咱們的 Django 項目上加入 BDD。今天就來分享下過程當中解決的坑和一些心得體會。 html

坑1 - test db 的初始數據準備

若是你項目中的數據庫初始數據一直維護得好,或者大家已經在用 Django 自己提供的測試機制在跑測試了,那你應該不會踩到這個坑。否則,跑測試時動態建立的 test db 中空空如也,代碼中的大部分 view 應該都會拋出各類的異常來。 python

坑2 - 捕獲 mechanize 拋出的異常

這個坑和上一個緊密關聯。因爲使用 mechanize 來模擬一個瀏覽器來訪問,這中間拋出的異常的內容其實就是用 Django 開發過程當中常常看到的異常信息頁,是一個 HTML 頁面。Behave 驅動 mechanize 時的輸出沒有進一步的細節,只能知道是 500 INTERNAL ERROR。並且若是隻是把異常內容打印到 console,HTML 的內容也很難閱讀。個人解決辦法是把異常內容寫到臨時文件去: git

try:
    ...
except Exception as e:
    with open("/tmp/error.html", 'w') as f:
        f.write(e.read())

固然目前這個辦法只能應對一次 test run 中只拋出一個異常。拋出多個時的狀況還須要進一步改進。 github

也可能 Behave 自己就能作到這樣的事情,不過目前還不知道。 sql

運行的輸出樣子是這樣: 數據庫

» behave tests/features
Feature: Demonstrate how to use the mechanize browser to do useful things. # tests/features/browser.feature:1
Creating test database for alias 'default'...

  Scenario: Logging in to our new Django site  # tests/features/browser.feature:3
    Given a user                               # tests/features/steps/browser_steps.py:7
    When I log in                              # tests/features/steps/browser_steps.py:15
    Then I see my account summary              # tests/features/steps/browser_steps.py:29
    And I see a warm and welcoming message     # tests/features/steps/browser_steps.py:37
Destroying test database for alias 'default'...


1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
4 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.7s

心得1 - WSGI intercept

和驅動 selenium 或者 splinter 不同的是,這個方法並不須要真正運行起 server 來(或者須要 django-live-server),而是利用 WSGI intercept 把 mechanize 產生的請求直接短路給 WSGI handler。在 view layer 層面作測試,這樣就夠了。因爲避免了運行一個 browser 進程,以及其加載靜態資源和運行 JS 代碼的 overhead,跑一遍測試的速度應該是大大加快了的。 django

心得2 - 爲快速跑測試的目的相應優化 PostgreSQL

在 postgresql.conf 中修改下列參數 瀏覽器

fsync=off
full_page_writes=off
synchronous_commit=off
checkpoint_segments = 6
checkpoint_timeout = 1h

依據參照 SO 上的這個回答post


做者:czhang 測試

原文連接:http://czhang.writings.io/articles/5-django-bdd-behave-20130519

相關文章
相關標籤/搜索