about: update contributors for v3.2
[git-cola.git] / test / helper.py
blob281a5ec5acd69e42073158583efc0fc0c7f54b9f
1 from __future__ import absolute_import, division, unicode_literals
2 import os
3 import shutil
4 import stat
5 import unittest
6 import subprocess
7 import tempfile
9 import mock
11 from cola import core
12 from cola import git
13 from cola import gitcfg
14 from cola import gitcmds
17 def tmp_path(*paths):
18 """Returns a path relative to the test/tmp directory"""
19 dirname = core.decode(os.path.dirname(__file__))
20 return os.path.join(dirname, 'tmp', *paths)
23 def fixture(*paths):
24 dirname = core.decode(os.path.dirname(__file__))
25 return os.path.join(dirname, 'fixtures', *paths)
28 def run_unittest(suite):
29 return unittest.TextTestRunner(verbosity=2).run(suite)
32 # shutil.rmtree() can't remove read-only files on Windows. This onerror
33 # handler, adapted from <http://stackoverflow.com/a/1889686/357338>, works
34 # around this by changing such files to be writable and then re-trying.
35 def remove_readonly(func, path, exc_info):
36 if func == os.remove and not os.access(path, os.W_OK):
37 os.chmod(path, stat.S_IWRITE)
38 func(path)
39 else:
40 raise
43 class TmpPathTestCase(unittest.TestCase):
45 def setUp(self):
46 self._testdir = tempfile.mkdtemp('_cola_test')
47 os.chdir(self._testdir)
49 def tearDown(self):
50 """Remove the test directory and return to the tmp root."""
51 path = self._testdir
52 os.chdir(tmp_path())
53 shutil.rmtree(path, onerror=remove_readonly)
55 @staticmethod
56 def touch(*paths):
57 for path in paths:
58 open(path, 'a').close()
60 @staticmethod
61 def write_file(path, content):
62 with open(path, 'w') as f:
63 f.write(content)
65 @staticmethod
66 def append_file(path, content):
67 with open(path, 'a') as f:
68 f.write(content)
70 def test_path(self, *paths):
71 return os.path.join(self._testdir, *paths)
74 class GitRepositoryTestCase(TmpPathTestCase):
75 """Tests that operate on temporary git repositories."""
77 def setUp(self, commit=True):
78 TmpPathTestCase.setUp(self)
79 self.initialize_repo()
80 if commit:
81 self.commit_files()
82 self.context = context = mock.Mock()
83 context.git = git.create()
84 context.git.set_worktree(core.getcwd())
85 context.cfg = gitcfg.create(context)
86 gitcmds.reset()
88 def git(self, *args):
89 status, out, err = core.run_command(['git'] + list(args))
90 self.assertEqual(status, 0)
91 return out
93 def initialize_repo(self):
94 self.git('init')
95 self.git('config', '--local', 'user.name', 'Your Name')
96 self.git('config', '--local', 'user.email', 'you@example.com')
97 self.touch('A', 'B')
98 self.git('add', 'A', 'B')
100 def commit_files(self):
101 self.git('commit', '-m', 'initial commit')