首页 > 解决方案 > 为测试创建临时 GIT 存储库不起作用

问题描述

大家好,我的函数 (get_commit_sha) 从最新提交中获取提交 sha。我现在必须测试这个功能。为此,我必须创建不同的测试场景和几个临时 git 存储库,仅用于测试,这些存储库将在测试函数中创建。在这个存储库中,我想推送“fake”、“senseles”提交,只是为了测试功能。

标签: pythongitgitlab

解决方案


只需使用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

通过删除临时目录进行清理:

在 Python 中使用 rm -rf 的最简单方法

例如:像这样创建测试仓库:

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())

推荐阅读