Mocking GitPython Repo Calls

huangapple go评论53阅读模式
英文:

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(&quot;-m&quot;, &quot;some commit message&quot;)
        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(&quot;myModule.Repo&quot;)
def test_commit_local_changes(self, mock_repo):
       mock_repo.return_value
            .git.return_value
            .diff.return_value = &#39;file1\nfile2&#39;

but when I print changed_files in the main method and call the mock I see that it's just some MagicMock:

&lt;MagicMock name=&#39;Repo().git.diff().splitlines()&#39; id=&#39;140551053340304&#39;&gt;

答案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 = &quot;file1\nfile2&quot;

huangapple
  • 本文由 发表于 2023年5月11日 05:31:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定