2017-04-01 160 views
0

我在寫一個模塊,它將一個系統與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回購。

回答

0

所以在嘗試子模塊和回購裏面的真正的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')