Merge pull request #520 from bariscelik/master
[git-cola.git] / test / helper.py
blob64d0dfc4f23734e31bc6cf6b1a3f8a10e97da1e8
1 from __future__ import unicode_literals
3 import os
4 import shutil
5 import stat
6 import unittest
7 import subprocess
8 import tempfile
10 from cola import core
11 from cola import git
12 from cola import gitcfg
13 from cola import gitcmds
16 def tmp_path(*paths):
17 """Returns a path relative to the test/tmp directory"""
18 return os.path.join(os.path.dirname(__file__), 'tmp', *paths)
21 def fixture(*paths):
22 return os.path.join(os.path.dirname(__file__), 'fixtures', *paths)
25 def run_unittest(suite):
26 return unittest.TextTestRunner(verbosity=2).run(suite)
29 # shutil.rmtree() can't remove read-only files on Windows. This onerror
30 # handler, adapted from <http://stackoverflow.com/a/1889686/357338>, works
31 # around this by changing such files to be writable and then re-trying.
32 def remove_readonly(func, path, exc_info):
33 if func == os.remove and not os.access(path, os.W_OK):
34 os.chmod(path, stat.S_IWRITE)
35 func(path)
36 else:
37 raise
40 class TmpPathTestCase(unittest.TestCase):
41 def setUp(self):
42 self._testdir = tempfile.mkdtemp('_cola_test')
43 os.chdir(self._testdir)
45 def tearDown(self):
46 """Remove the test directory and return to the tmp root."""
47 path = self._testdir
48 os.chdir(tmp_path())
49 shutil.rmtree(path, onerror=remove_readonly)
51 @staticmethod
52 def touch(*paths):
53 for path in paths:
54 open(path, 'a').close()
56 @staticmethod
57 def write_file(path, content):
58 with open(path, 'w') as f:
59 f.write(content)
61 @staticmethod
62 def append_file(path, content):
63 with open(path, 'a') as f:
64 f.write(content)
66 def test_path(self, *paths):
67 return os.path.join(self._testdir, *paths)
70 class GitRepositoryTestCase(TmpPathTestCase):
71 """Tests that operate on temporary git repositories."""
72 def setUp(self, commit=True):
73 TmpPathTestCase.setUp(self)
74 self.initialize_repo()
75 if commit:
76 self.commit_files()
77 git.current().set_worktree(core.getcwd())
78 gitcfg.current().reset()
79 gitcmds.reset()
81 def git(self, *args):
82 p = subprocess.Popen(['git'] + list(args), stdout=subprocess.PIPE,
83 stderr=subprocess.PIPE)
84 output, error = p.communicate()
85 self.failIf(p.returncode != 0)
86 return output.strip()
88 def initialize_repo(self):
89 self.git('init')
90 self.git('config', '--local', 'user.name', 'Your Name')
91 self.git('config', '--local', 'user.email', 'you@example.com')
92 self.touch('A', 'B')
93 self.git('add', 'A', 'B')
95 def commit_files(self):
96 self.git('commit', '-m', 'initial commit')