gpt4 book ai didi

python - 为什么 Monkeypatching os.path 需要路径参数?

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:13 25 4
gpt4 key购买 nike

pytest 在 monkeypatching 中有这个例子文档:

import os.path
def getssh(): # pseudo application code
return os.path.join(os.path.expanduser("~admin"), '.ssh')

def test_mytest(monkeypatch):
def mockreturn(path):
return '/abc'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
x = getssh()
assert x == '/abc/.ssh'

当我从 mockreturn 函数中删除 path 参数时,出现错误

    def getssh():  # pseudo application code
> return os.path.join(os.path.expanduser("~admin"), '.ssh')
E TypeError: mockreturn() takes 0 positional arguments but 1 was given

我不明白什么提供了位置参数?

此外,当我为 pathlib.Path.home() 重新实现相同的东西时,我不能在其中使用此参数 path ,否则它将无法工作。不幸的是,文档没有提及任何关于这个不祥的 path 参数。

任何关于这里发生的魔法的说明都会非常有帮助!

最佳答案

您正在尝试替换 os.path.expanduser它接受一个参数,而模拟根本不接受参数,这会在调用时导致错误。引擎盖下monkeypatch.setattr使用内置 setattr 所以原始版本基本上是在执行以下操作,因为 expandusermock采用单个参数:

>>> import os.path
>>> def mock(path):
... return '/abc'
...
>>> setattr(os.path, 'expanduser', mock)
>>> os.path.expanduser('~admin')
'/abc'

现在,如果您尝试替换 expanduser使用不接受参数的方法并继续以同样的方式调用它,您会收到错误:

>>> setattr(os.path, 'expanduser', mock)
>>> os.path.expanduser('~admin')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mock() takes 0 positional arguments but 1 was given

请注意,如果您尝试调用mock,您将得到完全相同的错误。直接:

>>> mock('~admin')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: mock() takes 0 positional arguments but 1 was given

关于python - 为什么 Monkeypatching os.path 需要路径参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41274325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com