測試我們的 Hello World 應用程式
介紹
在這個極簡主義的例子中,使用 pytest 我們將測試確實我們的 Hello World 應用程式確實返回 Hello World! 在 HTTP /上使用 GET 請求命中時,HTTP OK 狀態程式碼為 200
首先讓我們將 pytest 安裝到我們的 virtualenv 中
pip install pytest
僅供參考,這是我們的 hello world 應用程式:
# hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
定義測試
在我們的 hello.py 旁邊,我們定義了一個名為 test_hello.py 的測試模組,它將由 py.test 發現
# test_hello.py
from hello import app
def test_hello():
response = app.test_client().get('/')
assert response.status_code == 200
assert response.data == b'Hello, World!'
回顧一下,此時我們用 tree 命令獲得的專案結構是:
.
├── hello.py
└── test_hello.py
執行測試
現在我們可以使用 py.test 命令執行此測試,該命令將自動發現我們的 test_hello.py 及其中的測試功能
$ py.test
你應該看到一些輸出和 1 個測試已經過去的指示,例如
=== test session starts ===
collected 1 items
test_hello.py .
=== 1 passed in 0.13 seconds ===