remote: pass more context down to the remote model actions
[git-cola.git] / test / helper.py
blobb06600b3d7dcffa1cd3b106b4288e2b9f732ad04
1 from __future__ import absolute_import, division, 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):
42 def setUp(self):
43 self._testdir = tempfile.mkdtemp('_cola_test')
44 os.chdir(self._testdir)
46 def tearDown(self):
47 """Remove the test directory and return to the tmp root."""
48 path = self._testdir
49 os.chdir(tmp_path())
50 shutil.rmtree(path, onerror=remove_readonly)
52 @staticmethod
53 def touch(*paths):
54 for path in paths:
55 open(path, 'a').close()
57 @staticmethod
58 def write_file(path, content):
59 with open(path, 'w') as f:
60 f.write(content)
62 @staticmethod
63 def append_file(path, content):
64 with open(path, 'a') as f:
65 f.write(content)
67 def test_path(self, *paths):
68 return os.path.join(self._testdir, *paths)
71 class GitRepositoryTestCase(TmpPathTestCase):
72 """Tests that operate on temporary git repositories."""
74 def setUp(self, commit=True):
75 TmpPathTestCase.setUp(self)
76 self.initialize_repo()
77 if commit:
78 self.commit_files()
79 git.current().set_worktree(core.getcwd())
80 gitcfg.current().reset()
81 gitcmds.reset()
83 def git(self, *args):
84 p = subprocess.Popen(['git'] + list(args), stdout=subprocess.PIPE,
85 stderr=subprocess.PIPE)
86 output, error = p.communicate()
87 self.failIf(p.returncode != 0)
88 return output.strip()
90 def initialize_repo(self):
91 self.git('init')
92 self.git('config', '--local', 'user.name', 'Your Name')
93 self.git('config', '--local', 'user.email', 'you@example.com')
94 self.touch('A', 'B')
95 self.git('add', 'A', 'B')
97 def commit_files(self):
98 self.git('commit', '-m', 'initial commit')