python - 为测试创建临时 GIT 存储库不起作用
问题描述
大家好,我的函数 (get_commit_sha) 从最新提交中获取提交 sha。我现在必须测试这个功能。为此,我必须创建不同的测试场景和几个临时 git 存储库,仅用于测试,这些存储库将在测试函数中创建。在这个存储库中,我想推送“fake”、“senseles”提交,只是为了测试功能。
解决方案
只需使用tempfile
标准库创建临时目录:
https://docs.python.org/3/library/tempfile.html
将工作目录更改为新的临时目录:https ://docs.python.org/3/library/os.html#os.chdir
然后使用os.system("git init && touch file && git add file && git commit -m Test")
或使用 git python 库:
https://gitpython.readthedocs.io/en/stable/tutorial.html#tutorial-label
通过删除临时目录进行清理:
例如:像这样创建测试仓库:
import os
import tempfile
def test_repo():
"""Creates test repository with single commit and return its path."""
temporary_dir = tempfile.mkdtemp()
os.chdir(temporary_dir)
os.system("git init")
os.system("touch file1")
os.system("git add file1")
os.system("git commit -m Test")
return temporary_dir
print(test_repo())
推荐阅读
- function - Shell 参数作为 Fortran 的参数
- r - rbind.zoo(...) 的问题:索引在滞后函数中重叠
- javascript - 如何判断一个对象是否是类型化数组?
- reactjs - .如何使用 ref 在本机反应中清除自定义输入
- html - 在引导程序中将页面右侧的内容显示为块
- kubernetes - 计算节点关闭后 Pod 卡在“终止”状态
- elasticsearch - 如何在完整的字典中搜索
- python - 如何从python中给定的字符串选择中随机打印一个字符串
- c# - 现有 ADO.NET 代码和 EF 的 C# 数据访问层
- ubuntu - 如何在最新的 ubuntu 上安装 gcc-3.4 和 g++-3.4?