英文:
Mocking GitPython Repo Calls
问题
I've translated the code sections for you:
我有一个带有添加未暂存更改并提交它们的函数的类,用于 Git 存储库
我正在尝试编写单元测试来测试此功能,并希望 `repo.git.diff(None, name_only=True)` 实际返回不同于模拟的内容。我已尝试设置测试如下:
@patch("myModule.Repo")
def test_commit_local_changes(self, mock_repo):
mock_repo.return_value
.git.return_value
.diff.return_value = 'file1\nfile2'
但是,当我在主方法中打印`changed_files`并调用模拟时,我看到它只是一些 MagicMock:
<MagicMock name='Repo().git.diff().splitlines()' id='140551053340304'>
英文:
I've got a class with a function that adds unstaged changes in a git repo and commits them
def commit_local_changes(self, repo_path):
repo = Repo(repo_path)
changed_files = repo.git.diff(None, name_only=True).splitlines()
if changed_files:
for file in changed_files:
repo.git.add(file)
repo.git.commit("-m", "some commit message")
return repo.head.object.hexsha
I'm trying to write unit tests to go over this functionality and I was to have repo.git.diff(None, name_only=True)
actually return something besides a mock. I've tried to set up the tests like so:
@patch("myModule.Repo")
def test_commit_local_changes(self, mock_repo):
mock_repo.return_value
.git.return_value
.diff.return_value = 'file1\nfile2'
but when I print changed_files
in the main method and call the mock I see that it's just some MagicMock:
<MagicMock name='Repo().git.diff().splitlines()' id='140551053340304'>
答案1
得分: 1
问题出在我对Python的属性模拟与函数返回值的理解不够。在我的情况下,Repo()是一个创建Repo类实例的函数(Python可能对这些有不同的命名,我更熟悉Java)。因此,我需要模拟Repo()的返回值,然后Python会为我模拟其属性,然后我需要模拟对diff()的调用的返回值。以下代码可以解决问题:
mock_repo.return_value.git.diff.return_value = "file1\nfile2"
英文:
My issue was a lack of understanding of Python's attribute mocking versus return value for a function result.
In my case, Repo() is a function creating an instance of the class Repo (python may have different names for these, I'm more familiar with Java). So I needed to mock the return value of Repo(), then Python will mock it's attributes for me, then I needed to mock the return value of the call to diff(). The following worked:
mock_repo.return_value.git.diff.return_value = "file1\nfile2"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论