python - python - 使用PyTest进行python测试时如何模拟对象?
问题描述
在测试期间,我需要模拟一个对象。我目前正在使用 Pytest 和 monkeypatch 进行模拟。
示例函数:
def isGccInstalled():
gccInstallationFound = False
command = ['gcc', '-v']
process = subprocess.Popen(command, bufsize=1, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if process.stdout.readline:
gccInstallationFound = True
return gccInstallationFound
我对该功能的测试:
def mock_subprocess_Popen(*args, **kwargs):
return
def test_getSwBlockType(monkeypatch):
monkeypatch.setattr(subprocess, "Popen", mock_subprocess_Popen)
assert isGccInstalled() == "False"
我需要以某种方式模拟流程对象并将我自己的字符串写入 process.stdout.readline。我知道我可以使用 monkeypatch.setattr 模拟单个变量,但我不知道如何模拟对象甚至是从其他类继承的对象。有没有办法告诉我的模拟返回一个可以访问“process.stdout.readline”的虚拟数据结构?
解决方案
推荐阅读
- java - 为什么 JSON 响应是 200
- sql - SQL server 根据键合并行
- android - 使用 GreenDao 时启用 proguard 的发布版本中的应用程序崩溃
- javascript - D3 Zoom 的 translateExtent 未按预期工作
- flutter - Flutter Mobile 和 Web 包同居
- python - 为什么要执行这些类定义中的代码?
- javascript - 如何在控制台的 Angular 下拉菜单中设置范围值?
- javascript - InfoWindows 有一些问题。不太确定如何处理它
- google-cloud-data-fusion - 相当于谷歌云数据融合数据管道牧马人中的 LEFT() 函数?
- vim - 无法让 vim 8.0 终端 API 工作到 vim