diff --git a/gerrit_client.py b/gerrit_client.py index 8ea4df4d1..9bda02556 100755 --- a/gerrit_client.py +++ b/gerrit_client.py @@ -9,12 +9,20 @@ Example usage: ./gerrit_client.py [command] [args] """ +from __future__ import print_function + import json import logging import optparse import subcommand import sys -import urllib.parse + +if sys.version_info.major == 2: + import urlparse + from urllib import quote_plus +else: + from urllib.parse import quote_plus + import urllib.parse as urlparse import fix_encoding import gerrit_util @@ -41,7 +49,7 @@ def CMDmovechanges(parser, args): assert opt.destination_branch, "--destination_branch not defined" for p in opt.params: assert '=' in p, '--param is key=value, not "%s"' % p - host = urllib.parse.urlparse(opt.host).netloc + host = urlparse.urlparse(opt.host).netloc limit = 100 while True: @@ -64,9 +72,9 @@ def CMDbranchinfo(parser, args): parser.add_option('--branch', dest='branch', help='branch name') (opt, args) = parser.parse_args(args) - host = urllib.parse.urlparse(opt.host).netloc - project = urllib.parse.quote_plus(opt.project) - branch = urllib.parse.quote_plus(opt.branch) + host = urlparse.urlparse(opt.host).netloc + project = quote_plus(opt.project) + branch = quote_plus(opt.branch) result = gerrit_util.GetGerritBranch(host, project, branch) logging.info(result) write_result(result, opt) @@ -86,7 +94,7 @@ def CMDrawapi(parser, args): (opt, args) = parser.parse_args(args) assert opt.path, "--path not defined" - host = urllib.parse.urlparse(opt.host).netloc + host = urlparse.urlparse(opt.host).netloc kwargs = {} if opt.method: kwargs['reqtype'] = opt.method.upper() @@ -114,9 +122,9 @@ def CMDbranch(parser, args): assert opt.branch, "--branch not defined" assert opt.commit, "--commit not defined" - project = urllib.parse.quote_plus(opt.project) - host = urllib.parse.urlparse(opt.host).netloc - branch = urllib.parse.quote_plus(opt.branch) + project = quote_plus(opt.project) + host = urlparse.urlparse(opt.host).netloc + branch = quote_plus(opt.branch) result = gerrit_util.GetGerritBranch(host, project, branch) if result: if not opt.allow_existent_branch: @@ -153,9 +161,9 @@ def CMDtag(parser, args): assert opt.tag, "--tag not defined" assert opt.commit, "--commit not defined" - project = urllib.parse.quote_plus(opt.project) - host = urllib.parse.urlparse(opt.host).netloc - tag = urllib.parse.quote_plus(opt.tag) + project = quote_plus(opt.project) + host = urlparse.urlparse(opt.host).netloc + tag = quote_plus(opt.tag) result = gerrit_util.CreateGerritTag(host, project, tag, opt.commit) logging.info(result) write_result(result, opt) @@ -170,9 +178,9 @@ def CMDhead(parser, args): assert opt.project, "--project not defined" assert opt.branch, "--branch not defined" - project = urllib.parse.quote_plus(opt.project) - host = urllib.parse.urlparse(opt.host).netloc - branch = urllib.parse.quote_plus(opt.branch) + project = quote_plus(opt.project) + host = urlparse.urlparse(opt.host).netloc + branch = quote_plus(opt.branch) result = gerrit_util.UpdateHead(host, project, branch) logging.info(result) write_result(result, opt) @@ -185,8 +193,8 @@ def CMDheadinfo(parser, args): (opt, args) = parser.parse_args(args) assert opt.project, "--project not defined" - project = urllib.parse.quote_plus(opt.project) - host = urllib.parse.urlparse(opt.host).netloc + project = quote_plus(opt.project) + host = urlparse.urlparse(opt.host).netloc result = gerrit_util.GetHead(host, project) logging.info(result) write_result(result, opt) @@ -216,7 +224,7 @@ def CMDchanges(parser, args): assert '=' in p, '--param is key=value, not "%s"' % p result = gerrit_util.QueryChanges( - urllib.parse.urlparse(opt.host).netloc, + urlparse.urlparse(opt.host).netloc, list(tuple(p.split('=', 1)) for p in opt.params), first_param=opt.query, start=opt.start, # Default: None @@ -236,7 +244,7 @@ def CMDrelatedchanges(parser, args): (opt, args) = parser.parse_args(args) result = gerrit_util.GetRelatedChanges( - urllib.parse.urlparse(opt.host).netloc, + urlparse.urlparse(opt.host).netloc, change=opt.change, revision=opt.revision, ) @@ -274,7 +282,7 @@ def CMDcreatechange(parser, args): params.append(('notify_details', {'CC': {'accounts': opt.cc_list}})) result = gerrit_util.CreateChange( - urllib.parse.urlparse(opt.host).netloc, + urlparse.urlparse(opt.host).netloc, opt.project, branch=opt.branch, subject=opt.subject, @@ -296,7 +304,7 @@ def CMDchangeedit(parser, args): with open(opt.file) as f: data = f.read() result = gerrit_util.ChangeEdit( - urllib.parse.urlparse(opt.host).netloc, opt.change, opt.path, data) + urlparse.urlparse(opt.host).netloc, opt.change, opt.path, data) logging.info(result) write_result(result, opt) @@ -310,7 +318,7 @@ def CMDpublishchangeedit(parser, args): (opt, args) = parser.parse_args(args) result = gerrit_util.PublishChangeEdit( - urllib.parse.urlparse(opt.host).netloc, opt.change, opt.notify) + urlparse.urlparse(opt.host).netloc, opt.change, opt.notify) logging.info(result) write_result(result, opt) @@ -321,7 +329,7 @@ def CMDsubmitchange(parser, args): parser.add_option('-c', '--change', type=int, help='change number') (opt, args) = parser.parse_args(args) result = gerrit_util.SubmitChange( - urllib.parse.urlparse(opt.host).netloc, opt.change) + urlparse.urlparse(opt.host).netloc, opt.change) logging.info(result) write_result(result, opt) @@ -332,7 +340,7 @@ def CMDchangesubmittedtogether(parser, args): parser.add_option('-c', '--change', type=int, help='change number') (opt, args) = parser.parse_args(args) result = gerrit_util.GetChangesSubmittedTogether( - urllib.parse.urlparse(opt.host).netloc, opt.change) + urlparse.urlparse(opt.host).netloc, opt.change) logging.info(result) write_result(result, opt) @@ -343,7 +351,7 @@ def CMDgetcommitincludedin(parser, args): parser.add_option('--commit', dest='commit', help='commit hash') (opt, args) = parser.parse_args(args) result = gerrit_util.GetCommitIncludedIn( - urllib.parse.urlparse(opt.host).netloc, opt.project, opt.commit) + urlparse.urlparse(opt.host).netloc, opt.project, opt.commit) logging.info(result) write_result(result, opt) @@ -353,10 +361,11 @@ def CMDsetbotcommit(parser, args): """Sets bot-commit+1 to a bot generated change.""" parser.add_option('-c', '--change', type=int, help='change number') (opt, args) = parser.parse_args(args) - result = gerrit_util.SetReview(urllib.parse.urlparse(opt.host).netloc, - opt.change, - labels={'Bot-Commit': 1}, - ready=True) + result = gerrit_util.SetReview( + urlparse.urlparse(opt.host).netloc, + opt.change, + labels={'Bot-Commit': 1}, + ready=True) logging.info(result) write_result(result, opt) @@ -370,7 +379,7 @@ def CMDsetlabel(parser, args): nargs=2, metavar=('label_name', 'label_value')) (opt, args) = parser.parse_args(args) - result = gerrit_util.SetReview(urllib.parse.urlparse(opt.host).netloc, + result = gerrit_util.SetReview(urlparse.urlparse(opt.host).netloc, opt.change, labels={opt.label[0]: opt.label[1]}) logging.info(result) @@ -386,7 +395,8 @@ def CMDabandon(parser, args): (opt, args) = parser.parse_args(args) assert opt.change, "-c not defined" result = gerrit_util.AbandonChange( - urllib.parse.urlparse(opt.host).netloc, opt.change, opt.message) + urlparse.urlparse(opt.host).netloc, + opt.change, opt.message) logging.info(result) write_result(result, opt) @@ -429,7 +439,7 @@ def CMDmass_abandon(parser, args): search_query.append(('status', 'open')) logging.info("Searching for: %s" % search_query) - host = urllib.parse.urlparse(opt.host).netloc + host = urlparse.urlparse(opt.host).netloc result = gerrit_util.QueryChanges( host, diff --git a/gerrit_util.py b/gerrit_util.py index 1aeb94c51..8312bbac7 100644 --- a/gerrit_util.py +++ b/gerrit_util.py @@ -8,6 +8,9 @@ Utilities for requesting information for a Gerrit server via HTTPS. https://gerrit-review.googlesource.com/Documentation/rest-api.html """ +from __future__ import print_function +from __future__ import unicode_literals + import base64 import contextlib import httplib2 @@ -30,10 +33,15 @@ import metrics import metrics_utils import subprocess2 +from third_party import six from six.moves import urllib -import http.cookiejar -from io import StringIO +if sys.version_info.major == 2: + import cookielib + from StringIO import StringIO +else: + import http.cookiejar as cookielib + from io import StringIO LOGGER = logging.getLogger() # With a starting sleep time of 12.0 seconds, x <= [1.8-2.2]x backoff, and six @@ -247,7 +255,7 @@ class CookiesAuthenticator(Authenticator): def _get_auth_for_host(self, host): for domain, creds in self.gitcookies.items(): - if http.cookiejar.domain_match(host, domain): + if cookielib.domain_match(host, domain): return (creds[0], None, creds[1]) return self.netrc.authenticators(host) diff --git a/git_cache.py b/git_cache.py index cd67f24f8..6c4609c61 100755 --- a/git_cache.py +++ b/git_cache.py @@ -5,7 +5,10 @@ """A git command for managing a local cache of git repositories.""" +from __future__ import print_function + import contextlib +import errno import logging import optparse import os @@ -15,7 +18,11 @@ import sys import tempfile import threading import time -import urllib.parse + +try: + import urlparse +except ImportError: # For Py3 compatibility + import urllib.parse as urlparse from download_from_google_storage import Gsutil import gclient_utils @@ -135,7 +142,7 @@ class Mirror(object): b = os.getenv('OVERRIDE_BOOTSTRAP_BUCKET') if b: return b - u = urllib.parse.urlparse(self.url) + u = urlparse.urlparse(self.url) if u.netloc == 'chromium.googlesource.com': return 'chromium-git-cache' # Not recognized. @@ -157,7 +164,7 @@ class Mirror(object): url = os.path.splitdrive(url)[1] return url.replace('-', '--').replace(os.sep, '-') - parsed = urllib.parse.urlparse(url) + parsed = urlparse.urlparse(url) norm_url = parsed.netloc + parsed.path if norm_url.endswith('.git'): norm_url = norm_url[:-len('.git')] @@ -352,7 +359,7 @@ class Mirror(object): def supported_project(self): """Returns true if this repo is known to have a bootstrap zip file.""" - u = urllib.parse.urlparse(self.url) + u = urlparse.urlparse(self.url) return u.netloc in [ 'chromium.googlesource.com', 'chrome-internal.googlesource.com'] diff --git a/git_cl.py b/git_cl.py index 352bf8a72..b0f7efbb0 100755 --- a/git_cl.py +++ b/git_cl.py @@ -7,6 +7,8 @@ """A git-command for integrating reviews on Gerrit.""" +from __future__ import print_function + import base64 import collections import datetime @@ -53,9 +55,14 @@ import subprocess2 import swift_format import watchlists +from third_party import six from six.moves import urllib +if sys.version_info.major == 3: + basestring = (str,) # pylint: disable=redefined-builtin + + __version__ = '2.0' # Traces for git push will be stored in a traces directory inside the @@ -915,7 +922,7 @@ def ParseIssueNumberArgument(arg): if isinstance(arg, int): return _ParsedIssueNumberArgument(issue=arg) - if not isinstance(arg, str): + if not isinstance(arg, basestring): return fail_result if arg.isdigit(): @@ -3172,7 +3179,7 @@ class ChangeDescription(object): return '\n'.join(self._description_lines) def set_description(self, desc): - if isinstance(desc, str): + if isinstance(desc, basestring): lines = desc.splitlines() else: lines = [line.rstrip() for line in desc] diff --git a/git_common.py b/git_common.py index 8ba938dba..4add1782b 100644 --- a/git_common.py +++ b/git_common.py @@ -13,7 +13,9 @@ from multiprocessing.pool import IMapIterator def wrapper(func): def wrap(self, timeout=None): - return func(self, timeout=timeout or threading.TIMEOUT_MAX) + default_timeout = (1 << 31 if sys.version_info.major == 2 else + threading.TIMEOUT_MAX) + return func(self, timeout=timeout or default_timeout) return wrap IMapIterator.next = wrapper(IMapIterator.next) diff --git a/git_drover.py b/git_drover.py index 7fb089763..524d967b7 100755 --- a/git_drover.py +++ b/git_drover.py @@ -3,6 +3,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from __future__ import print_function + import argparse diff --git a/git_find_releases.py b/git_find_releases.py index 64de921bd..770cc01d4 100755 --- a/git_find_releases.py +++ b/git_find_releases.py @@ -11,6 +11,8 @@ Note that it uses the "cherry picked from" annotation to find merges, so it will only work on merges that followed the "use cherry-pick -x" instructions. """ +from __future__ import print_function + import optparse import re import sys diff --git a/git_footers.py b/git_footers.py index b8c1db7d8..88149c982 100755 --- a/git_footers.py +++ b/git_footers.py @@ -3,6 +3,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from __future__ import print_function + import argparse import json import re diff --git a/git_hyper_blame.py b/git_hyper_blame.py index 560a3bf34..1b63a3b20 100755 --- a/git_hyper_blame.py +++ b/git_hyper_blame.py @@ -6,6 +6,9 @@ """Wrapper around git blame that ignores certain commits. """ +from __future__ import print_function +from __future__ import unicode_literals + import argparse import collections import logging diff --git a/git_map.py b/git_map.py index e693fbece..10b321bfb 100755 --- a/git_map.py +++ b/git_map.py @@ -17,6 +17,8 @@ point to them. Items are colorized as follows: * Blue background - The currently checked out commit """ +from __future__ import unicode_literals + import os import sys @@ -27,6 +29,12 @@ import subprocess2 from third_party import colorama +if sys.version_info.major == 2: + # On Python 3, BrokenPipeError is raised instead. + # pylint:disable=redefined-builtin + BrokenPipeError = IOError + + RESET = colorama.Fore.RESET + colorama.Back.RESET + colorama.Style.RESET_ALL BRIGHT = colorama.Style.BRIGHT diff --git a/git_map_branches.py b/git_map_branches.py index 53a195a19..d06a4ceb9 100755 --- a/git_map_branches.py +++ b/git_map_branches.py @@ -24,6 +24,8 @@ Branches are colorized as follows: upstream, then you will see this. """ +from __future__ import print_function + import argparse import collections import metrics diff --git a/git_mark_merge_base.py b/git_mark_merge_base.py index 2a45bae13..35ae5eebb 100755 --- a/git_mark_merge_base.py +++ b/git_mark_merge_base.py @@ -11,6 +11,8 @@ purposes of the chromium depot_tools git extensions. Passing no arguments will just print the effective merge base for the current branch. """ +from __future__ import print_function + import argparse import sys diff --git a/git_nav_downstream.py b/git_nav_downstream.py index a378707a6..a77d9a2a7 100755 --- a/git_nav_downstream.py +++ b/git_nav_downstream.py @@ -9,6 +9,8 @@ is more than one downstream branch, then this script will prompt you to select which branch. """ +from __future__ import print_function + import argparse import sys diff --git a/git_number.py b/git_number.py index 864f3ee8c..f46b1eeb6 100755 --- a/git_number.py +++ b/git_number.py @@ -21,6 +21,9 @@ commit's entire history, this script caches all calculated data inside the git repo that it operates on in the ref 'refs/number/commits'. """ +from __future__ import print_function +from __future__ import division + import binascii import collections import logging @@ -57,7 +60,10 @@ def pathlify(hash_prefix): >>> pathlify('\xDE\xAD') 'de/ad' """ - return '/'.join('%02x' % b for b in hash_prefix) + if sys.version_info.major == 3: + return '/'.join('%02x' % b for b in hash_prefix) + + return '/'.join('%02x' % ord(b) for b in hash_prefix) @git.memoize_one(threadsafe=False) @@ -178,7 +184,10 @@ def preload_tree(prefix): def all_prefixes(depth=PREFIX_LEN): - prefixes = [bytes([i]) for i in range(255)] + if sys.version_info.major == 3: + prefixes = [bytes([i]) for i in range(255)] + else: + prefixes = [chr(i) for i in range(255)] for x in prefixes: # This isn't covered because PREFIX_LEN currently == 1 if depth > 1: # pragma: no cover diff --git a/git_rebase_update.py b/git_rebase_update.py index 9c9881ab6..c7bae67f3 100755 --- a/git_rebase_update.py +++ b/git_rebase_update.py @@ -7,6 +7,8 @@ Tool to update all branches to have the latest changes from their upstreams. """ +from __future__ import print_function + import argparse import collections import logging diff --git a/git_reparent_branch.py b/git_reparent_branch.py index e84fdd74f..9180f6035 100755 --- a/git_reparent_branch.py +++ b/git_reparent_branch.py @@ -5,6 +5,8 @@ """Change the upstream of the current branch.""" +from __future__ import print_function + import argparse import sys diff --git a/git_upstream_diff.py b/git_upstream_diff.py index 4fd9da5cc..f1e712ea8 100755 --- a/git_upstream_diff.py +++ b/git_upstream_diff.py @@ -3,6 +3,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from __future__ import print_function + import argparse import sys diff --git a/testing_support/git_test_utils.py b/testing_support/git_test_utils.py index 2a7a9c22d..1b9f655fa 100644 --- a/testing_support/git_test_utils.py +++ b/testing_support/git_test_utils.py @@ -20,6 +20,10 @@ import gclient_utils DEFAULT_BRANCH = 'main' +if sys.version_info.major == 3: + # pylint: disable=redefined-builtin + basestring = (str,) + def git_hash_data(data, typ='blob'): """Calculate the git-style SHA1 for some data. @@ -329,7 +333,7 @@ class GitRepo(object): for fname, file_data in commit_data.items(): # If it isn't a string, it's one of the special keys. - if not isinstance(fname, str): + if not isinstance(fname, basestring): continue deleted = False @@ -492,6 +496,8 @@ class GitRepoSchemaTestBase(unittest.TestCase): @classmethod def getRepoContent(cls, commit): commit = 'COMMIT_%s' % commit + if sys.version_info.major == 2: + commit = commit.encode('utf-8') return getattr(cls, commit, None) @classmethod diff --git a/tests/gerrit_client_test.py b/tests/gerrit_client_test.py index c4375929e..4ad4a2b2e 100755 --- a/tests/gerrit_client_test.py +++ b/tests/gerrit_client_test.py @@ -9,11 +9,20 @@ import logging import os import sys import unittest -from unittest import mock + +if sys.version_info.major == 2: + from StringIO import StringIO + import mock + BUILTIN_OPEN = '__builtin__.open' +else: + from io import StringIO + from unittest import mock + BUILTIN_OPEN = 'builtins.open' sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import gerrit_client +import gerrit_util class TestGerritClient(unittest.TestCase): @@ -111,7 +120,7 @@ class TestGerritClient(unittest.TestCase): subject='subject', params=[('work_in_progress', 'true')]) - @mock.patch('builtins.open', mock.mock_open()) + @mock.patch(BUILTIN_OPEN, mock.mock_open()) @mock.patch('gerrit_util.ChangeEdit', return_value='') def test_changeedit(self, util_mock): open().read.return_value = 'test_data' diff --git a/tests/gerrit_util_test.py b/tests/gerrit_util_test.py index 59d427d31..4eda84aa8 100755 --- a/tests/gerrit_util_test.py +++ b/tests/gerrit_util_test.py @@ -4,19 +4,31 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from __future__ import print_function +from __future__ import unicode_literals + + +import base64 import httplib2 -from io import StringIO import json import os import socket import sys import unittest -from unittest import mock + +if sys.version_info.major == 2: + from cStringIO import StringIO + import mock +else: + from io import StringIO + from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import gerrit_util +import gclient_utils import metrics +import metrics_utils import subprocess2 diff --git a/tests/git_cache_test.py b/tests/git_cache_test.py index 43278d66b..a85231e2a 100755 --- a/tests/git_cache_test.py +++ b/tests/git_cache_test.py @@ -5,7 +5,6 @@ """Unit tests for git_cache.py""" -from io import StringIO import logging import os import shutil @@ -13,7 +12,13 @@ import subprocess import sys import tempfile import unittest -from unittest import mock + +if sys.version_info.major == 2: + from StringIO import StringIO + import mock +else: + from io import StringIO + from unittest import mock DEPOT_TOOLS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, DEPOT_TOOLS_ROOT) diff --git a/tests/git_cl_test.py b/tests/git_cl_test.py index 0262afc40..c8304f76e 100755 --- a/tests/git_cl_test.py +++ b/tests/git_cl_test.py @@ -6,18 +6,27 @@ """Unit tests for git_cl.py.""" +from __future__ import print_function +from __future__ import unicode_literals + import datetime import json import logging -from io import StringIO import multiprocessing import optparse import os +import pprint import shutil import sys import tempfile import unittest -from unittest import mock + +if sys.version_info.major == 2: + from StringIO import StringIO + import mock +else: + from io import StringIO + from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) diff --git a/tests/git_common_test.py b/tests/git_common_test.py index 3c001b5bc..3d4d60ac8 100755 --- a/tests/git_common_test.py +++ b/tests/git_common_test.py @@ -6,6 +6,9 @@ """Unit tests for git_common.py""" +from __future__ import print_function +from __future__ import unicode_literals + import binascii import collections import datetime diff --git a/tests/git_find_releases_test.py b/tests/git_find_releases_test.py index 5db8c5d3d..d4d9490da 100755 --- a/tests/git_find_releases_test.py +++ b/tests/git_find_releases_test.py @@ -5,16 +5,25 @@ # found in the LICENSE file. """Unit tests for git_find_releases.py.""" -from io import StringIO +from __future__ import print_function +from __future__ import unicode_literals + import logging import os import sys import unittest -from unittest import mock + +if sys.version_info.major == 2: + from StringIO import StringIO + import mock +else: + from io import StringIO + from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import git_find_releases +import git_common class TestGitFindReleases(unittest.TestCase): diff --git a/tests/git_footers_test.py b/tests/git_footers_test.py index de73cadd5..a67537e37 100755 --- a/tests/git_footers_test.py +++ b/tests/git_footers_test.py @@ -2,12 +2,18 @@ """Tests for git_footers.""" -from io import StringIO import json import os import sys +import tempfile import unittest -from unittest import mock + +if sys.version_info.major == 2: + from StringIO import StringIO + import mock +else: + from io import StringIO + from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) diff --git a/tests/git_hyper_blame_test.py b/tests/git_hyper_blame_test.py index edc5038cf..419930887 100755 --- a/tests/git_hyper_blame_test.py +++ b/tests/git_hyper_blame_test.py @@ -4,13 +4,23 @@ # found in the LICENSE file. """Tests for git_dates.""" -from io import BytesIO, StringIO +from __future__ import unicode_literals + +import datetime import os import re import shutil import sys import tempfile -from unittest import mock +import unittest + +from io import BytesIO +if sys.version_info.major == 2: + from StringIO import StringIO + import mock +else: + from io import StringIO + from unittest import mock DEPOT_TOOLS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, DEPOT_TOOLS_ROOT) @@ -19,6 +29,7 @@ from testing_support import coverage_utils from testing_support import git_test_utils import gclient_utils +import git_common GitRepo = git_test_utils.GitRepo @@ -579,7 +590,11 @@ class GitHyperBlameUnicodeTest(GitHyperBlameTestBase): # Add a line. COMMIT_B = { - GitRepo.AUTHOR_NAME: '\u4e2d\u56fd\u4f5c\u8005', + # AUTHOR_NAME has .encode('utf-8') for py2 as Windows raises exception + # otherwise. Type remains str + GitRepo.AUTHOR_NAME: + ('\u4e2d\u56fd\u4f5c\u8005'.encode('utf-8') + if sys.version_info.major == 2 else '\u4e2d\u56fd\u4f5c\u8005'), 'file': { 'data': b'red\ngreen\nblue\n' }, @@ -587,12 +602,40 @@ class GitHyperBlameUnicodeTest(GitHyperBlameTestBase): # Modify a line with non-UTF-8 author and file text. COMMIT_C = { - GitRepo.AUTHOR_NAME: 'Lat\xedn-1 Author', + GitRepo.AUTHOR_NAME: + ('Lat\u00edn-1 Author'.encode('latin-1') + if sys.version_info.major == 2 else 'Lat\xedn-1 Author'), 'file': { 'data': 'red\ngre\u00e9n\nblue\n'.encode('latin-1') }, } + @unittest.skipIf( + sys.platform.startswith("win") and sys.version_info.major == 2, + "Known issue for Windows and py2") + def testNonASCIIAuthorName(self): + """Ensures correct tabulation. + + Tests the case where there are non-ASCII (UTF-8) characters in the author + name. + + Regression test for https://crbug.com/808905. + + This test is disabled only for Windows and Python2 as `author` gets escaped + differently. + """ + # Known issue with Windows and py2, skip test for such env + expected_output = [ + self.blame_line('A', '1) red', author='ASCII Author'), + # Expect 8 spaces, to line up with the other name. + self.blame_line( + 'B', '2) green', author='\u4e2d\u56fd\u4f5c\u8005 '), + self.blame_line('A', '3) blue', author='ASCII Author'), + ] + retval, output = self.run_hyperblame([], 'file', 'tag_B') + self.assertEqual(0, retval) + self.assertEqual(expected_output, output) + def testNonUTF8Data(self): """Ensures correct behaviour even if author or file data is not UTF-8. diff --git a/tests/git_map_test.py b/tests/git_map_test.py index ecb272eaa..60d44f512 100644 --- a/tests/git_map_test.py +++ b/tests/git_map_test.py @@ -5,12 +5,14 @@ # found in the LICENSE file. """Tests for git_map.""" +from __future__ import print_function +from __future__ import unicode_literals + import io import os import re import sys import unittest -from unittest import mock DEPOT_TOOLS_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, DEPOT_TOOLS_ROOT) @@ -20,6 +22,11 @@ from testing_support import git_test_utils import git_map import git_common +if sys.version_info.major == 2: + import mock +else: + from unittest import mock + git_common.TEST_MODE = True GitRepo = git_test_utils.GitRepo @@ -104,7 +111,7 @@ class GitMapTest(git_test_utils.GitRepoReadOnlyTestBase): '* 315457dbe8 (tag_B) 1970-01-04 ~ B', '* cd589e62d8 (tag_A, origin/root_A) 1970-01-02 ~ A', '* 7026d3d68e (tag_", root_", main, branch_") 1970-01-02 ~ "', - ]) + ]) outbuf = io.BytesIO() self.repo.run(git_map.main, [], outbuf) output = outbuf.getvalue() diff --git a/tests/git_migrate_default_branch_test.py b/tests/git_migrate_default_branch_test.py index 8f227e53b..977713bda 100755 --- a/tests/git_migrate_default_branch_test.py +++ b/tests/git_migrate_default_branch_test.py @@ -8,7 +8,11 @@ import collections import os import sys import unittest -from unittest import mock + +if sys.version_info.major == 2: + import mock +else: + from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) diff --git a/tests/git_rebase_update_test.py b/tests/git_rebase_update_test.py index 492c2e076..dd4276121 100755 --- a/tests/git_rebase_update_test.py +++ b/tests/git_rebase_update_test.py @@ -5,6 +5,9 @@ """Unit tests for git_rebase_update.py""" +from __future__ import print_function +from __future__ import unicode_literals + import os import sys diff --git a/tests/owners_client_test.py b/tests/owners_client_test.py index 22ebfdb6f..3e69c7697 100755 --- a/tests/owners_client_test.py +++ b/tests/owners_client_test.py @@ -6,13 +6,19 @@ import os import sys import unittest -from unittest import mock + +if sys.version_info.major == 2: + import mock +else: + from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import gerrit_util import owners_client +from testing_support import filesystem_mock + alice = 'alice@example.com' bob = 'bob@example.com' diff --git a/tests/owners_finder_test.py b/tests/owners_finder_test.py index 0f43716ba..56955954f 100755 --- a/tests/owners_finder_test.py +++ b/tests/owners_finder_test.py @@ -8,7 +8,11 @@ import os import sys import unittest -from unittest import mock + +if sys.version_info.major == 2: + import mock +else: + from unittest import mock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))