簡體   English   中英

如何測試關閉 PIL 圖像的方法(使用 unittest)?

[英]How do I test a method (using unittest) that closes a PIL image?

我有一個方法( close() ),它是我的 class ( Img )的一部分,如下所示:

    def close(self):
        Image.Image.close(self.image)

我一直在努力尋找一種方法來使用unittest package 測試此方法,因為它不返回任何內容,而且我不知道是否有辦法實際檢查圖像是否關閉。

先感謝您!

您可以使用unittest.mock.patch方法來模擬PIL package 和Image.Image.close方法。 調用img.close()方法后,可以使用assert_call_once_with(*args, **kwargs)檢查Image.Image.close方法是否被調用。

例如

img.py

from PIL import Image


class Img:
    def __init__(self):
        self.image = '123'

    def close(self):
        Image.Image.close(self.image)

test_img.py

import unittest
from unittest import mock
from img import Img


class TestImg(unittest.TestCase):
    @mock.patch('img.Image')
    def test_close(self, mock_Image):
        my_img = Img()
        my_img.close()
        mock_Image.Image.close.assert_called_once_with('123')


if __name__ == '__main__':
    unittest.main()

帶有覆蓋率報告的單元測試結果:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Name                                     Stmts   Miss  Cover   Missing
----------------------------------------------------------------------
src/stackoverflow/63132966/img.py            6      0   100%
src/stackoverflow/63132966/test_img.py      10      0   100%
----------------------------------------------------------------------
TOTAL                                       16      0   100%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM