[英]Asserting execution order in python unittest
我有一個函數可以創建一個臨時目錄,切換到該臨時目錄,執行一些工作,然后再切換回原始目錄。 我正在嘗試編寫一個對此進行測試的單元測試。 驗證當前目錄是否已更改為temp dir並再次更改回目錄時,我沒有問題,但是驗證這些調用之間是否發生了重要的事情時,我遇到了問題。
我最初的想法是將函數抽象為三個子函數,以便測試調用順序。 我可以用模擬替換三個子函數中的每一個,以驗證它們是否被調用了-但是,我仍然遇到驗證順序的問題。 在模擬中,我可以使用assert_has_calls,但是在哪個對象上調用該函數?
這是我要測試的課程:
import shutil
import os
import subprocess
import tempfile
import pkg_resources
class Converter:
def __init__(self, encoded_file_path):
self.encoded_file_path = encoded_file_path
self.unencoded_file_path = None
self.original_path = None
self.temp_dir = None
def change_to_temp_dir(self):
self.original_path = os.getcwd()
self.temp_dir = tempfile.mkdtemp()
os.chdir(self.temp_dir)
def change_to_original_dir(self):
os.chdir(self.original_path)
shutil.rmtree(self.temp_dir)
def do_stuff(self):
pass
def run(self):
self.change_to_temp_dir()
self.do_stuff()
self.change_to_original_dir()
就我編寫測試用例而言:
def test_converter(self, pkg_resources, tempfile, subprocess, os, shutil):
encoded_file_path = Mock()
converter = Converter(encoded_file_path)
converter.change_to_temp_dir = Mock()
converter.do_stuff= Mock()
converter.change_to_original_dir = Mock()
assert converter.encoded_file_path == encoded_file_path
assert converter.unencoded_file_path is None
converter.run()
現在,我已經模擬了每個函數,可以驗證它們是否被調用,但不能以什么ORDER進行驗證。 我該怎么做呢?
一種解決方法是創建一個單獨的模擬對象,將方法附加到該對象上,然后使用assert_has_calls()
檢查調用順序:
converter = Converter(encoded_file_path)
converter.change_to_temp_dir = Mock()
converter.do_stuff = Mock()
converter.change_to_original_dir = Mock()
m = Mock()
m.configure_mock(first=converter.change_to_temp_dir,
second=converter.do_stuff,
third=converter.change_to_original_dir)
converter.run()
m.assert_has_calls([call.first(), call.second(), call.third()])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.