【问题标题】:Creating temp GIT repo for testing is not working为测试创建临时 GIT 存储库不起作用
【发布时间】:2021-02-11 19:40:24
【问题描述】:

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

【问题讨论】:

  • 这个怎么样:将整个代码库复制到另一个文件夹,在那里初始化一个新的 git repo,测试你的代码,如果它似乎可以工作,只需将整个代码库复制并粘贴回原始代码库回购并提交更改。注意不要复制.git文件夹,只复制代码。
  • 或者在你的原始仓库上测试它,如果它有效,压缩你所有的“测试”提交。

标签: python git gitlab


【解决方案1】:

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

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

Easiest way to rm -rf in Python

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

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

【讨论】:

  • 嗨 Roman,感谢您的回答 :) 我必须为我的函数 get_commit_sha(repo) 提供一个输入参数 (repo)。我应该在我的箱子里放什么?我的意思是如果我按照你的回答去做。这让我有点困惑。
  • 我改变了我的测试功能,你能看看吗? @Roman 因为我不能将 testrepo 写为输入参数
  • 好吧,您可以使用 git 命令行工具获取提交 sha,使用 popen:stackoverflow.com/a/16561182/12118546 您也可以在不提交的情况下创建空仓库,然后测试您的工具会做什么。你也可以测试会发生什么,当路径完全无效时,零长度以及当它指向没有 git repo 的目录时......你可以测试当 repo 中有更多提交时它会做什么......
  • 有什么办法可以循环执行吗? creatinf 10 文件添加它们并提交?它不会导致 os.system 中的命令是字符串 @roman
  • 对于范围内的文件(0, 10): test_file = "touch file" + str(file) os.system(test_file) os.system("git add .") os.system(" git commit -m 测试")
猜你喜欢
  • 2011-05-01
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 2011-03-12
  • 2020-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多