# python でテストを書く
[pytest](https://docs.pytest.org/en/stable/contents.html) というライブラリを使ってテストコードを実行する方法

## シンプルな例
テスト用ファイルを準備

```python:tests/test.py
def test_hoge():
    a = 1
    b = 1
    assert a == b
    
def test_fuga():
    a = 1
    b = 2
    assert a == b
```

以下コマンドでテストを実行

```shell
$ pip install pytest
$ pytest ./tests/test.py

=============================== test session starts ================================
platform darwin -- Python 3.7.9, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: /Users/yusuketakizawa/mahjong-manager-bot
collected 2 items                                                                  

tests/test.py .F                                                             [100%]

===================================== FAILURES =====================================
____________________________________ test_fuga _____________________________________

    def test_fuga():
        a = 1
        b = 2
>       assert a == b
E       assert 1 == 2

tests/test.py:66: AssertionError
============================= short test summary info ==============================
FAILED tests/test.py::test_fuga - assert 1 == 2
=========================== 1 failed, 1 passed in 0.03s ============================
```

こんな感じで結果が表示される。

## 注意点
### テスト対象のメソッドかどうかはメソッド名で判別される
テストをするメソッドかどうかは `python_functions` という設定値で指定される(デフォルトは `test_*` )

https://docs.pytest.org/en/latest/reference.html#confval-python_functions

テスト対象のメソッドがなかった場合 `no tests run` となるが、これは github action 上では `Error: Process completed with exit code 5.` となり fail と扱われるので注意が必要

### ライブラリのパスが通るパターンと通らないパターン
```
$ pytest ./tests/test.py
>>> ModuleNotFoundError: No module named 'flask'
```

上記のように直接 pytest コマンドを実行するとモジュールインポート時にエラーが出る場合は以下のように python コマンドで実行すればよい

```
$ python -m pytest ./tests/test.py
```

### 上位階層にあるファイルのインポート
tests ディレクトリと同階層にあるファイル(例えば`libs.py`)を使いたいとき `import ..lib.py` としてもインポートできない。以下のように予め上位ディレクトリにパスを通しておくとインポートできるようになる

```
import sys
import os

sys.path.append(os.path.abspath(
    os.path.dirname(os.path.abspath(__file__)) + "/../"))
```


---

## Page Navigation

- Canonical URL: https://tips.weseek.co.jp/用語集/Python/テストを書く
- Permalink: https://tips.weseek.co.jp/603462f091cd67004906d99f
- Parent: [Python](/5e48bfd61ec5e4004811d4f1.md)
- Children: 0 total
- Total descendants: 0
- Siblings: 4 total
  - [イテレータのkeyとvalue両方使いたい](/5e49380e1ec5e4004811d516.md)
  - [リスト内包表記](/5e493b681ec5e4004811d51b.md)
  - [拡張IterableUnpacking](/5e492c431ec5e4004811d50a.md)
  - [集合演算](/5e49315f1ec5e4004811d510.md)
- Last updated: 2021-02-23T02:05:36.155Z by deleted_at_1672138409189
- Full page listing (all children regardless of count): https://tips.weseek.co.jp/_api/v3/page-listing/children?id=603462f091cd67004906d99f
