From e61439b3018b0b9a8eb43e59d0d7cf32041e2fed Mon Sep 17 00:00:00 2001 From: Kostis Anagnostopoulos Date: Tue, 27 Sep 2016 16:05:58 +0200 Subject: [PATCH] src: constify is_() calls + TCs: unittest-asserts for git-tests. --- git/cmd.py | 10 +++++----- git/compat.py | 14 +++----------- git/index/base.py | 2 +- git/index/fun.py | 2 +- git/remote.py | 2 +- git/repo/base.py | 4 ++-- git/test/lib/helper.py | 8 ++++---- git/test/test_base.py | 4 ++-- git/test/test_git.py | 37 +++++++++++++++++++------------------ git/test/test_index.py | 6 +++--- git/test/test_submodule.py | 2 +- git/test/test_util.py | 2 +- git/util.py | 4 ++-- 13 files changed, 45 insertions(+), 52 deletions(-) diff --git a/git/cmd.py b/git/cmd.py index 4a2163d55..698443668 100644 --- a/git/cmd.py +++ b/git/cmd.py @@ -55,7 +55,7 @@ __all__ = ('Git',) -if is_win(): +if is_win: WindowsError = OSError if PY3: @@ -239,7 +239,7 @@ def dict_to_slots_and__excluded_are_none(self, d, excluded=()): ## CREATE_NEW_PROCESS_GROUP is needed to allow killing it afterwards, # seehttps://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal PROC_CREATIONFLAGS = (CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP - if is_win() + if is_win else 0) @@ -630,7 +630,7 @@ def execute(self, command, env["LC_ALL"] = "C" env.update(self._environment) - if is_win(): + if is_win: cmd_not_found_exception = WindowsError if kill_after_timeout: raise GitCommandError('"kill_after_timeout" feature is not supported on Windows.') @@ -650,13 +650,13 @@ def execute(self, command, stderr=PIPE, stdout=PIPE if with_stdout else open(os.devnull, 'wb'), shell=self.USE_SHELL, - close_fds=(is_posix()), # unsupported on windows + close_fds=(is_posix), # unsupported on windows universal_newlines=universal_newlines, creationflags=PROC_CREATIONFLAGS, **subprocess_kwargs ) except cmd_not_found_exception as err: - raise GitCommandNotFound(str(err)) + raise GitCommandNotFound('%s: %s' % (command[0], err)) if as_process: return self.AutoInterrupt(proc, command) diff --git a/git/compat.py b/git/compat.py index 8c5036c61..dced3a5f2 100644 --- a/git/compat.py +++ b/git/compat.py @@ -24,6 +24,9 @@ ) PY3 = sys.version_info[0] >= 3 +is_win = (os.name == 'nt') +is_posix = (os.name == 'posix') +is_darwin = (os.name == 'darwin') defenc = sys.getdefaultencoding() if PY3: @@ -78,17 +81,6 @@ def __new__(cls, name, nbases, d): return meta(name, bases, d) return metaclass(meta.__name__ + 'Helper', None, {}) -def is_win(): - return os.name == 'nt' - - -def is_posix(): - return os.name == 'posix' - - -def is_darwin(): - return os.name == 'darwin' - ## From https://docs.python.org/3.3/howto/pyporting.html class UnicodeMixin(object): diff --git a/git/index/base.py b/git/index/base.py index 82df361fb..6656d9403 100644 --- a/git/index/base.py +++ b/git/index/base.py @@ -137,7 +137,7 @@ def _set_cache_(self, attr): # which happens during read-tree. # In this case, we will just read the memory in directly. # Its insanely bad ... I am disappointed ! - allow_mmap = (is_win() or sys.version_info[1] > 5) + allow_mmap = (is_win or sys.version_info[1] > 5) stream = file_contents_ro(fd, stream=True, allow_mmap=allow_mmap) try: diff --git a/git/index/fun.py b/git/index/fun.py index 64312300a..1e931b7c7 100644 --- a/git/index/fun.py +++ b/git/index/fun.py @@ -76,7 +76,7 @@ def run_commit_hook(name, index): stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=index.repo.working_dir, - close_fds=(is_posix()), + close_fds=(is_posix), creationflags=PROC_CREATIONFLAGS,) stdout, stderr = cmd.communicate() cmd.stdout.close() diff --git a/git/remote.py b/git/remote.py index 19deefb7f..7a7b4840a 100644 --- a/git/remote.py +++ b/git/remote.py @@ -376,7 +376,7 @@ def __init__(self, repo, name): self.repo = repo self.name = name - if is_win(): + if is_win: # some oddity: on windows, python 2.5, it for some reason does not realize # that it has the config_writer property, but instead calls __getattr__ # which will not yield the expected results. 'pinging' the members diff --git a/git/repo/base.py b/git/repo/base.py index d0f131bd6..2a56eaeda 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -370,7 +370,7 @@ def delete_remote(self, remote): def _get_config_path(self, config_level): # we do not support an absolute path of the gitconfig on windows , # use the global config instead - if is_win() and config_level == "system": + if is_win and config_level == "system": config_level = "global" if config_level == "system": @@ -884,7 +884,7 @@ def _clone(cls, git, url, path, odb_default_type, progress, **kwargs): prev_cwd = None prev_path = None odbt = kwargs.pop('odbt', odb_default_type) - if is_win(): + if is_win: if '~' in path: raise OSError("Git cannot handle the ~ character in path %r correctly" % path) diff --git a/git/test/lib/helper.py b/git/test/lib/helper.py index 0a845a3f6..7f4e81e02 100644 --- a/git/test/lib/helper.py +++ b/git/test/lib/helper.py @@ -74,7 +74,7 @@ def _mktemp(*args): prefixing /private/ will lead to incorrect paths on OSX.""" tdir = tempfile.mktemp(*args) # See :note: above to learn why this is comented out. - # if is_darwin(): + # if is_darwin: # tdir = '/private' + tdir return tdir @@ -84,7 +84,7 @@ def _rmtree_onerror(osremove, fullpath, exec_info): Handle the case on windows that read-only files cannot be deleted by os.remove by setting it to mode 777, then retry deletion. """ - if is_win() or osremove is not os.remove: + if is_win or osremove is not os.remove: raise os.chmod(fullpath, 0o777) @@ -141,7 +141,7 @@ def repo_creator(self): def launch_git_daemon(temp_dir, ip, port): - if is_win(): + if is_win: ## On MINGW-git, daemon exists in .\Git\mingw64\libexec\git-core\, # but if invoked as 'git daemon', it detaches from parent `git` cmd, # and then CANNOT DIE! @@ -242,7 +242,7 @@ def remote_repo_creator(self): gd.proc.terminate() log.warning('git(%s) ls-remote failed due to:%s', rw_repo.git_dir, e) - if is_win(): + if is_win: msg = textwrap.dedent(""" MINGW yet has problems with paths, and `git-daemon.exe` must be in PATH (look into .\Git\mingw64\libexec\git-core\); diff --git a/git/test/test_base.py b/git/test/test_base.py index cf92997f4..fa0bebcaa 100644 --- a/git/test/test_base.py +++ b/git/test/test_base.py @@ -118,7 +118,7 @@ def test_with_rw_remote_and_rw_repo(self, rw_repo, rw_remote_repo): assert rw_remote_repo.config_reader("repository").getboolean("core", "bare") assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib')) - @skipIf(sys.version_info < (3,) and is_win(), + @skipIf(sys.version_info < (3,) and is_win, "Unicode woes, see https://github.com/gitpython-developers/GitPython/pull/519") @with_rw_repo('0.1.6') def test_add_unicode(self, rw_repo): @@ -135,7 +135,7 @@ def test_add_unicode(self, rw_repo): open(file_path, "wb").write(b'something') - if is_win(): + if is_win: # on windows, there is no way this works, see images on # https://github.com/gitpython-developers/GitPython/issues/147#issuecomment-68881897 # Therefore, it must be added using the python implementation diff --git a/git/test/test_git.py b/git/test/test_git.py index a6213c585..36bbbb10f 100644 --- a/git/test/test_git.py +++ b/git/test/test_git.py @@ -85,7 +85,7 @@ def test_it_transforms_kwargs_into_git_command_arguments(self): # order is undefined res = self.git.transform_kwargs(**{'s': True, 't': True}) - assert ['-s', '-t'] == res or ['-t', '-s'] == res + self.assertEqual(set(['-s', '-t']), set(res)) def test_it_executes_git_to_shell_and_returns_result(self): assert_match('^git version [\d\.]{2}.*$', self.git.execute(["git", "version"])) @@ -117,7 +117,7 @@ def test_persistent_cat_file_command(self): g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n") g.stdin.flush() obj_info_two = g.stdout.readline() - assert obj_info == obj_info_two + self.assertEqual(obj_info, obj_info_two) # read data - have to read it in one large chunk size = int(obj_info.split()[2]) @@ -127,18 +127,19 @@ def test_persistent_cat_file_command(self): # now we should be able to read a new object g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n") g.stdin.flush() - assert g.stdout.readline() == obj_info + self.assertEqual(g.stdout.readline(), obj_info) # same can be achived using the respective command functions hexsha, typename, size = self.git.get_object_header(hexsha) hexsha, typename_two, size_two, data = self.git.get_object_data(hexsha) - assert typename == typename_two and size == size_two + self.assertEqual(typename, typename_two) + self.assertEqual(size, size_two) def test_version(self): v = self.git.version_info - assert isinstance(v, tuple) + self.assertIsInstance(v, tuple) for n in v: - assert isinstance(n, int) + self.assertIsInstance(n, int) # END verify number types def test_cmd_override(self): @@ -174,28 +175,28 @@ def test_insert_after_kwarg_raises(self): def test_env_vars_passed_to_git(self): editor = 'non_existant_editor' with mock.patch.dict('os.environ', {'GIT_EDITOR': editor}): - assert self.git.var("GIT_EDITOR") == editor + self.assertEqual(self.git.var("GIT_EDITOR"), editor) @with_rw_directory def test_environment(self, rw_dir): # sanity check - assert self.git.environment() == {} + self.assertEqual(self.git.environment(), {}) # make sure the context manager works and cleans up after itself with self.git.custom_environment(PWD='/tmp'): - assert self.git.environment() == {'PWD': '/tmp'} + self.assertEqual(self.git.environment(), {'PWD': '/tmp'}) - assert self.git.environment() == {} + self.assertEqual(self.git.environment(), {}) old_env = self.git.update_environment(VARKEY='VARVALUE') # The returned dict can be used to revert the change, hence why it has # an entry with value 'None'. - assert old_env == {'VARKEY': None} - assert self.git.environment() == {'VARKEY': 'VARVALUE'} + self.assertEqual(old_env, {'VARKEY': None}) + self.assertEqual(self.git.environment(), {'VARKEY': 'VARVALUE'}) new_env = self.git.update_environment(**old_env) - assert new_env == {'VARKEY': 'VARVALUE'} - assert self.git.environment() == {} + self.assertEqual(new_env, {'VARKEY': 'VARVALUE'}) + self.assertEqual(self.git.environment(), {}) path = os.path.join(rw_dir, 'failing-script.sh') stream = open(path, 'wt') @@ -214,11 +215,11 @@ def test_environment(self, rw_dir): try: remote.fetch() except GitCommandError as err: - if sys.version_info[0] < 3 and is_darwin(): - assert 'ssh-origin' in str(err) - assert err.status == 128 + if sys.version_info[0] < 3 and is_darwin: + self.assertIn('ssh-orig, ' in str(err)) + self.assertEqual(err.status, 128) else: - assert 'FOO' in str(err) + self.assertIn('FOO', str(err)) # end # end # end if select.poll exists diff --git a/git/test/test_index.py b/git/test/test_index.py index b83201c92..2a8df7981 100644 --- a/git/test/test_index.py +++ b/git/test/test_index.py @@ -577,7 +577,7 @@ def mixed_iterator(): assert len(entries) == 1 and entries[0].hexsha != null_hex_sha # add symlink - if not is_win(): + if not is_win: for target in ('/etc/nonexisting', '/etc/passwd', '/etc'): basename = "my_real_symlink" @@ -630,7 +630,7 @@ def mixed_iterator(): index.checkout(fake_symlink_path) # on windows we will never get symlinks - if is_win(): + if is_win: # simlinks should contain the link as text ( which is what a # symlink actually is ) open(fake_symlink_path, 'rb').read() == link_target @@ -711,7 +711,7 @@ def make_paths(): assert fkey not in index.entries index.add(files, write=True) - if is_win(): + if is_win: hp = hook_path('pre-commit', index.repo.git_dir) hpd = os.path.dirname(hp) if not os.path.isdir(hpd): diff --git a/git/test/test_submodule.py b/git/test/test_submodule.py index 5906b06c4..9307bab24 100644 --- a/git/test/test_submodule.py +++ b/git/test/test_submodule.py @@ -26,7 +26,7 @@ # Change the configuration if possible to prevent the underlying memory manager # to keep file handles open. On windows we get problems as they are not properly # closed due to mmap bugs on windows (as it appears) -if is_win(): +if is_win: try: import smmap.util smmap.util.MapRegion._test_read_into_memory = True diff --git a/git/test/test_util.py b/git/test/test_util.py index 76a5e0e9b..9fc159dfe 100644 --- a/git/test/test_util.py +++ b/git/test/test_util.py @@ -92,7 +92,7 @@ def test_blocking_lock_file(self): elapsed = time.time() - start # More extra time costs, but... extra_time = 0.2 - if is_win(): + if is_win: extra_time *= 4 self.assertLess(elapsed, wait_time + 0.02) diff --git a/git/util.py b/git/util.py index 31ff94fa1..f931abe2b 100644 --- a/git/util.py +++ b/git/util.py @@ -106,7 +106,7 @@ def join_path(a, *p): return path -if is_win(): +if is_win: def to_native_path_windows(path): return path.replace('/', '\\') @@ -587,7 +587,7 @@ def _release_lock(self): try: # on bloody windows, the file needs write permissions to be removable. # Why ... - if is_win(): + if is_win: os.chmod(lfp, 0o777) # END handle win32 os.remove(lfp)