Skip to content

Commit e61439b

Browse files
committed
src: constify is_<platform>() calls
+ TCs: unittest-asserts for git-tests.
1 parent df2fb54 commit e61439b

13 files changed

+45
-52
lines changed

git/cmd.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555

5656
__all__ = ('Git',)
5757

58-
if is_win():
58+
if is_win:
5959
WindowsError = OSError
6060

6161
if PY3:
@@ -239,7 +239,7 @@ def dict_to_slots_and__excluded_are_none(self, d, excluded=()):
239239
## CREATE_NEW_PROCESS_GROUP is needed to allow killing it afterwards,
240240
# seehttps://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal
241241
PROC_CREATIONFLAGS = (CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
242-
if is_win()
242+
if is_win
243243
else 0)
244244

245245

@@ -630,7 +630,7 @@ def execute(self, command,
630630
env["LC_ALL"] = "C"
631631
env.update(self._environment)
632632

633-
if is_win():
633+
if is_win:
634634
cmd_not_found_exception = WindowsError
635635
if kill_after_timeout:
636636
raise GitCommandError('"kill_after_timeout" feature is not supported on Windows.')
@@ -650,13 +650,13 @@ def execute(self, command,
650650
stderr=PIPE,
651651
stdout=PIPE if with_stdout else open(os.devnull, 'wb'),
652652
shell=self.USE_SHELL,
653-
close_fds=(is_posix()), # unsupported on windows
653+
close_fds=(is_posix), # unsupported on windows
654654
universal_newlines=universal_newlines,
655655
creationflags=PROC_CREATIONFLAGS,
656656
**subprocess_kwargs
657657
)
658658
except cmd_not_found_exception as err:
659-
raise GitCommandNotFound(str(err))
659+
raise GitCommandNotFound('%s: %s' % (command[0], err))
660660

661661
if as_process:
662662
return self.AutoInterrupt(proc, command)

git/compat.py

+3-11
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
)
2525

2626
PY3 = sys.version_info[0] >= 3
27+
is_win = (os.name == 'nt')
28+
is_posix = (os.name == 'posix')
29+
is_darwin = (os.name == 'darwin')
2730
defenc = sys.getdefaultencoding()
2831

2932
if PY3:
@@ -78,17 +81,6 @@ def __new__(cls, name, nbases, d):
7881
return meta(name, bases, d)
7982
return metaclass(meta.__name__ + 'Helper', None, {})
8083

81-
def is_win():
82-
return os.name == 'nt'
83-
84-
85-
def is_posix():
86-
return os.name == 'posix'
87-
88-
89-
def is_darwin():
90-
return os.name == 'darwin'
91-
9284

9385
## From https://docs.python.org/3.3/howto/pyporting.html
9486
class UnicodeMixin(object):

git/index/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def _set_cache_(self, attr):
137137
# which happens during read-tree.
138138
# In this case, we will just read the memory in directly.
139139
# Its insanely bad ... I am disappointed !
140-
allow_mmap = (is_win() or sys.version_info[1] > 5)
140+
allow_mmap = (is_win or sys.version_info[1] > 5)
141141
stream = file_contents_ro(fd, stream=True, allow_mmap=allow_mmap)
142142

143143
try:

git/index/fun.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def run_commit_hook(name, index):
7676
stdout=subprocess.PIPE,
7777
stderr=subprocess.PIPE,
7878
cwd=index.repo.working_dir,
79-
close_fds=(is_posix()),
79+
close_fds=(is_posix),
8080
creationflags=PROC_CREATIONFLAGS,)
8181
stdout, stderr = cmd.communicate()
8282
cmd.stdout.close()

git/remote.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ def __init__(self, repo, name):
376376
self.repo = repo
377377
self.name = name
378378

379-
if is_win():
379+
if is_win:
380380
# some oddity: on windows, python 2.5, it for some reason does not realize
381381
# that it has the config_writer property, but instead calls __getattr__
382382
# which will not yield the expected results. 'pinging' the members

git/repo/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,7 @@ def delete_remote(self, remote):
370370
def _get_config_path(self, config_level):
371371
# we do not support an absolute path of the gitconfig on windows ,
372372
# use the global config instead
373-
if is_win() and config_level == "system":
373+
if is_win and config_level == "system":
374374
config_level = "global"
375375

376376
if config_level == "system":
@@ -884,7 +884,7 @@ def _clone(cls, git, url, path, odb_default_type, progress, **kwargs):
884884
prev_cwd = None
885885
prev_path = None
886886
odbt = kwargs.pop('odbt', odb_default_type)
887-
if is_win():
887+
if is_win:
888888
if '~' in path:
889889
raise OSError("Git cannot handle the ~ character in path %r correctly" % path)
890890

