[英]How to write a pytest unit test for a function if it uses __init__ values?
我喜欢使用 pytest 为提取 function 编写单元测试,但这取决于init ,所以我的问题是如何为提取 ZC1C425268E68385D1AB5074C17A 编写单元测试? 此外,我需要确保提取调用 _funct_2 或 funct_3 是否取决于初始化值。
class Extraction:
def __init__(self, spark: SparkSession, dbutils: DBUtils, params: dict):
self._params = params
self._spark = spark
self._dbutils = dbutils
self.logger = getLogger(Extraction.__name__)
def extract(self) -> DataFrame:
file_path = self._params["RawFilePath"]
path_length = len(file_path)
self.logger.info("determine extraction method based on file length: {}".format(path_length))
if len(file_path) == 0:
self.logger.info("funct_2/db extraction case")
return self._funct_2()
else:
self.logger.info("file based")
return self._funct_3()
不确定,但可能是您将两个概念混为一谈。
如果你想编写一个单元测试来测试一些提取功能(依赖于一个完全初始化的提取对象),你可以简单地把它写在一个测试模块中:
玩具 EG: test_extraction.py
def test_toy_extract():
extract_obj = Extraction(...init params...)
assert extract_obj.extract() == "Whatever"
然后只需在上述模块上运行pytest
。
On the other hand, if you need setup (or teardown) behavior on a whole test module, class, or function, can do that: https://docs.pytest.org/en/stable/xunit_setup.html#class-level -setup-teardown
您可以使用 pytest 夹具为您的测试创建一个 object,然后将 object 传递给您的 ZA8ZFDE6331CCBD4B662AC 方法的测试。
@pytest.fixture
def edb():
# you need to specify parameter values here
# this should be database, not file in params
return Extraction(spark, dbutils, params)
@pytest.fixture
def efile():
# you need to specify parameter values here
# this should be file in params
return Extraction(spark, dbutils, params)
def test_extract_funct2(edb):
# test the _funct2 use case
def test_extract_funct3(efile):
# test the _funct3 use case
我认为如果您将文件路径作为要extract.
然后你可以使用相同的 object 并只需更改 file_path 参数。 现在设置的方式,你可以设置 _params["RawFilePath"],但这很尴尬。
def extract(self, file_path: str = None) -> DataFrame:
if not file_path:
file_path = self._params.get("RawFilePath")
# rest of method
此外,对file_path
的检测似乎可能会引发错误,因为如果您不使用 RawFilePath 键,则没有理由为它包含一个空白值。 您可以使用get
代替,然后测试是否存在而不是按长度。 这比获取字符串的长度或 None 值更简单,更 Pythonic。
if self._params.get("RawFilePath"):
self.logger.info("funct_2/db extraction case")
return self._funct_2()
self.logger.info("file based")
return self._funct_3()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.