git - 将sub git存储库视为unittests的正常存储库?

问题描述:

我在写一个模块,它将一个系统与git集成在一起。我正在编写测试,并希望在测试目录中有测试存储库,所以我可以在其上运行unittests。git - 将sub git存储库视为unittests的正常存储库?

模块和项目结构如下:

myproject/ 
    mymodule/ 
    some_dir/ 
    tests/ 
     __init__.py 
     testrepo/ 
     /.git 
     test_some.py 
    /.git 

现在虽然我发展,这是工作。我可以使用testrepo运行测试。虽然我注意到,当我提交时,git开始自动处理testrepo作为子项目。所以基本上它不会跟踪发生的所有变化。如果实际代码发生更改,则会将其识别为子项目/子模块更改。但是,如果我说增加新的分支,那些改变不会被识别(除非我会检查它等)。

所以我想知道什么可能是最好的方式使用testrepo unittests。我希望它能够在源代码控制中,所以整个结构对于单元测试是完整的。

如果从how can I add git submodule into git repo as normal directory?正确理解,它不是真的有可能(只是有点黑客git名字来回)将子git存储库视为正常的存储库。

那么我如何保存子存储库中的所有更改,所以我需要拉myproject并获得testrepo与所有分支机构等?

或者我只能用它作为真正的子模块,需要在克隆之后初始化它myproject

更新

如果我使用testrepo作为真正的子模块,然后我的测试中停止工作,因为它不再识别为正常git回购。

所以在尝试子模块和回购里面的真正的git回购后,我使用简单的回购设置和拆卸测试之间。

我敢打赌,这不是最理想的解决方案,但现在我没有看到任何更好的解决方案(速度可能会以某种方式隐藏git作为普通目录,并在运行测试时将其更改为git repo,测试,再次隐藏它:虽然有点哈克)。

如果有人有更好的想法,请将其写为答案。

我实现样品(它使用setUpClasstearDownClass建成并删除使用):

# -*- coding: utf-8 -*- 
import os 
import sh 
import shutil 


class cd: 
    """Context manager for changing the current working directory""" 
    def __init__(self, newPath): 
     self.newPath = os.path.expanduser(newPath) 

    def __enter__(self): 
     self.savedPath = os.getcwd() 
     os.chdir(self.newPath) 

    def __exit__(self, etype, value, traceback): 
     os.chdir(self.savedPath) 


def build_test_repo(dir_path): 
    """Build testrepo for unittests.""" 
    def git_add_file(g, txt): 
     """create, add and commit dummy file.""" 
     with open('%s.txt' % txt, 'w') as f: 
      f.write('%s content' % txt) 
     # add and commit 
     g.add('%s.txt' % txt) 
     g.commit('-m', '[ADD] %s.txt' % txt) 

    path = "%s/%s" % (dir_path, 'testrepo') 
    os.makedirs(path) 
    # change dir to initialize repo. We use context manager, so after 
    # setting up repo, we would get back to previous working directory. 
    with cd(path): 
     # git from shell 
     g = sh.git 
     g.init() 
     git_add_file(g, 't0') 
     # create f1 branch 
     g.checkout('-b', 'f1') 
     # add and commit for f1 
     git_add_file(g, 't1') 
     # create f2 branch from master 
     g.checkout('master') 
     g.checkout('-b', 'f2') 
     git_add_file(g, 't2') 
     # create copy of master without any difference. 
     g.checkout('master') 
     g.checkout('-b', 'master_copy')