git/test/lib/helper.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def _mktemp(*args):
7474
prefixing /private/ will lead to incorrect paths on OSX."""
7575
tdir = tempfile.mktemp(*args)
7676
# See :note: above to learn why this is comented out.
77-
# if is_darwin():
77+
# if is_darwin:
7878
# tdir = '/private' + tdir
7979
return tdir
8080

@@ -84,7 +84,7 @@ def _rmtree_onerror(osremove, fullpath, exec_info):
8484
Handle the case on windows that read-only files cannot be deleted by
8585
os.remove by setting it to mode 777, then retry deletion.
8686
"""
87-
if is_win() or osremove is not os.remove:
87+
if is_win or osremove is not os.remove:
8888
raise
8989

9090
os.chmod(fullpath, 0o777)
@@ -141,7 +141,7 @@ def repo_creator(self):
141141

142142

143143
def launch_git_daemon(temp_dir, ip, port):
144-
if is_win():
144+
if is_win:
145145
## On MINGW-git, daemon exists in .\Git\mingw64\libexec\git-core\,
146146
# but if invoked as 'git daemon', it detaches from parent `git` cmd,
147147
# and then CANNOT DIE!
@@ -242,7 +242,7 @@ def remote_repo_creator(self):
242242
gd.proc.terminate()
243243
log.warning('git(%s) ls-remote failed due to:%s',
244244
rw_repo.git_dir, e)
245-
if is_win():
245+
if is_win:
246246
msg = textwrap.dedent("""
247247
MINGW yet has problems with paths, and `git-daemon.exe` must be in PATH
248248
(look into .\Git\mingw64\libexec\git-core\);

git/test/test_base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def test_with_rw_remote_and_rw_repo(self, rw_repo, rw_remote_repo):
118118
assert rw_remote_repo.config_reader("repository").getboolean("core", "bare")
119119
assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib'))
120120

121-
@skipIf(sys.version_info < (3,) and is_win(),
121+
@skipIf(sys.version_info < (3,) and is_win,
122122
"Unicode woes, see https://github.com/gitpython-developers/GitPython/pull/519")
123123
@with_rw_repo('0.1.6')
124124
def test_add_unicode(self, rw_repo):
@@ -135,7 +135,7 @@ def test_add_unicode(self, rw_repo):
135135

136136
open(file_path, "wb").write(b'something')
137137

138-
if is_win():
138+
if is_win:
139139
# on windows, there is no way this works, see images on
140140
# https://github.com/gitpython-developers/GitPython/issues/147#issuecomment-68881897
141141
# Therefore, it must be added using the python implementation

git/test/test_git.py

+19-18
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def test_it_transforms_kwargs_into_git_command_arguments(self):
8585

8686
# order is undefined
8787
res = self.git.transform_kwargs(**{'s': True, 't': True})
88-
assert ['-s', '-t'] == res or ['-t', '-s'] == res
88+
self.assertEqual(set(['-s', '-t']), set(res))
8989

9090
def test_it_executes_git_to_shell_and_returns_result(self):
9191
assert_match('^git version [\d\.]{2}.*$', self.git.execute(["git", "version"]))
@@ -117,7 +117,7 @@ def test_persistent_cat_file_command(self):
117117
g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
118118
g.stdin.flush()
119119
obj_info_two = g.stdout.readline()
120-
assert obj_info == obj_info_two
120+
self.assertEqual(obj_info, obj_info_two)
121121

122122
# read data - have to read it in one large chunk
123123
size = int(obj_info.split()[2])
@@ -127,18 +127,19 @@ def test_persistent_cat_file_command(self):
127127
# now we should be able to read a new object
128128
g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
129129
g.stdin.flush()
130-
assert g.stdout.readline() == obj_info
130+
self.assertEqual(g.stdout.readline(), obj_info)
131131

132132
# same can be achived using the respective command functions
133133
hexsha, typename, size = self.git.get_object_header(hexsha)
134134
hexsha, typename_two, size_two, data = self.git.get_object_data(hexsha)
135-
assert typename == typename_two and size == size_two
135+
self.assertEqual(typename, typename_two)
136+
self.assertEqual(size, size_two)
136137

137138
def test_version(self):
138139
v = self.git.version_info
139-
assert isinstance(v, tuple)
140+
self.assertIsInstance(v, tuple)
140141
for n in v:
141-
assert isinstance(n, int)
142+
self.assertIsInstance(n, int)
142143
# END verify number types
143144

144145
def test_cmd_override(self):
@@ -174,28 +175,28 @@ def test_insert_after_kwarg_raises(self):
174175
def test_env_vars_passed_to_git(self):
175176
editor = 'non_existant_editor'
176177
with mock.patch.dict('os.environ', {'GIT_EDITOR': editor}):
177-
assert self.git.var("GIT_EDITOR") == editor
178+
self.assertEqual(self.git.var("GIT_EDITOR"), editor)
178179

179180
@with_rw_directory
180181
def test_environment(self, rw_dir):
181182
# sanity check
182-
assert self.git.environment() == {}
183+
self.assertEqual(self.git.environment(), {})
183184

184185
# make sure the context manager works and cleans up after itself
185186
with self.git.custom_environment(PWD='/tmp'):
186-
assert self.git.environment() == {'PWD': '/tmp'}
187+
self.assertEqual(self.git.environment(), {'PWD': '/tmp'})
187188

188-
assert self.git.environment() == {}
189+
self.assertEqual(self.git.environment(), {})
189190

190191
old_env = self.git.update_environment(VARKEY='VARVALUE')
191192
# The returned dict can be used to revert the change, hence why it has
192193
# an entry with value 'None'.
193-
assert old_env == {'VARKEY': None}
194-
assert self.git.environment() == {'VARKEY': 'VARVALUE'}
194+
self.assertEqual(old_env, {'VARKEY': None})
195+
self.assertEqual(self.git.environment(), {'VARKEY': 'VARVALUE'})
195196

196197
new_env = self.git.update_environment(**old_env)
197-
assert new_env == {'VARKEY': 'VARVALUE'}
198-
assert self.git.environment() == {}
198+
self.assertEqual(new_env, {'VARKEY': 'VARVALUE'})
199+
self.assertEqual(self.git.environment(), {})
199200

200201
path = os.path.join(rw_dir, 'failing-script.sh')
201202
stream = open(path, 'wt')
@@ -214,11 +215,11 @@ def test_environment(self, rw_dir):
214215
try:
215216
remote.fetch()
216217
except GitCommandError as err:
217-
if sys.version_info[0] < 3 and is_darwin():
218-
assert 'ssh-origin' in str(err)
219-
assert err.status == 128
218+
if sys.version_info[0] < 3 and is_darwin:
219+
self.assertIn('ssh-orig, ' in str(err))
220+
self.assertEqual(err.status, 128)
220221
else:
221-
assert 'FOO' in str(err)
222+
self.assertIn('FOO', str(err))
222223
# end
223224
# end
224225
# end if select.poll exists

git/test/test_index.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,7 @@ def mixed_iterator():
577577
assert len(entries) == 1 and entries[0].hexsha != null_hex_sha
578578

579579
# add symlink
580-
if not is_win():
580+
if not is_win:
581581
for target in ('/etc/nonexisting', '/etc/passwd', '/etc'):
582582
basename = "my_real_symlink"
583583

@@ -630,7 +630,7 @@ def mixed_iterator():
630630
index.checkout(fake_symlink_path)
631631

632632
# on windows we will never get symlinks
633-
if is_win():
633+
if is_win:
634634
# simlinks should contain the link as text ( which is what a
635635
# symlink actually is )
636636
open(fake_symlink_path, 'rb').read() == link_target
@@ -711,7 +711,7 @@ def make_paths():
711711
assert fkey not in index.entries
712712

713713
index.add(files, write=True)
714-
if is_win():
714+
if is_win:
715715
hp = hook_path('pre-commit', index.repo.git_dir)
716716
hpd = os.path.dirname(hp)
717717
if not os.path.isdir(hpd):

git/test/test_submodule.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
# Change the configuration if possible to prevent the underlying memory manager
2727
# to keep file handles open. On windows we get problems as they are not properly
2828
# closed due to mmap bugs on windows (as it appears)
29-
if is_win():
29+
if is_win:
3030
try:
3131
import smmap.util
3232
smmap.util.MapRegion._test_read_into_memory = True

git/test/test_util.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def test_blocking_lock_file(self):
9292
elapsed = time.time() - start
9393
# More extra time costs, but...
9494
extra_time = 0.2
95-
if is_win():
95+
if is_win:
9696
extra_time *= 4
9797
self.assertLess(elapsed, wait_time + 0.02)
9898

git/util.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def join_path(a, *p):
106106
return path
107107

108108

109-
if is_win():
109+
if is_win:
110110
def to_native_path_windows(path):
111111
return path.replace('/', '\\')
112112

@@ -587,7 +587,7 @@ def _release_lock(self):
587587
try:
588588
# on bloody windows, the file needs write permissions to be removable.
589589
# Why ...
590-
if is_win():
590+
if is_win:
591591
os.chmod(lfp, 0o777)
592592
# END handle win32
593593
os.remove(lfp)

0 commit comments

Comments
 (0)