はじめに
タイトルのように、poetry で FastAPIを使った開発をしているときに、pytest を使ってみます。テストは開発環境でのみ実行するということにしたい。できるかな。
作業内容
これは、ここの続きです。
poetry の環境で用意
poetry 管理のもとで pytest をdev環境 にのみインストールします。
$ poetry add pytest --dev
The --dev option is deprecated, use the `--group dev` notation instead.
Using version ^7.2.1 for pytest
...
無事にインストールされたが、--group dev
を使った方が良いらしい.
。pyproject.toml で確認できます。
[tool.poetry.group.dev.dependencies]
pytest = "^7.2.1"
このあと、httpx がない、怒られたのでそれも追加しました。もしかしたら必要ないかもしれないですが、よく分からないのでいれました。
$ poetry add httpx --group dev
あとカバレッジとか計算するためにpytest-cov も追加しました。
$ poetry add pytest-cov --group dev
Pytest を用意する
下記を実行します。ネタは FastAPI のテストのページです。
from fastapi.testclient import TestClient
from my_try_webapi.main import app
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"msg": "Hello World"}
今、下記のような構造になっています。
$ tree .
.
├── Dockerfile
├── README.md
├── my_try_webapi
│ ├── __init__.py
│ └── main.py
├── poetry.lock
├── pyproject.toml
└── tests
├── __init__.py
└── test_main.py
このファイルはpoetry shell
で入った仮想環境では下記のように実行できます。
$ poetry shell
(my-try-webapi-py3.8)$ pytest ./tests/test_main.py
Poetry で pytest
なのですが、poetry の仮想環境に入っていなくても下記でも実行できました。
$ poetry run pytest
======================================================== test session starts ========================================================
platform linux -- Python 3.8.10, pytest-7.2.1, pluggy-1.0.0
rootdir: /home/x77/xxxxxx/my_try_webapi
plugins: anyio-3.6.2
collected 1 item
tests/test_main.py . [100%]
========================================================= 1 passed in 0.18s =========================================================
先程インストールした pytest-cov を使うといろいろ出せます。
$ poetry run pytest --cov=my_try_webapi -v
======================================================== test session starts ========================================================
platform linux -- Python 3.8.10, pytest-7.2.1, pluggy-1.0.0 -- /home/x77/xxxxxxx/my_try_webapi/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/x77/xxxxxxxxx/my_try_webapi
plugins: anyio-3.6.2, cov-4.0.0
collected 1 item
tests/test_main.py::test_read_main PASSED [100%]
---------- coverage: platform linux, python 3.8.10-final-0 -----------
Name Stmts Miss Cover
-----------------------------------------------
my_try_webapi/__init__.py 0 0 100%
my_try_webapi/main.py 9 1 89%
-----------------------------------------------
TOTAL 9 1 89%
出力option を指定するとブラウザでも結果を見れます。
$ poetry run pytest --cov=my_try_webapi -v --cov-report=html
まとめ
poetry で仮想環境の dev 環境に pytest を入れて、FastAPIの確認を行うことができました。とりあえず確認したかったことができたので、これにて撤退します。
下記のページを参考にしました。ありがとうございます。
https://tech-blog.s-yoshiki.com/entry/236
https://qiita.com/KWS_0901/items/58c54970f13ba9b6edd9
まぁ、明日はどうなることやら。おじさんはもう寝よう。
できたらいいこと:
- CIで実行する
- コンテナで実行する(意味ないかな)
- covergage を 100% にする。FastAPIの部分も追加する。
(2023/02/25)