# Flask-Testing
**Flask-Testing** 擴展為 Flask 提供了單元測試的工具。
## 安裝 Flask-Testing
使用 **pip** 或者 **easy_install** 安裝:
```
pip install Flask-Testing
```
或者從版本控制系統(github)中下載最新的版本:
```
git clone https://github.com/jarus/flask-testing.git
cd flask-testing
python setup.py develop
```
如果你正在使用 **virtualenv**,假設你會安裝 **Flask-Testing** 在運行你的 Flask 應用程序的同一個 virtualenv 上。
## 編寫測試用例
簡單地繼承 `TestCase` 的 MyTest:
```
from flask.ext.testing import TestCase
class MyTest(TestCase):
pass
```
你必須定義 `create_app` 方法,該方法返回一個 Flask 實例:
```
from flask import Flask
from flask.ext.testing import TestCase
class MyTest(TestCase):
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
return app
```
如果不定義 `create_app`,`NotImplementedError` 異常將會拋出。
### 使用 LiveServer 測試
如果你想要你的測試通過 Selenium 或者 無頭瀏覽器(無頭瀏覽器的意思就是無外設的意思,可以在命令行下運行的瀏覽器)運行,你可以使用 LiveServerTestCase:
```
import urllib2
from flask import Flask
from flask.ext.testing import LiveServerTestCase
class MyTest(LiveServerTestCase):
def create_app(self):
app = Flask(__name__)
app.config['TESTING'] = True
# Default port is 5000
app.config['LIVESERVER_PORT'] = 8943
return app
def test_server_is_up_and_running(self):
response = urllib2.urlopen(self.get_server_url())
self.assertEqual(response.code, 200)
```
在這個例子中 `get_server_url` 方法將會返回 [http://localhost:8943](http://localhost:8943)。
### 測試 JSON 響應
如果你正在測試一個返回 JSON 的視圖函數的話,你可以使用 `Response` 對象的特殊的屬性 `json` 來測試輸出:
```
@app.route("/ajax/")
def some_json():
return jsonify(success=True)
class TestViews(TestCase):
def test_some_json(self):
response = self.client.get("/ajax/")
self.assertEquals(response.json, dict(success=True))
```
### 選擇不渲染模板
當測試需要處理模板渲染的時候可能是一個大問題。如果在測試中你不想要渲染模板的話可以設置 `render_templates` 屬性:
```
class TestNotRenderTemplates(TestCase):
render_templates = False
def test_assert_not_process_the_template(self):
response = self.client.get("/template/")
assert "" == response.data
```
盡管可以設置不想渲染模板,但是渲染模板的信號在任何時候都會發送,你也可以使用 `assert_template_used` 方法來檢查模板是否被渲染:
```
class TestNotRenderTemplates(TestCase):
render_templates = False
def test_assert_mytemplate_used(self):
response = self.client.get("/template/")
self.assert_template_used('mytemplate.html')
```
當渲染模板被關閉的時候,測試執行起來會更加的快速并且視圖函數的邏輯將會孤立地被測試。
### 使用 Twill
[Twill](http://twill.idyll.org/) 是一個用來通過使用命令行界面瀏覽網頁的簡單的語言。
Note
請注意 Twill 只支持 Python 2.x,不能在 Python 3 或者以上版本上使用。
`Flask-Testing` 擁有一個輔助類用來創建使用 Twill 的功能測試用例:
```
def test_something_with_twill(self):
with Twill(self.app, port=3000) as t:
t.browser.go(t.url("/"))
```
舊的 `TwillTestCase` 類已經被棄用。
### 測試 SQLAlchemy
這部分將會涉及使用 **Flask-Testing** 測試 [SQLAlchemy](http://sqlalchemy.org) 的一部分內容。這里假設你使用的是 [Flask-SQLAlchemy](http://packages.python.org/Flask-SQLAlchemy/) 擴展,并且這里的例子也不是太難,可以適用于用戶自己的配置。
首先,先確保數據庫的 URI 是設置成開發環境而不是生產環境!其次,一個好的測試習慣就是在每一次測試執行的時候先創建表,在結束的時候刪除表,這樣保證干凈的測試環境:
```
from flask.ext.testing import TestCase
from myapp import create_app, db
class MyTest(TestCase):
SQLALCHEMY_DATABASE_URI = "sqlite://"
TESTING = True
def create_app(self):
# pass in test configuration
return create_app(self)
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
```
同樣需要注意地是每一個新的 SQLAlchemy 會話在測試用例運行的時候就被創建, `db.session.remove()` 在每一個測試用例的結尾被調用(這是為了確保 SQLAlchemy 會話及時被刪除) - 這是一種常見的 “陷阱”。
另外一個 “陷阱” 就是 Flask-SQLAlchemy 會在每一個請求結束的時候刪除 SQLAlchemy 會話(session)。因此每次調用 `client.get()` 或者其它客戶端方法的后,SQLAlchemy 會話(session)連同添加到它的任何對象都會被刪除。
例如:
```
class SomeTest(MyTest):
def test_something(self):
user = User()
db.session.add(user)
db.session.commit()
# this works
assert user in db.session
response = self.client.get("/")
# this raises an AssertionError
assert user in db.session
```
你現在必須重新添加 “user” 實例回 SQLAlchemy 會話(session)使用 `db.session.add(user)`,如果你想要在數據庫上做進一步的操作。
同樣需要注意地是在這個例子中內存數據庫 SQLite 是被使用:盡管它是十分的快,但是你要是使用其它類型的數據庫(例如 MySQL 或者 PostgreSQL),可能上述代碼就不適用。
你也可能想要在 `setUp()` 里為你的數據庫增加一組實例一旦你的數據庫的表已經創建。如果你想要使用數據集的話,請參看 [Fixture](http://farmdev.com/projects/fixture/index.html),它包含了對 SQLAlchemy 的支持。
## 運行測試用例
### 使用 unittest
一開始我建議把所有的測試放在一個文件里面,這樣你可以使用 `unittest.main()` 函數。這個函數將會發現在你的 `TestCase` 類里面的所有的測試方法。請記住,所有的測試方法和類請以 `test` 開頭(不區分大小寫),這樣才能被自動識別出來。
一個測試用例的文件可以看起來像這樣:
```
import unittest
import flask.ext.testing
# your test cases
if __name__ == '__main__':
unittest.main()
```
現在你可以用 `python tests.py` 命令執行你的測試。
### 使用 nose
同樣 [nose](http://nose.readthedocs.org/en/latest/) 也與 Flask-Testing 能夠很好的融合在一起。
## 更新歷史
### 0.4.2 (24.07.2014)
>
>
> * Improved teardown to be more graceful.
> * Add `message` argument to `assertStatus` respectively all assertion methods with fixed status like `assert404`.
>
>
### 0.4.1 (27.02.2014)
This release is dedicated to every contributer who made this release possible. Thank you very much.
>
>
> * Python 3 compatibility (without twill)
> * Add `LiveServerTestCase`
> * Use unittest2 backports if available in python 2.6
> * Install multiprocessing for python versions earlier than 2.6
>
>
### 0.4 (06.07.2012)
>
>
> * Use of the new introduced import way for flask extensions. Use `import flask.ext.testing` instead of `import flaskext.testing`.
> * Replace all `assert` with `self.assert*` methods for better output with unittest.
> * Improved Python 2.5 support.
> * Use Flask’s preferred JSON module.
>
>
## API
`class flask.ext.testing.TestCase(methodName='runTest')`
`assert200(response)`
Checks if response status code is 200
Parameters: **response** – Flask response
`assert400(response)`
Checks if response status code is 400
Versionadded: 0.2.5
Parameters: **response** – Flask response
`assert401(response)`
Checks if response status code is 401
Versionadded: 0.2.1
Parameters: **response** – Flask response
`assert403(response)`
Checks if response status code is 403
Versionadded: 0.2
Parameters: **response** – Flask response
`assert404(response)`
Checks if response status code is 404
Parameters: **response** – Flask response
`assert405(response)`
Checks if response status code is 405
Versionadded: 0.2
Parameters: **response** – Flask response
`assert500(response)`
Checks if response status code is 500
Versionadded: 0.4.1
Parameters: **response** – Flask response
`assertContext(name, value)`
Checks if given name exists in the template context and equals the given value.
Versionadded:
0.2
Parameters:
* **name** – name of context variable
* **value** – value to check against
`assertRedirects(response, location)`
Checks if response is an HTTP redirect to the given location.
Parameters:
* **response** – Flask response
* **location** – relative URL (i.e. without **http://localhost**)
`assertStatus(response, status_code)`
Helper method to check matching response status.
Parameters:
* **response** – Flask response
* **status_code** – response status code (e.g. 200)
`assertTemplateUsed(name, tmpl_name_attribute='name')`
Checks if a given template is used in the request. Only works if your version of Flask has signals support (0.6+) and blinker is installed. If the template engine used is not Jinja2, provide `tmpl_name_attribute` with a value of its `Template` class attribute name which contains the provided `name` value.
Versionadded:
0.2
Parameters:
* **name** – template name
* **tmpl_name_attribute** – template engine specific attribute name
`assert_200(response)`
Checks if response status code is 200
Parameters: **response** – Flask response
`assert_400(response)`
Checks if response status code is 400
Versionadded: 0.2.5
Parameters: **response** – Flask response
`assert_401(response)`
Checks if response status code is 401
Versionadded: 0.2.1
Parameters: **response** – Flask response
`assert_403(response)`
Checks if response status code is 403
Versionadded: 0.2
Parameters: **response** – Flask response
`assert_404(response)`
Checks if response status code is 404
Parameters: **response** – Flask response
`assert_405(response)`
Checks if response status code is 405
Versionadded: 0.2
Parameters: **response** – Flask response
`assert_500(response)`
Checks if response status code is 500
Versionadded: 0.4.1
Parameters: **response** – Flask response
`assert_context(name, value)`
Checks if given name exists in the template context and equals the given value.
Versionadded:
0.2
Parameters:
* **name** – name of context variable
* **value** – value to check against
`assert_redirects(response, location)`
Checks if response is an HTTP redirect to the given location.
Parameters:
* **response** – Flask response
* **location** – relative URL (i.e. without **http://localhost**)
`assert_status(response, status_code)`
Helper method to check matching response status.
Parameters:
* **response** – Flask response
* **status_code** – response status code (e.g. 200)
`assert_template_used(name, tmpl_name_attribute='name')`
Checks if a given template is used in the request. Only works if your version of Flask has signals support (0.6+) and blinker is installed. If the template engine used is not Jinja2, provide `tmpl_name_attribute` with a value of its `Template` class attribute name which contains the provided `name` value.
Versionadded:
0.2
Parameters:
* **name** – template name
* **tmpl_name_attribute** – template engine specific attribute name
`create_app()`
Create your Flask app here, with any configuration you need.
`get_context_variable(name)`
Returns a variable from the context passed to the template. Only works if your version of Flask has signals support (0.6+) and blinker is installed.
Raises a ContextVariableDoesNotExist exception if does not exist in context.
Versionadded: 0.2
Parameters: **name** – name of variable
`class flask.ext.testing.Twill(app, host='127.0.0.1', port=5000, scheme='http')`
Versionadded: 0.3
Twill wrapper utility class.
Creates a Twill `browser` instance and handles WSGI intercept.
Usage:
```
t = Twill(self.app)
with t:
t.browser.go("/")
t.url("/")
```
`url(url)`
Makes complete URL based on host, port and scheme Twill settings.
Parameters: **url** – relative URL
`class flask.ext.testing.TwillTestCase(methodName='runTest')`
Deprecated: use Twill helper class instead.
Creates a Twill `browser` instance and handles WSGI intercept.
`make_twill_url`<big>(</big>_url_<big>)</big>
Makes complete URL based on host, port and scheme Twill settings.
Parameters: **url** – relative URL