Python 3.x 如何编写用于检查git_状态的模拟单元测试?
我正在尝试为我的一个函数编写一个模拟单元测试,用于检查Python 3.x 如何编写用于检查git_状态的模拟单元测试?,python-3.x,mocking,pytest,python-unittest,Python 3.x,Mocking,Pytest,Python Unittest,我正在尝试为我的一个函数编写一个模拟单元测试,用于检查git\u状态。我不知道该怎么做。 该函数如下所示: import git_status def check_git_status(): status = git_status.Status(".") if status.A != []: raise RuntimeError( 'Added git files not commited: {}'.format(
git\u状态
。我不知道该怎么做。
该函数如下所示:
import git_status
def check_git_status():
status = git_status.Status(".")
if status.A != []:
raise RuntimeError(
'Added git files not commited: {}'.format(status.A)
)
elif status.M != []:
raise RuntimeError(
'Modified git files not commited: {}'.format(status.M)
)
elif status.D != []:
raise RuntimeError(
'Deleted git files not commited: {}'.format(status.D)
)
elif status.R != []:
raise RuntimeError(
'Renamed git files not commited: {}'.format(status.R)
)
我试过什么:
import pytest
from unittest import mock
@pytest.mark.parametrize(
"status, expected_status",
[
("A", []), ("M", []), ("D", []), ("R", []),
("B", 'error')
])
@mock.patch("git_status.Status", autospec=True)
def test_check_git_status(mock_git_status, status, expected_status):
if expected_status != 'error':
mock_git_status = mock.Mock(name="mock git status", **{str(status): expected_status})
else:
with pytest.raises(RuntimeError):
check_git_status()
如果有人能在这里指导/帮助我,那就太好了。谢谢:)当我试图重现问题时,测试正在通过;请添加一个。Hi@hoefling,是的,这一个通过了测试,但我不确定是否写对了。这也可能是侥幸。所以,我需要一双新的眼睛来观察它,并引导我,就好像这是写对了还是没有写对一样。例如,如果我将(“A”,[])改为(“A”,“error”),那么这个测试仍然通过,这应该是错误的。为什么测试不应该通过呢?看看您的测试函数体:如果状态为错误,将引发并截获异常。如果状态不是错误,则会创建mock(可能是针对
check\u git\u status
?)并且不会发生任何其他情况,因此测试也会通过。您可能根本不需要else
块。这就是为什么我问一个问题,从哪里可以清楚地看到与预期行为的偏差。