summaryrefslogtreecommitdiff
path: root/git/test
diff options
context:
space:
mode:
Diffstat (limited to 'git/test')
-rw-r--r--git/test/fixtures/git_config_global1
-rw-r--r--git/test/lib/asserts.py18
-rw-r--r--git/test/lib/helper.py26
-rw-r--r--git/test/performance/test_commit.py10
-rw-r--r--git/test/performance/test_streams.py2
-rw-r--r--git/test/test_base.py22
-rw-r--r--git/test/test_commit.py69
-rw-r--r--git/test/test_config.py17
-rw-r--r--git/test/test_fun.py16
-rw-r--r--git/test/test_git.py25
-rw-r--r--git/test/test_index.py47
-rw-r--r--git/test/test_reflog.py5
-rw-r--r--git/test/test_refs.py6
-rw-r--r--git/test/test_remote.py5
-rw-r--r--git/test/test_repo.py41
-rw-r--r--git/test/test_stats.py3
-rw-r--r--git/test/test_submodule.py43
-rw-r--r--git/test/test_tree.py7
-rw-r--r--git/test/test_util.py3
19 files changed, 221 insertions, 145 deletions
diff --git a/git/test/fixtures/git_config_global b/git/test/fixtures/git_config_global
index 1a55397f..56fbd3b3 100644
--- a/git/test/fixtures/git_config_global
+++ b/git/test/fixtures/git_config_global
@@ -1,3 +1,4 @@
+# just a comment
[alias]
st = status
ci = commit
diff --git a/git/test/lib/asserts.py b/git/test/lib/asserts.py
index 0f2fd99a..60a888b3 100644
--- a/git/test/lib/asserts.py
+++ b/git/test/lib/asserts.py
@@ -7,13 +7,6 @@
import re
import stat
-__all__ = ['assert_instance_of', 'assert_not_instance_of',
- 'assert_none', 'assert_not_none',
- 'assert_match', 'assert_not_match', 'assert_mode_644',
- 'assert_mode_755',
- 'assert_equal', 'assert_not_equal', 'assert_raises', 'patch', 'raises',
- 'assert_true', 'assert_false']
-
from nose.tools import (
assert_equal,
assert_not_equal,
@@ -23,9 +16,14 @@ from nose.tools import (
assert_false
)
-from mock import (
- patch
-)
+from mock import patch
+
+__all__ = ['assert_instance_of', 'assert_not_instance_of',
+ 'assert_none', 'assert_not_none',
+ 'assert_match', 'assert_not_match', 'assert_mode_644',
+ 'assert_mode_755',
+ 'assert_equal', 'assert_not_equal', 'assert_raises', 'patch', 'raises',
+ 'assert_true', 'assert_false']
def assert_instance_of(expected, actual, msg=None):
diff --git a/git/test/lib/helper.py b/git/test/lib/helper.py
index 9c935ce0..bd679512 100644
--- a/git/test/lib/helper.py
+++ b/git/test/lib/helper.py
@@ -6,12 +6,14 @@
from __future__ import print_function
import os
import sys
-from git import Repo, Remote, GitCommandError, Git
from unittest import TestCase
import time
import tempfile
import shutil
-import cStringIO
+import io
+
+from git import Repo, Remote, GitCommandError, Git
+from git.compat import string_types
GIT_REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
@@ -46,8 +48,8 @@ class StringProcessAdapter(object):
Its tailored to work with the test system only"""
def __init__(self, input_string):
- self.stdout = cStringIO.StringIO(input_string)
- self.stderr = cStringIO.StringIO()
+ self.stdout = io.BytesIO(input_string)
+ self.stderr = io.BytesIO()
def wait(self):
return 0
@@ -89,7 +91,7 @@ def with_rw_repo(working_tree_ref, bare=False):
To make working with relative paths easier, the cwd will be set to the working
dir of the repository.
"""
- assert isinstance(working_tree_ref, basestring), "Decorator requires ref name for working tree checkout"
+ assert isinstance(working_tree_ref, string_types), "Decorator requires ref name for working tree checkout"
def argument_passer(func):
def repo_creator(self):
@@ -152,7 +154,7 @@ def with_rw_and_rw_remote_repo(working_tree_ref):
See working dir info in with_rw_repo
:note: We attempt to launch our own invocation of git-daemon, which will be shutdown at the end of the test.
"""
- assert isinstance(working_tree_ref, basestring), "Decorator requires ref name for working tree checkout"
+ assert isinstance(working_tree_ref, string_types), "Decorator requires ref name for working tree checkout"
def argument_passer(func):
def remote_repo_creator(self):
@@ -177,6 +179,7 @@ def with_rw_and_rw_remote_repo(working_tree_ref):
pass
crw.set(section, "receivepack", True)
# release lock
+ crw.release()
del(crw)
# initialize the remote - first do it as local remote and pull, then
@@ -191,7 +194,7 @@ def with_rw_and_rw_remote_repo(working_tree_ref):
temp_dir = os.path.dirname(_mktemp())
# On windows, this will fail ... we deal with failures anyway and default to telling the user to do it
try:
- gd = Git().daemon(temp_dir, as_process=True)
+ gd = Git().daemon(temp_dir, enable='receive-pack', as_process=True)
# yes, I know ... fortunately, this is always going to work if sleep time is just large enough
time.sleep(0.5)
except Exception:
@@ -213,7 +216,8 @@ def with_rw_and_rw_remote_repo(working_tree_ref):
msg += 'Otherwise, run: git-daemon "%s"' % temp_dir
raise AssertionError(msg)
else:
- msg = 'Please start a git-daemon to run this test, execute: git-daemon "%s"' % temp_dir
+ msg = 'Please start a git-daemon to run this test, execute: git daemon --enable=receive-pack "%s"'
+ msg %= temp_dir
raise AssertionError(msg)
# END make assertion
# END catch ls remote error
@@ -225,7 +229,8 @@ def with_rw_and_rw_remote_repo(working_tree_ref):
return func(self, rw_repo, rw_remote_repo)
finally:
# gd.proc.kill() ... no idea why that doesn't work
- os.kill(gd.proc.pid, 15)
+ if gd is not None:
+ os.kill(gd.proc.pid, 15)
os.chdir(prev_cwd)
rw_repo.git.clear_cache()
@@ -233,7 +238,8 @@ def with_rw_and_rw_remote_repo(working_tree_ref):
shutil.rmtree(repo_dir, onerror=_rmtree_onerror)
shutil.rmtree(remote_repo_dir, onerror=_rmtree_onerror)
- gd.proc.wait()
+ if gd is not None:
+ gd.proc.wait()
# END cleanup
# END bare repo creator
remote_repo_creator.__name__ = func.__name__
diff --git a/git/test/performance/test_commit.py b/git/test/performance/test_commit.py
index a890c833..7d3e87c4 100644
--- a/git/test/performance/test_commit.py
+++ b/git/test/performance/test_commit.py
@@ -4,13 +4,15 @@
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
from __future__ import print_function
+from io import BytesIO
+from time import time
+import sys
+
from .lib import TestBigRepoRW
from git import Commit
from gitdb import IStream
+from git.compat import xrange
from git.test.test_commit import assert_commit_serialization
-from cStringIO import StringIO
-from time import time
-import sys
class TestPerformance(TestBigRepoRW):
@@ -90,7 +92,7 @@ class TestPerformance(TestBigRepoRW):
hc.committer, hc.committed_date, hc.committer_tz_offset,
str(i), parents=hc.parents, encoding=hc.encoding)
- stream = StringIO()
+ stream = BytesIO()
cm._serialize(stream)
slen = stream.tell()
stream.seek(0)
diff --git a/git/test/performance/test_streams.py b/git/test/performance/test_streams.py
index ff664c10..aecb7728 100644
--- a/git/test/performance/test_streams.py
+++ b/git/test/performance/test_streams.py
@@ -80,7 +80,7 @@ class TestObjDBPerformance(TestBigRepoR):
elapsed_readchunks = time() - st
stream.seek(0)
- assert ''.join(chunks) == stream.getvalue()
+ assert b''.join(chunks) == stream.getvalue()
cs_kib = cs / 1000
print("Read %i KiB of %s data in %i KiB chunks from loose odb in %f s ( %f Read KiB / s)"
diff --git a/git/test/test_base.py b/git/test/test_base.py
index a14d4680..301384ef 100644
--- a/git/test/test_base.py
+++ b/git/test/test_base.py
@@ -1,12 +1,13 @@
+#-*-coding:utf-8-*-
# test_base.py
# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
#
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
-
-import git.objects.base as base
import os
+import tempfile
+import git.objects.base as base
from git.test.lib import (
TestBase,
assert_raises,
@@ -68,10 +69,13 @@ class TestBase(TestBase):
data = data_stream.read()
assert data
- tmpfile = os.tmpfile()
+ tmpfilename = tempfile.mktemp(suffix='test-stream')
+ tmpfile = open(tmpfilename, 'wb+')
assert item == item.stream_data(tmpfile)
tmpfile.seek(0)
assert tmpfile.read() == data
+ tmpfile.close()
+ os.remove(tmpfilename)
# END stream to file directly
# END for each object type to create
@@ -85,7 +89,7 @@ class TestBase(TestBase):
assert base.Object in get_object_type_by_name(tname).mro()
# END for each known type
- assert_raises(ValueError, get_object_type_by_name, "doesntexist")
+ assert_raises(ValueError, get_object_type_by_name, b"doesntexist")
def test_object_resolution(self):
# objects must be resolved to shas so they compare equal
@@ -106,3 +110,13 @@ class TestBase(TestBase):
assert not rw_repo.config_reader("repository").getboolean("core", "bare")
assert rw_remote_repo.config_reader("repository").getboolean("core", "bare")
assert os.path.isdir(os.path.join(rw_repo.working_tree_dir, 'lib'))
+
+ @with_rw_repo('0.1.6')
+ def test_add_unicode(self, rw_repo):
+ filename = u"שלום.txt"
+
+ file_path = os.path.join(rw_repo.working_dir, filename)
+ open(file_path, "wb").write(b'something')
+
+ rw_repo.git.add(rw_repo.working_dir)
+ rw_repo.index.commit('message')
diff --git a/git/test/test_commit.py b/git/test/test_commit.py
index bfad6fd6..1f0f8c56 100644
--- a/git/test/test_commit.py
+++ b/git/test/test_commit.py
@@ -19,9 +19,12 @@ from git import (
Actor,
)
from gitdb import IStream
-from gitdb.util import hex_to_bin
+from git.compat import (
+ string_types,
+ text_type
+)
-from cStringIO import StringIO
+from io import BytesIO
import time
import sys
import re
@@ -40,14 +43,14 @@ def assert_commit_serialization(rwrepo, commit_id, print_performance_info=False)
# assert that we deserialize commits correctly, hence we get the same
# sha on serialization
- stream = StringIO()
+ stream = BytesIO()
cm._serialize(stream)
ns += 1
streamlen = stream.tell()
stream.seek(0)
istream = rwrepo.odb.store(IStream(Commit.type, streamlen, stream))
- assert istream.hexsha == cm.hexsha
+ assert istream.hexsha == cm.hexsha.encode('ascii')
nc = Commit(rwrepo, Commit.NULL_BIN_SHA, cm.tree,
cm.author, cm.authored_date, cm.author_tz_offset,
@@ -55,7 +58,7 @@ def assert_commit_serialization(rwrepo, commit_id, print_performance_info=False)
cm.message, cm.parents, cm.encoding)
assert nc.parents == cm.parents
- stream = StringIO()
+ stream = BytesIO()
nc._serialize(stream)
ns += 1
streamlen = stream.tell()
@@ -125,11 +128,11 @@ class TestCommit(TestBase):
def test_unicode_actor(self):
# assure we can parse unicode actors correctly
- name = "Üäöß ÄußÉ".decode("utf-8")
+ name = u"Üäöß ÄußÉ"
assert len(name) == 9
special = Actor._from_string(u"%s <something@this.com>" % name)
assert special.name == name
- assert isinstance(special.name, unicode)
+ assert isinstance(special.name, text_type)
def test_traversal(self):
start = self.rorepo.commit("a4d06724202afccd2b5c54f81bcf2bf26dea7fff")
@@ -142,13 +145,13 @@ class TestCommit(TestBase):
# basic branch first, depth first
dfirst = start.traverse(branch_first=False)
bfirst = start.traverse(branch_first=True)
- assert dfirst.next() == p0
- assert dfirst.next() == p00
+ assert next(dfirst) == p0
+ assert next(dfirst) == p00
- assert bfirst.next() == p0
- assert bfirst.next() == p1
- assert bfirst.next() == p00
- assert bfirst.next() == p10
+ assert next(bfirst) == p0
+ assert next(bfirst) == p1
+ assert next(bfirst) == p00
+ assert next(bfirst) == p10
# at some point, both iterations should stop
assert list(bfirst)[-1] == first
@@ -157,19 +160,19 @@ class TestCommit(TestBase):
assert len(l[0]) == 2
# ignore self
- assert start.traverse(ignore_self=False).next() == start
+ assert next(start.traverse(ignore_self=False)) == start
# depth
assert len(list(start.traverse(ignore_self=False, depth=0))) == 1
# prune
- assert start.traverse(branch_first=1, prune=lambda i, d: i == p0).next() == p1
+ assert next(start.traverse(branch_first=1, prune=lambda i, d: i == p0)) == p1
# predicate
- assert start.traverse(branch_first=1, predicate=lambda i, d: i == p1).next() == p1
+ assert next(start.traverse(branch_first=1, predicate=lambda i, d: i == p1)) == p1
# traversal should stop when the beginning is reached
- self.failUnlessRaises(StopIteration, first.traverse().next)
+ self.failUnlessRaises(StopIteration, next, first.traverse())
# parents of the first commit should be empty ( as the only parent has a null
# sha )
@@ -206,7 +209,7 @@ class TestCommit(TestBase):
first_parent=True,
bisect_all=True)
- commits = Commit._iter_from_process_or_stream(self.rorepo, StringProcessAdapter(revs))
+ commits = Commit._iter_from_process_or_stream(self.rorepo, StringProcessAdapter(revs.encode('ascii')))
expected_ids = (
'7156cece3c49544abb6bf7a0c218eb36646fad6d',
'1f66cfbbce58b4b552b041707a12d437cc5f400a',
@@ -220,8 +223,10 @@ class TestCommit(TestBase):
assert self.rorepo.tag('refs/tags/0.1.5').commit.count() == 143
def test_list(self):
+ # This doesn't work anymore, as we will either attempt getattr with bytes, or compare 20 byte string
+ # with actual 20 byte bytes. This usage makes no sense anyway
assert isinstance(Commit.list_items(self.rorepo, '0.1.5', max_count=5)[
- hex_to_bin('5117c9c8a4d3af19a9958677e45cda9269de1541')], Commit)
+ '5117c9c8a4d3af19a9958677e45cda9269de1541'], Commit)
def test_str(self):
commit = Commit(self.rorepo, Commit.NULL_BIN_SHA)
@@ -243,14 +248,14 @@ class TestCommit(TestBase):
c = self.rorepo.commit('0.1.5')
for skip in (0, 1):
piter = c.iter_parents(skip=skip)
- first_parent = piter.next()
+ first_parent = next(piter)
assert first_parent != c
assert first_parent == c.parents[0]
# END for each
- def test_base(self):
+ def test_name_rev(self):
name_rev = self.rorepo.head.commit.name_rev
- assert isinstance(name_rev, basestring)
+ assert isinstance(name_rev, string_types)
@with_rw_repo('HEAD', bare=True)
def test_serialization(self, rwrepo):
@@ -263,16 +268,16 @@ class TestCommit(TestBase):
# create a commit with unicode in the message, and the author's name
# Verify its serialization and deserialization
cmt = self.rorepo.commit('0.1.6')
- assert isinstance(cmt.message, unicode) # it automatically decodes it as such
- assert isinstance(cmt.author.name, unicode) # same here
+ assert isinstance(cmt.message, text_type) # it automatically decodes it as such
+ assert isinstance(cmt.author.name, text_type) # same here
- cmt.message = "üäêèß".decode("utf-8")
+ cmt.message = u"üäêèß"
assert len(cmt.message) == 5
- cmt.author.name = "äüß".decode("utf-8")
+ cmt.author.name = u"äüß"
assert len(cmt.author.name) == 3
- cstream = StringIO()
+ cstream = BytesIO()
cmt._serialize(cstream)
cstream.seek(0)
assert len(cstream.getvalue())
@@ -288,7 +293,7 @@ class TestCommit(TestBase):
def test_gpgsig(self):
cmt = self.rorepo.commit()
- cmt._deserialize(open(fixture_path('commit_with_gpgsig')))
+ cmt._deserialize(open(fixture_path('commit_with_gpgsig'), 'rb'))
fixture_sig = """-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
@@ -312,9 +317,9 @@ JzJMZDRLQLFvnzqZuCjE
cmt.gpgsig = "<test\ndummy\nsig>"
assert cmt.gpgsig != fixture_sig
- cstream = StringIO()
+ cstream = BytesIO()
cmt._serialize(cstream)
- assert re.search(r"^gpgsig <test\n dummy\n sig>$", cstream.getvalue(), re.MULTILINE)
+ assert re.search(r"^gpgsig <test\n dummy\n sig>$", cstream.getvalue().decode('ascii'), re.MULTILINE)
cstream.seek(0)
cmt.gpgsig = None
@@ -322,6 +327,6 @@ JzJMZDRLQLFvnzqZuCjE
assert cmt.gpgsig == "<test\ndummy\nsig>"
cmt.gpgsig = None
- cstream = StringIO()
+ cstream = BytesIO()
cmt._serialize(cstream)
- assert not re.search(r"^gpgsig ", cstream.getvalue(), re.MULTILINE)
+ assert not re.search(r"^gpgsig ", cstream.getvalue().decode('ascii'), re.MULTILINE)
diff --git a/git/test/test_config.py b/git/test/test_config.py
index d1c8e72f..546a2fe1 100644
--- a/git/test/test_config.py
+++ b/git/test/test_config.py
@@ -11,16 +11,19 @@ from git.test.lib import (
from git import (
GitConfigParser
)
-import StringIO
+from git.compat import (
+ string_types,
+)
+import io
from copy import copy
-from ConfigParser import NoSectionError
+from git.config import cp
class TestBase(TestCase):
def _to_memcache(self, file_path):
- fp = open(file_path, "r")
- sio = StringIO.StringIO(fp.read())
+ fp = open(file_path, "rb")
+ sio = io.BytesIO(fp.read())
sio.name = file_path
return sio
@@ -38,7 +41,7 @@ class TestBase(TestCase):
w_config.write() # enforce writing
# we stripped lines when reading, so the results differ
- assert file_obj.getvalue() != file_obj_orig.getvalue()
+ assert file_obj.getvalue() and file_obj.getvalue() != file_obj_orig.getvalue()
# creating an additional config writer must fail due to exclusive access
self.failUnlessRaises(IOError, GitConfigParser, file_obj, read_only=False)
@@ -85,7 +88,7 @@ class TestBase(TestCase):
num_options += 1
val = r_config.get(section, option)
val_typed = r_config.get_value(section, option)
- assert isinstance(val_typed, (bool, long, float, basestring))
+ assert isinstance(val_typed, (bool, int, float, ) + string_types)
assert val
assert "\n" not in option
assert "\n" not in val
@@ -104,4 +107,4 @@ class TestBase(TestCase):
assert r_config.get_value("doesnt", "exist", default) == default
# it raises if there is no default though
- self.failUnlessRaises(NoSectionError, r_config.get_value, "doesnt", "exist")
+ self.failUnlessRaises(cp.NoSectionError, r_config.get_value, "doesnt", "exist")
diff --git a/git/test/test_fun.py b/git/test/test_fun.py
index bf178aaa..40d040b9 100644
--- a/git/test/test_fun.py
+++ b/git/test/test_fun.py
@@ -24,13 +24,13 @@ from stat import (
)
from git.index import IndexFile
-from cStringIO import StringIO
+from io import BytesIO
class TestFun(TestBase):
def _assert_index_entries(self, entries, trees):
- index = IndexFile.from_tree(self.rorepo, *[self.rorepo.tree(bin_to_hex(t)) for t in trees])
+ index = IndexFile.from_tree(self.rorepo, *[self.rorepo.tree(bin_to_hex(t).decode('ascii')) for t in trees])
assert entries
assert len(index.entries) == len(entries)
for entry in entries:
@@ -72,7 +72,7 @@ class TestFun(TestBase):
def mktree(self, odb, entries):
"""create a tree from the given tree entries and safe it to the database"""
- sio = StringIO()
+ sio = BytesIO()
tree_to_stream(entries, sio.write)
sio.seek(0)
istream = odb.store(IStream(str_tree_type, len(sio.getvalue()), sio))
@@ -91,9 +91,9 @@ class TestFun(TestBase):
assert has_conflict == (len([e for e in entries if e.stage != 0]) > 0)
mktree = self.mktree
- shaa = "\1" * 20
- shab = "\2" * 20
- shac = "\3" * 20
+ shaa = b"\1" * 20
+ shab = b"\2" * 20
+ shac = b"\3" * 20
odb = rwrepo.odb
@@ -256,6 +256,6 @@ class TestFun(TestBase):
assert entries
# END for each commit
- def test_tree_entries_from_data(self):
+ def test_tree_entries_from_data_with_failing_name_decode(self):
r = tree_entries_from_data(b'100644 \x9f\0aaa')
- assert r == [('aaa', 33188, '\x9f')], r
+ assert r == [(b'aaa', 33188, b'\x9f')], r
diff --git a/git/test/test_git.py b/git/test/test_git.py
index 553f8d1b..502e6091 100644
--- a/git/test/test_git.py
+++ b/git/test/test_git.py
@@ -1,3 +1,4 @@
+#-*-coding:utf-8-*-
# test_git.py
# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
#
@@ -16,6 +17,8 @@ from git.test.lib import (TestBase,
from git import (Git,
GitCommandError)
+from git.compat import PY3
+
class TestGit(TestBase):
@@ -32,12 +35,20 @@ class TestGit(TestBase):
assert_equal(git.call_args, ((['git', 'version'],), {}))
def test_call_unpack_args_unicode(self):
- args = Git._Git__unpack_args(u'Unicode' + unichr(40960))
- assert_equal(args, ['Unicode\xea\x80\x80'])
+ args = Git._Git__unpack_args(u'Unicode€™')
+ if PY3:
+ mangled_value = 'Unicode\u20ac\u2122'
+ else:
+ mangled_value = 'Unicode\xe2\x82\xac\xe2\x84\xa2'
+ assert_equal(args, [mangled_value])
def test_call_unpack_args(self):
- args = Git._Git__unpack_args(['git', 'log', '--', u'Unicode' + unichr(40960)])
- assert_equal(args, ['git', 'log', '--', 'Unicode\xea\x80\x80'])
+ args = Git._Git__unpack_args(['git', 'log', '--', u'Unicode€™'])
+ if PY3:
+ mangled_value = 'Unicode\u20ac\u2122'
+ else:
+ mangled_value = 'Unicode\xe2\x82\xac\xe2\x84\xa2'
+ assert_equal(args, ['git', 'log', '--', mangled_value])
@raises(GitCommandError)
def test_it_raises_errors(self):
@@ -75,13 +86,13 @@ class TestGit(TestBase):
import subprocess as sp
hexsha = "b2339455342180c7cc1e9bba3e9f181f7baa5167"
g = self.git.cat_file(batch_check=True, istream=sp.PIPE, as_process=True)
- g.stdin.write("b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
+ g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
g.stdin.flush()
obj_info = g.stdout.readline()
# read header + data
g = self.git.cat_file(batch=True, istream=sp.PIPE, as_process=True)
- g.stdin.write("b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
+ g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
g.stdin.flush()
obj_info_two = g.stdout.readline()
assert obj_info == obj_info_two
@@ -92,7 +103,7 @@ class TestGit(TestBase):
g.stdout.read(1)
# now we should be able to read a new object
- g.stdin.write("b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
+ g.stdin.write(b"b2339455342180c7cc1e9bba3e9f181f7baa5167\n")
g.stdin.flush()
assert g.stdout.readline() == obj_info
diff --git a/git/test/test_index.py b/git/test/test_index.py
index 15fff8d4..f7504b32 100644
--- a/git/test/test_index.py
+++ b/git/test/test_index.py
@@ -20,6 +20,7 @@ from git import (
GitCommandError,
CheckoutError,
)
+from git.compat import string_types
from gitdb.util import hex_to_bin
import os
import sys
@@ -30,7 +31,7 @@ from stat import (
ST_MODE
)
-from StringIO import StringIO
+from io import BytesIO
from gitdb.base import IStream
from git.objects import Blob
from git.index.typ import (
@@ -47,7 +48,7 @@ class TestIndex(TestBase):
def _assert_fprogress(self, entries):
assert len(entries) == len(self._fprogress_map)
- for path, call_count in self._fprogress_map.iteritems():
+ for path, call_count in self._fprogress_map.items():
assert call_count == 2
# END for each item in progress map
self._reset_progress()
@@ -85,7 +86,7 @@ class TestIndex(TestBase):
assert index.version > 0
# test entry
- entry = index.entries.itervalues().next()
+ entry = next(iter(index.entries.values()))
for attr in ("path", "ctime", "mtime", "dev", "inode", "mode", "uid",
"gid", "size", "binsha", "hexsha", "stage"):
getattr(entry, attr)
@@ -99,7 +100,7 @@ class TestIndex(TestBase):
# test stage
index_merge = IndexFile(self.rorepo, fixture_path("index_merge"))
assert len(index_merge.entries) == 106
- assert len(list(e for e in index_merge.entries.itervalues() if e.stage != 0))
+ assert len(list(e for e in index_merge.entries.values() if e.stage != 0))
# write the data - it must match the original
tmpfile = tempfile.mktemp()
@@ -166,7 +167,7 @@ class TestIndex(TestBase):
assert unmerged_blob_map
# pick the first blob at the first stage we find and use it as resolved version
- three_way_index.resolve_blobs(l[0][1] for l in unmerged_blob_map.itervalues())
+ three_way_index.resolve_blobs(l[0][1] for l in unmerged_blob_map.values())
tree = three_way_index.write_tree()
assert isinstance(tree, Tree)
num_blobs = 0
@@ -200,7 +201,7 @@ class TestIndex(TestBase):
# Add a change with a NULL sha that should conflict with next_commit. We
# pretend there was a change, but we do not even bother adding a proper
# sha for it ( which makes things faster of course )
- manifest_fake_entry = BaseIndexEntry((manifest_entry[0], "\0" * 20, 0, manifest_entry[3]))
+ manifest_fake_entry = BaseIndexEntry((manifest_entry[0], b"\0" * 20, 0, manifest_entry[3]))
# try write flag
self._assert_entries(rw_repo.index.add([manifest_fake_entry], write=False))
# add actually resolves the null-hex-sha for us as a feature, but we can
@@ -235,7 +236,7 @@ class TestIndex(TestBase):
# now make a proper three way merge with unmerged entries
unmerged_tree = IndexFile.from_tree(rw_repo, parent_commit, tree, next_commit)
unmerged_blobs = unmerged_tree.unmerged_blobs()
- assert len(unmerged_blobs) == 1 and unmerged_blobs.keys()[0] == manifest_key[0]
+ assert len(unmerged_blobs) == 1 and list(unmerged_blobs.keys())[0] == manifest_key[0]
@with_rw_repo('0.1.6')
def test_index_file_diffing(self, rw_repo):
@@ -294,7 +295,7 @@ class TestIndex(TestBase):
assert index.diff(None)
# reset the working copy as well to current head,to pull 'back' as well
- new_data = "will be reverted"
+ new_data = b"will be reverted"
file_path = os.path.join(rw_repo.working_tree_dir, "CHANGES")
fp = open(file_path, "wb")
fp.write(new_data)
@@ -311,7 +312,7 @@ class TestIndex(TestBase):
# test full checkout
test_file = os.path.join(rw_repo.working_tree_dir, "CHANGES")
- open(test_file, 'ab').write("some data")
+ open(test_file, 'ab').write(b"some data")
rval = index.checkout(None, force=True, fprogress=self._fprogress)
assert 'CHANGES' in list(rval)
self._assert_fprogress([None])
@@ -335,7 +336,7 @@ class TestIndex(TestBase):
self.failUnlessRaises(CheckoutError, index.checkout, paths=["doesnt/exist"])
# checkout file with modifications
- append_data = "hello"
+ append_data = b"hello"
fp = open(test_file, "ab")
fp.write(append_data)
fp.close()
@@ -343,15 +344,15 @@ class TestIndex(TestBase):
index.checkout(test_file)
except CheckoutError as e:
assert len(e.failed_files) == 1 and e.failed_files[0] == os.path.basename(test_file)
- assert (len(e.failed_files) == len(e.failed_reasons)) and isinstance(e.failed_reasons[0], basestring)
+ assert (len(e.failed_files) == len(e.failed_reasons)) and isinstance(e.failed_reasons[0], string_types)
assert len(e.valid_files) == 0
- assert open(test_file).read().endswith(append_data)
+ assert open(test_file, 'rb').read().endswith(append_data)
else:
raise AssertionError("Exception CheckoutError not thrown")
# if we force it it should work
index.checkout(test_file, force=True)
- assert not open(test_file).read().endswith(append_data)
+ assert not open(test_file, 'rb').read().endswith(append_data)
# checkout directory
shutil.rmtree(os.path.join(rw_repo.working_tree_dir, "lib"))
@@ -378,14 +379,16 @@ class TestIndex(TestBase):
uname = "Some Developer"
umail = "sd@company.com"
- rw_repo.config_writer().set_value("user", "name", uname)
- rw_repo.config_writer().set_value("user", "email", umail)
+ writer = rw_repo.config_writer()
+ writer.set_value("user", "name", uname)
+ writer.set_value("user", "email", umail)
+ writer.release()
# remove all of the files, provide a wild mix of paths, BaseIndexEntries,
# IndexEntries
def mixed_iterator():
count = 0
- for entry in index.entries.itervalues():
+ for entry in index.entries.values():
type_id = count % 4
if type_id == 0: # path
yield entry.path
@@ -499,7 +502,7 @@ class TestIndex(TestBase):
# mode 0 not allowed
null_hex_sha = Diff.NULL_HEX_SHA
- null_bin_sha = "\0" * 20
+ null_bin_sha = b"\0" * 20
self.failUnlessRaises(ValueError, index.reset(
new_commit).add, [BaseIndexEntry((0, null_bin_sha, 0, "doesntmatter"))])
@@ -525,7 +528,7 @@ class TestIndex(TestBase):
assert S_ISLNK(index.entries[index.entry_key("my_real_symlink", 0)].mode)
# we expect only the target to be written
- assert index.repo.odb.stream(entries[0].binsha).read() == target
+ assert index.repo.odb.stream(entries[0].binsha).read().decode('ascii') == target
# END real symlink test
# add fake symlink and assure it checks-our as symlink
@@ -617,7 +620,7 @@ class TestIndex(TestBase):
for fid in range(3):
fname = 'newfile%i' % fid
- open(fname, 'wb').write("abcd")
+ open(fname, 'wb').write(b"abcd")
yield Blob(rw_repo, Blob.NULL_BIN_SHA, 0o100644, fname)
# END for each new file
# END path producer
@@ -697,9 +700,9 @@ class TestIndex(TestBase):
# instead of throwing the Exception we are expecting. This is
# a quick hack to make this test fail when expected.
rw_bare_repo._working_tree_dir = None
- contents = 'This is a StringIO file'
+ contents = b'This is a BytesIO file'
filesize = len(contents)
- fileobj = StringIO(contents)
+ fileobj = BytesIO(contents)
filename = 'my-imaginary-file'
istream = rw_bare_repo.odb.store(
IStream(Blob.type, filesize, fileobj))
@@ -715,5 +718,5 @@ class TestIndex(TestBase):
try:
rw_bare_repo.index.add([path])
except Exception as e:
- asserted = "does not have a working tree" in e.message
+ asserted = "does not have a working tree" in str(e)
assert asserted, "Adding using a filename is not correctly asserted."
diff --git a/git/test/test_reflog.py b/git/test/test_reflog.py
index 4efb8025..3571e083 100644
--- a/git/test/test_reflog.py
+++ b/git/test/test_reflog.py
@@ -8,6 +8,7 @@ from git.refs import (
RefLog
)
from git.util import Actor
+from gitdb.util import hex_to_bin
import tempfile
import shutil
@@ -51,7 +52,7 @@ class TestRefLog(TestBase):
assert len(reflog)
# iter_entries works with path and with stream
- assert len(list(RefLog.iter_entries(open(rlp_master))))
+ assert len(list(RefLog.iter_entries(open(rlp_master, 'rb'))))
assert len(list(RefLog.iter_entries(rlp_master)))
# raise on invalid revlog
@@ -65,7 +66,7 @@ class TestRefLog(TestBase):
self.failUnlessRaises(ValueError, RefLog().write)
# test serialize and deserialize - results must match exactly
- binsha = chr(255) * 20
+ binsha = hex_to_bin(('f' * 40).encode('ascii'))
msg = "my reflog message"
cr = self.rorepo.config_reader()
for rlp in (rlp_head, rlp_master):
diff --git a/git/test/test_refs.py b/git/test/test_refs.py
index af33765a..14b91cfe 100644
--- a/git/test/test_refs.py
+++ b/git/test/test_refs.py
@@ -105,9 +105,11 @@ class TestRefs(TestBase):
tv = "testopt"
writer.set_value(tv, 1)
assert writer.get_value(tv) == 1
- del(writer)
+ writer.release()
assert head.config_reader().get_value(tv) == 1
- head.config_writer().remove_option(tv)
+ writer = head.config_writer()
+ writer.remove_option(tv)
+ writer.release()
# after the clone, we might still have a tracking branch setup
head.set_tracking_branch(None)
diff --git a/git/test/test_remote.py b/git/test/test_remote.py
index a8d5179a..75dc19c5 100644
--- a/git/test/test_remote.py
+++ b/git/test/test_remote.py
@@ -23,6 +23,7 @@ from git import (
GitCommandError
)
from git.util import IterableList
+from git.compat import string_types
import tempfile
import shutil
import os
@@ -97,7 +98,7 @@ class TestRemote(TestBase):
# self._print_fetchhead(remote.repo)
assert len(results) > 0 and isinstance(results[0], FetchInfo)
for info in results:
- assert isinstance(info.note, basestring)
+ assert isinstance(info.note, string_types)
if isinstance(info.ref, Reference):
assert info.flags != 0
# END reference type flags handling
@@ -113,7 +114,7 @@ class TestRemote(TestBase):
assert len(results) > 0 and isinstance(results[0], PushInfo)
for info in results:
assert info.flags
- assert isinstance(info.summary, basestring)
+ assert isinstance(info.summary, string_types)
if info.old_commit is not None:
assert isinstance(info.old_commit, Commit)
if info.flags & info.ERROR:
diff --git a/git/test/test_repo.py b/git/test/test_repo.py
index f6b46a6e..f216039e 100644
--- a/git/test/test_repo.py
+++ b/git/test/test_repo.py
@@ -30,12 +30,16 @@ from git import (
from git.util import join_path_native
from git.exc import BadObject
from gitdb.util import bin_to_hex
+from git.compat import (
+ string_types,
+ defenc
+)
import os
import sys
import tempfile
import shutil
-from cStringIO import StringIO
+from io import BytesIO
class TestRepo(TestBase):
@@ -258,13 +262,16 @@ class TestRepo(TestBase):
assert self.rorepo.tag('refs/tags/0.1.5').commit
def test_archive(self):
- tmpfile = os.tmpfile()
- self.rorepo.archive(tmpfile, '0.1.5')
- assert tmpfile.tell()
+ tmpfile = tempfile.mktemp(suffix='archive-test')
+ stream = open(tmpfile, 'wb')
+ self.rorepo.archive(stream, '0.1.5')
+ assert stream.tell()
+ stream.close()
+ os.remove(tmpfile)
@patch.object(Git, '_call_process')
def test_should_display_blame_information(self, git):
- git.return_value = fixture('blame')
+ git.return_value = fixture('blame').decode(defenc)
b = self.rorepo.blame('master', 'lib/git.py')
assert_equal(13, len(b))
assert_equal(2, len(b[0]))
@@ -286,7 +293,7 @@ class TestRepo(TestBase):
# test the 'lines per commit' entries
tlist = b[0][1]
assert_true(tlist)
- assert_true(isinstance(tlist[0], basestring))
+ assert_true(isinstance(tlist[0], string_types))
assert_true(len(tlist) < sum(len(t) for t in tlist)) # test for single-char bug
def test_blame_real(self):
@@ -335,6 +342,7 @@ class TestRepo(TestBase):
try:
writer = self.rorepo.config_writer(config_level)
assert not writer.read_only
+ writer.release()
except IOError:
# its okay not to get a writer for some configuration files if we
# have no permissions
@@ -349,7 +357,8 @@ class TestRepo(TestBase):
tag = self.rorepo.create_tag("new_tag", "HEAD~2")
self.rorepo.delete_tag(tag)
- self.rorepo.config_writer()
+ writer = self.rorepo.config_writer()
+ writer.release()
remote = self.rorepo.create_remote("new_remote", "git@server:repo.git")
self.rorepo.delete_remote(remote)
@@ -361,27 +370,27 @@ class TestRepo(TestBase):
def test_git_cmd(self):
# test CatFileContentStream, just to be very sure we have no fencepost errors
# last \n is the terminating newline that it expects
- l1 = "0123456789\n"
- l2 = "abcdefghijklmnopqrstxy\n"
- l3 = "z\n"
- d = "%s%s%s\n" % (l1, l2, l3)
+ l1 = b"0123456789\n"
+ l2 = b"abcdefghijklmnopqrstxy\n"
+ l3 = b"z\n"
+ d = l1 + l2 + l3 + b"\n"
l1p = l1[:5]
# full size
# size is without terminating newline
def mkfull():
- return Git.CatFileContentStream(len(d) - 1, StringIO(d))
+ return Git.CatFileContentStream(len(d) - 1, BytesIO(d))
ts = 5
def mktiny():
- return Git.CatFileContentStream(ts, StringIO(d))
+ return Git.CatFileContentStream(ts, BytesIO(d))
# readlines no limit
s = mkfull()
lines = s.readlines()
- assert len(lines) == 3 and lines[-1].endswith('\n')
+ assert len(lines) == 3 and lines[-1].endswith(b'\n')
assert s._stream.tell() == len(d) # must have scrubbed to the end
# realines line limit
@@ -565,7 +574,7 @@ class TestRepo(TestBase):
# try partial parsing
max_items = 40
for i, binsha in enumerate(self.rorepo.odb.sha_iter()):
- assert rev_parse(bin_to_hex(binsha)[:8 - (i % 2)]).binsha == binsha
+ assert rev_parse(bin_to_hex(binsha)[:8 - (i % 2)].decode('ascii')).binsha == binsha
if i > max_items:
# this is rather slow currently, as rev_parse returns an object
# which requires accessing packs, it has some additional overhead
@@ -644,6 +653,6 @@ class TestRepo(TestBase):
assert os.path.abspath(git_file_repo.git_dir) == real_path_abs
# Test using an absolute gitdir path in the .git file.
- open(git_file_path, 'wb').write('gitdir: %s\n' % real_path_abs)
+ open(git_file_path, 'wb').write(('gitdir: %s\n' % real_path_abs).encode('ascii'))
git_file_repo = Repo(rwrepo.working_tree_dir)
assert os.path.abspath(git_file_repo.git_dir) == real_path_abs
diff --git a/git/test/test_stats.py b/git/test/test_stats.py
index c4535b75..884ab1ab 100644
--- a/git/test/test_stats.py
+++ b/git/test/test_stats.py
@@ -10,12 +10,13 @@ from git.test.lib import (
assert_equal
)
from git import Stats
+from git.compat import defenc
class TestStats(TestBase):
def test_list_from_string(self):
- output = fixture('diff_numstat')
+ output = fixture('diff_numstat').decode(defenc)
stats = Stats._list_from_string(self.rorepo, output)
assert_equal(2, stats.total['files'])
diff --git a/git/test/test_submodule.py b/git/test/test_submodule.py
index ec3459e4..99996ce3 100644
--- a/git/test/test_submodule.py
+++ b/git/test/test_submodule.py
@@ -9,6 +9,7 @@ from git.exc import InvalidGitRepositoryError
from git.objects.submodule.base import Submodule
from git.objects.submodule.root import RootModule, RootUpdateProgress
from git.util import to_native_path_linux, join_path_native
+from git.compat import string_types
import shutil
import git
import sys
@@ -76,10 +77,10 @@ class TestSubmodule(TestBase):
self.failUnlessRaises(InvalidGitRepositoryError, getattr, sm, 'branch')
# branch_path works, as its just a string
- assert isinstance(sm.branch_path, basestring)
+ assert isinstance(sm.branch_path, string_types)
# some commits earlier we still have a submodule, but its at a different commit
- smold = Submodule.iter_items(rwrepo, self.k_subm_changed).next()
+ smold = next(Submodule.iter_items(rwrepo, self.k_subm_changed))
assert smold.binsha != sm.binsha
assert smold != sm # the name changed
@@ -98,7 +99,7 @@ class TestSubmodule(TestBase):
# for faster checkout, set the url to the local path
new_smclone_path = to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path))
writer.set_value('url', new_smclone_path)
- del(writer)
+ writer.release()
assert sm.config_reader().get_value('url') == new_smclone_path
assert sm.url == new_smclone_path
# END handle bare repo
@@ -195,7 +196,9 @@ class TestSubmodule(TestBase):
# adjust the path of the submodules module to point to the local destination
new_csmclone_path = to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path, csm.path))
- csm.config_writer().set_value('url', new_csmclone_path)
+ writer = csm.config_writer()
+ writer.set_value('url', new_csmclone_path)
+ writer.release()
assert csm.url == new_csmclone_path
# dry-run does nothing
@@ -256,8 +259,12 @@ class TestSubmodule(TestBase):
# NOTE: As we did a few updates in the meanwhile, the indices were reset
# Hence we create some changes
csm.set_parent_commit(csm.repo.head.commit)
- sm.config_writer().set_value("somekey", "somevalue")
- csm.config_writer().set_value("okey", "ovalue")
+ writer = sm.config_writer()
+ writer.set_value("somekey", "somevalue")
+ writer.release()
+ writer = csm.config_writer()
+ writer.set_value("okey", "ovalue")
+ writer.release()
self.failUnlessRaises(InvalidGitRepositoryError, sm.remove)
# if we remove the dirty index, it would work
sm.module().index.reset()
@@ -405,7 +412,8 @@ class TestSubmodule(TestBase):
assert len(rm.list_items(rm.module())) == 1
rm.config_reader()
- rm.config_writer()
+ w = rm.config_writer()
+ w.release()
# deep traversal gitdb / async
rsmsp = [sm.path for sm in rm.traverse()]
@@ -430,8 +438,9 @@ class TestSubmodule(TestBase):
assert not sm.module_exists() # was never updated after rwrepo's clone
# assure we clone from a local source
- sm.config_writer().set_value(
- 'url', to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path)))
+ writer = sm.config_writer()
+ writer.set_value('url', to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path)))
+ writer.release()
# dry-run does nothing
sm.update(recursive=False, dry_run=True, progress=prog)
@@ -439,7 +448,9 @@ class TestSubmodule(TestBase):
sm.update(recursive=False)
assert sm.module_exists()
- sm.config_writer().set_value('path', fp) # change path to something with prefix AFTER url change
+ writer = sm.config_writer()
+ writer.set_value('path', fp) # change path to something with prefix AFTER url change
+ writer.release()
# update fails as list_items in such a situations cannot work, as it cannot
# find the entry at the changed path
@@ -503,7 +514,9 @@ class TestSubmodule(TestBase):
# repository at the different url
nsm.set_parent_commit(csmremoved)
nsmurl = to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, rsmsp[0]))
- nsm.config_writer().set_value('url', nsmurl)
+ writer = nsm.config_writer()
+ writer.set_value('url', nsmurl)
+ writer.release()
csmpathchange = rwrepo.index.commit("changed url")
nsm.set_parent_commit(csmpathchange)
@@ -531,7 +544,9 @@ class TestSubmodule(TestBase):
nsmm = nsm.module()
prev_commit = nsmm.head.commit
for branch in ("some_virtual_branch", cur_branch.name):
- nsm.config_writer().set_value(Submodule.k_head_option, git.Head.to_full_path(branch))
+ writer = nsm.config_writer()
+ writer.set_value(Submodule.k_head_option, git.Head.to_full_path(branch))
+ writer.release()
csmbranchchange = rwrepo.index.commit("changed branch to %s" % branch)
nsm.set_parent_commit(csmbranchchange)
# END for each branch to change
@@ -559,7 +574,9 @@ class TestSubmodule(TestBase):
assert nsm.exists() and nsm.module_exists() and len(nsm.children()) >= 1
# assure we pull locally only
nsmc = nsm.children()[0]
- nsmc.config_writer().set_value('url', async_url)
+ writer = nsmc.config_writer()
+ writer.set_value('url', async_url)
+ writer.release()
rm.update(recursive=True, progress=prog, dry_run=True) # just to run the code
rm.update(recursive=True, progress=prog)
diff --git a/git/test/test_tree.py b/git/test/test_tree.py
index d2e3606b..7a16b777 100644
--- a/git/test/test_tree.py
+++ b/git/test/test_tree.py
@@ -11,7 +11,7 @@ from git import (
Blob
)
-from cStringIO import StringIO
+from io import BytesIO
class TestTree(TestBase):
@@ -30,7 +30,7 @@ class TestTree(TestBase):
orig_data = tree.data_stream.read()
orig_cache = tree._cache
- stream = StringIO()
+ stream = BytesIO()
tree._serialize(stream)
assert stream.getvalue() == orig_data
@@ -82,7 +82,7 @@ class TestTree(TestBase):
mod.set_done() # multiple times are okay
# serialize, its different now
- stream = StringIO()
+ stream = BytesIO()
testtree._serialize(stream)
stream.seek(0)
assert stream.getvalue() != orig_data
@@ -138,6 +138,7 @@ class TestTree(TestBase):
# END check for slash
# slashes in paths are supported as well
+ # NOTE: on py3, / doesn't work with strings anymore ...
assert root[item.path] == item == root / item.path
# END for each item
assert found_slash
diff --git a/git/test/test_util.py b/git/test/test_util.py
index 888eb4ee..c6ca6920 100644
--- a/git/test/test_util.py
+++ b/git/test/test_util.py
@@ -24,6 +24,7 @@ from git.objects.util import (
parse_date,
)
from git.cmd import dashify
+from git.compat import string_types
import time
@@ -104,7 +105,7 @@ class TestUtils(TestBase):
# now that we are here, test our conversion functions as well
utctz = altz_to_utctz_str(offset)
- assert isinstance(utctz, basestring)
+ assert isinstance(utctz, string_types)
assert utctz_to_altz(verify_utctz(utctz)) == offset
# END assert rval utility