如何为gitpythonclone/pull函数编写单元测试?
我有一个python项目,它使用GitPython对远程Git存储库执行克隆和拉取功能 举个简单的例子:如何为gitpythonclone/pull函数编写单元测试?,python,git,unit-testing,gitpython,Python,Git,Unit Testing,Gitpython,我有一个python项目,它使用GitPython对远程Git存储库执行克隆和拉取功能 举个简单的例子: import git from git import Git from git import Repo def clone_and_checkout(full_dir, git_url, repo_ver): repo = Repo.clone_from( url=git_url, to_path=full_dir ) # Tr
import git
from git import Git
from git import Repo
def clone_and_checkout(full_dir, git_url, repo_ver):
repo = Repo.clone_from(
url=git_url,
to_path=full_dir
)
# Trigger re-create if repository is bare
if repo.bare:
raise git.exc.InvalidGitRepositoryError
# Set origin and pull
origin = repo.remotes.origin
origin.pull()
# Check out desired version of repository
g = Git(full_dir)
g.checkout(repo_ver)
我希望能够为这个函数编写一个单元测试,但显然,这需要与当前的外部系统联系起来
我很好奇是否有人有过模拟这种外部交互的经验,这种方式类似于使用模拟来模拟HTTP调用。我希望能够以一种在测试时可以模拟的方式执行这些任务,而无需调用实际的Git remote
我应该如何着手为此编写测试
编辑:为了更清楚地说明我的问题,我应该提到我对Mock还不熟悉,并且正在努力理解如何模拟这些类的实例,而不是类本身。我的问题应该用更好的措辞——类似于“如何使用Mock来设置特定于实例的属性,比如bare?”
从那以后,我已经了解了很多关于Mock的知识,并且已经知道了如何做到这一点,所以我将回答我自己的问题。这似乎是由于对Mock的理解不全面,或者使用了补丁方法造成的 首先要做的是阅读位于模拟文档上的“”部分。有了这些信息,您应该能够使用patch函数模拟上述函数中使用的GitPython对象。这些装饰器将出现在单元测试函数的上方
@mock.patch('gitter.Repo')
@mock.patch('gitter.Git')
为了为这些模拟对象之一的实例提供返回值,可以使用。下面是一个充分利用这一点的单元测试示例:
import gitter # file containing our clone function
import mock
import unittest
class test_gitter(unittest.TestCase):
@mock.patch('gitter.Repo')
@mock.patch('gitter.Git')
def runTest(self, mock_git, mock_repo):
# Set the "bare" attribute of the Repo instance to be False
p = mock.PropertyMock(return_value=False)
type(mock_repo.clone_from.return_value).bare = p
gitter.clone_and_checkout(
'/tmp/docker',
'git@github.com:docker/docker.git',
'master'
)
mock_git.checkout.called_once_with('master')
你提到了Mock和
Mock
-你试过了吗?这实际上是我用来模拟GitPython方法的,但我认为我最头疼的是模拟Repo和Git对象。你需要比“挣扎”更具体一些-提供您的尝试的详细信息,并准确描述问题。@jornsharpe-谢谢您的提示。诚然,我写这篇文章时有点匆忙。我将更详细地改进这个问题。