【问题标题】:git - treat sub git repository as normal repository for unittests?git - 将子 git 存储库视为单元测试的普通存储库?
【发布时间】:2017-04-02 02:22:53
【问题描述】:

我正在编写一个将一个系统与git 集成的模块。我正在编写测试并希望在测试目录中拥有测试存储库,因此我可以在其上运行单元测试。

模块和项目结构如下所示:

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

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

所以我想知道使用testrepo 进行单元测试的最佳方式是什么。我希望它在源代码控制中,因此整个结构在单元测试中是完整的。

如果从how can I add git submodule into git repo as normal directory? 正确理解的话,将子 git 存储库视为普通存储库是不可能的(仅通过来回修改 git 名称)。

那么我如何才能保留子存储库中的所有更改,所以我只需要拉myproject 并获取所有分支等的testrepo

还是只能作为真正的子模块使用,克隆myproject后需要初始化?

更新

如果我使用testrepo 作为真正的子模块,那么我的测试将停止工作,因为它不再被识别为正常的git repo。

【问题讨论】:

    标签: git git-submodules


    【解决方案1】:

    所以在 repo 中尝试了子模块和真正的 git repo 之后,我继续使用简单的 repo 设置并在测试之间拆除。

    我敢打赌这不是非常理想的解决方案,但目前我没有看到更好的解决方案(更快的可能是以某种方式将 git 隐藏为正常目录,并且在运行测试时,将其更改为被识别为 git repo 并在测试后,再次隐藏它:虽然有点老套)。

    如果有人有更好的想法,请写下来作为答案。

    我的实现示例(使用setUpClass 构建并使用tearDownClass 删除):

    # -*- 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')
    

    【讨论】:

      猜你喜欢
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2018-04-05
      相关资源
      最近更新 更多