0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pytestのmock

Last updated at Posted at 2022-10-11

フォルダ構成

tree
.
├── config.yml
├── main.py
├── src
│   ├── __init__.py
│   └── my_module.py
└── tests
    ├── __init__.py
    └── unit
        ├── __init__.py
        └── test_handler.py

サンプルコード

main.py
import os
import src.my_module as my_module

def get_config() -> dict:
    cd = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(cd, 'config.yml')
    with open(path, encoding="utf-8") as f:
        config = yaml.safe_load(f)
    return config

def main():
    # *1
    if os.path.isfile('./config.yml'):
        print('ファイルが存在します')
    else:
        print('ファイルが存在しません')

    # *2
    config = get_config()

    # *3
    return my_module.get_sample(config)

if __name__ == '__main__':
    main()
tests/unit/test_handler.py
import pytest
import main

def test_response_ok(mocker):
    # *1) os.path.isfile をモック化する(常にFalse)
    mocker.patch('main.os.path.isfile', return_value=False)

    # *2) 自作関数のモック化
    mocker.patch('main.get_config', return_value={})

    # *3) 自作ライブラリのモック化
    mocker.patch('main.my_module.get_sample', return_value={'status': '200'})

    response = main.main()
    assert response['status'] == '200'

*1 はmain.pyでのos.path.isfile()の結果を固定
*2 はmain.pyでのget_config()の結果を固定
*3 はmain.pyでのmy_module.get_sample()の結果を固定

参考

pytest でモックを使う方法
pytest で単体テストの方法まとめ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?