LoginSignup
2
0

More than 3 years have passed since last update.

with 構文で使っているメソッドをmockする

Posted at

with構文で使っているメソッドをmockしたい

Unittest を書いていて with でリソースを取得している箇所のmockをすることを考えました。
以下のように書けばmockができるので、参考にしてください。

withが使えるということは?

withが使えるということは、以下のようなメソッドがクラスに定義されていて、
withの開始、終了でそれぞれのメソッドが呼ばれます

class someClass:

    # with の開始で呼ばれる
    def __enter__(self):
        return self

    # with の終了で呼ばれる
    def __exit__(self, exception_type, exception_value, traceback):
        pass

Unittest を書いてみる

以下のようなソースのUnittestを書こうと思いました。
tempfile.TemporaryDirectory()をmockしてtmp_dir_name固定の値にしたい

  • テストするソース
class processFile():
   def process(self):
        tempfile.TemporaryDirectory() as tmp_dir_name:
            # テンポラリのディレクトリでなにか処理
  • テスト
    @mock.patch("tempfile.TemporaryDirectory")
    def test_process_temp_dir_test(self, mock_TemporaryDirectory):

        proess_file = processFile()

        mock_TemporaryDirectory.return_value.__enter__.return_value = "/tmp"

こんな感じに書いてあげると、tmp_dir_name/tmp に固定できます。

2
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
2
0