簡體   English   中英

如何模擬與正在測試的方法相同的 class 中的方法?

[英]How to mock a method from the same class that the method being tested?

我有以下項目結構

repo
|
|--utils
|----hudi.py
|----__init__.py
|--tests
|----test_hudi.py
|----__init__.py

我想測試 hudi.py 中的hudi.py ,它是:

class Partitions:
    def __init__(self, bucket, table)
        self.bucket = bucket
        self.table = table
    
    def get_partitions(self):
        return [
            f"s3://{self.bucket}/{self.table}{i}" 
            for i in list(range(10))
            if self.path_exists(i)
        ]

    def path_exists(self, i):
        s3_paths = code using external libraries
        if s3_paths:
            return True
        else:
            return False

我在文件test_hudi.py中編寫了測試代碼如下:

from utils import hudi

class TestHudi(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        cls.hudi_partitions = hudi.Partitions(
            table="signal",
            bucket="bkt_name",
        )

    def test_get_partitions(self):
        p = self.hudi_partitions.get_partitions()
        assert p = ["s3://bkt_name/signal1"]

為了能夠執行上述測試,我需要模擬 function path_exist ,並使其返回值為真,因此我嘗試使用以下補丁模擬它:

@mock.patch("utils.hudi.path_exists", return_value=True)
@mock.patch("utils.hudi.partitions.path_exists", return_value=True)
@mock.patch("hudi_partitions.path_exists", return_value=True)
@mock.patch("hudi.partitions.path_exists", return_value=True)
@mock.patch("hudi.path_exists", return_value=True)

而且它們都不起作用。

有什么辦法可以模擬 function path_exists 嗎? 謝謝!

據我了解你應該是 mocking 使用外部庫。 此外,通過這種方式,您可以測試路徑存在或不存在時會發生什么。

如果您仍想完成此操作,請考慮以下事項。 實際上,您可以很容易地替換 python 中的 class function 參考:

>>> class Test:
...   def dummy(self):
...     print("Original Test")
...
>>> test = Test()
>>> test.dummy()
Original Test
>>> def new_dummy():
...   print("New Test")
...
>>> test.dummy = new_dummy
>>> test.dummy()
New Test

暫無
暫無

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

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