From 01682c1dcfd5fa92f08c00437fadb4650b8d4bf9 Mon Sep 17 00:00:00 2001 From: Stephen Finucane Date: Wed, 15 Dec 2021 10:18:17 +0000 Subject: Remove logic for Python < 3.6 Signed-off-by: Stephen Finucane --- filters/subunit2gtk | 24 ++++++--------- python/subunit/__init__.py | 13 ++------ python/subunit/iso8601.py | 21 +++++-------- python/subunit/run.py | 5 +--- python/subunit/tests/test_subunit_filter.py | 4 --- python/subunit/tests/test_test_protocol.py | 46 ++++++++--------------------- python/subunit/tests/test_test_results.py | 10 ++----- python/subunit/v2.py | 33 +++++++++------------ 8 files changed, 50 insertions(+), 106 deletions(-) diff --git a/filters/subunit2gtk b/filters/subunit2gtk index 5c0ebe3..fb8f984 100755 --- a/filters/subunit2gtk +++ b/filters/subunit2gtk @@ -174,26 +174,15 @@ class GTKTestResult(unittest.TestResult): GObject.idle_add(self.update_counts) def addSkip(self, test, reason): - # addSkip is new in Python 2.7/3.1 - addSkip = getattr(super(GTKTestResult, self), 'addSkip', None) - if callable(addSkip): - addSkip(test, reason) + super(GTKTestResult, self).addSkip(test, reason) GObject.idle_add(self.update_counts) def addExpectedFailure(self, test, err): - # addExpectedFailure is new in Python 2.7/3.1 - addExpectedFailure = getattr(super(GTKTestResult, self), - 'addExpectedFailure', None) - if callable(addExpectedFailure): - addExpectedFailure(test, err) + super(GTKTestResult, self).addExpectedFailure(test, err) GObject.idle_add(self.update_counts) def addUnexpectedSuccess(self, test): - # addUnexpectedSuccess is new in Python 2.7/3.1 - addUnexpectedSuccess = getattr(super(GTKTestResult, self), - 'addUnexpectedSuccess', None) - if callable(addUnexpectedSuccess): - addUnexpectedSuccess(test) + super(GTKTestResult, self).addUnexpectedSuccess(test) GObject.idle_add(self.update_counts) def progress(self, offset, whence): @@ -218,16 +207,21 @@ class GTKTestResult(unittest.TestResult): self.ok_label.set_text(str(self.testsRun - bad)) self.not_ok_label.set_text(str(bad)) + GObject.threads_init() result = StreamToExtendedDecorator(GTKTestResult()) test = ByteStreamToStreamResult(sys.stdin, non_subunit_name='stdout') # Get setup while Gtk.events_pending(): - Gtk.main_iteration() + Gtk.main_iteration() + + # Start IO def run_and_finish(): test.run(result) result.stopTestRun() + + t = threading.Thread(target=run_and_finish) t.daemon = True result.startTestRun() diff --git a/python/subunit/__init__.py b/python/subunit/__init__.py index 6917f42..614c647 100644 --- a/python/subunit/__init__.py +++ b/python/subunit/__init__.py @@ -42,8 +42,7 @@ Twisted. See the ``TestProtocolServer`` parser class for more details. Subunit includes extensions to the Python ``TestResult`` protocol. These are all done in a compatible manner: ``TestResult`` objects that do not implement the extension methods will not cause errors to be raised, instead the extension -will either lose fidelity (for instance, folding expected failures to success -in Python versions < 2.7 or 3.1), or discard the extended data (for extra +will either lose fidelity, or discard the extended data (for extra details, tags, timestamping and progress markers). The test outcome methods ``addSuccess``, ``addError``, ``addExpectedFailure``, @@ -513,9 +512,7 @@ class TestProtocolServer(object): """ self.client = ExtendedToOriginalDecorator(client) if stream is None: - stream = sys.stdout - if sys.version_info > (3, 0): - stream = stream.buffer + stream = sys.stdout.buffer self._stream = stream self._forward_stream = forward_stream or DiscardStream() # state objects we can switch too @@ -1292,11 +1289,7 @@ def _make_binary_on_windows(fileno): def _unwrap_text(stream): """Unwrap stream if it is a text stream to get the original buffer.""" exceptions = (_UnsupportedOperation, IOError) - if sys.version_info > (3, 0): - unicode_type = str - else: - unicode_type = unicode - exceptions += (ValueError,) + unicode_type = str try: # Read streams if type(stream.read(0)) is unicode_type: diff --git a/python/subunit/iso8601.py b/python/subunit/iso8601.py index 07855d0..7d392d4 100644 --- a/python/subunit/iso8601.py +++ b/python/subunit/iso8601.py @@ -1,5 +1,5 @@ # Copyright (c) 2007 Michael Twomey -# +# # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including @@ -7,10 +7,10 @@ # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: -# +# # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. -# +# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. @@ -31,7 +31,6 @@ datetime.datetime(2007, 1, 25, 12, 0, tzinfo=) from datetime import datetime, timedelta, tzinfo import re -import sys __all__ = ["parse_date", "ParseError"] @@ -47,10 +46,6 @@ TIMEZONE_REGEX = re.compile(TIMEZONE_REGEX_PATTERN.encode('utf8')) zulu = "Z".encode('latin-1') minus = "-".encode('latin-1') -if sys.version_info < (3, 0): - bytes = str - - class ParseError(Exception): """Raised when there is a problem parsing a date string""" @@ -58,7 +53,7 @@ class ParseError(Exception): ZERO = timedelta(0) class Utc(tzinfo): """UTC - + """ def utcoffset(self, dt): return ZERO @@ -72,7 +67,7 @@ UTC = Utc() class FixedOffset(tzinfo): """Fixed offset in hours and minutes from UTC - + """ def __init__(self, offset_hours, offset_minutes, name): self.__offset = timedelta(hours=offset_hours, minutes=offset_minutes) @@ -86,13 +81,13 @@ class FixedOffset(tzinfo): def dst(self, dt): return ZERO - + def __repr__(self): return "" % self.__name def parse_timezone(tzstring, default_timezone=UTC): """Parses ISO 8601 time zone specs into tzinfo offsets - + """ if tzstring == zulu: return default_timezone @@ -111,7 +106,7 @@ def parse_timezone(tzstring, default_timezone=UTC): def parse_date(datestring, default_timezone=UTC): """Parses ISO 8601 dates into datetime objects - + The timezone is parsed from the date string. However it is quite common to have dates without a timezone (not strictly correct). In this case the default timezone specified in default_timezone is used. This is UTC by diff --git a/python/subunit/run.py b/python/subunit/run.py index 6b20351..366e855 100755 --- a/python/subunit/run.py +++ b/python/subunit/run.py @@ -136,10 +136,7 @@ def main(argv=None, stdout=None): if hasattr(stdout, 'fileno'): # Patch stdout to be unbuffered, so that pdb works well on 2.6/2.7. binstdout = io.open(stdout.fileno(), 'wb', 0) - if sys.version_info[0] > 2: - sys.stdout = io.TextIOWrapper(binstdout, encoding=sys.stdout.encoding) - else: - sys.stdout = binstdout + sys.stdout = io.TextIOWrapper(binstdout, encoding=sys.stdout.encoding) stdout = sys.stdout SubunitTestProgram(module=None, argv=argv, testRunner=runner, stdout=stdout, exit=False) diff --git a/python/subunit/tests/test_subunit_filter.py b/python/subunit/tests/test_subunit_filter.py index baef3f6..364fad9 100644 --- a/python/subunit/tests/test_subunit_filter.py +++ b/python/subunit/tests/test_subunit_filter.py @@ -300,10 +300,6 @@ xfail todo ('stopTest', 'foo - renamed')], [(ev[0], ev[1].id()) for ev in result._events]) - if sys.version_info < (2, 7): - # These tests require Python >=2.7. - del test_fixup_expected_failures, test_fixup_expected_errors, test_fixup_unexpected_success - class TestFilterCommand(TestCase): diff --git a/python/subunit/tests/test_test_protocol.py b/python/subunit/tests/test_test_protocol.py index 70e3564..a498b33 100644 --- a/python/subunit/tests/test_test_protocol.py +++ b/python/subunit/tests/test_test_protocol.py @@ -20,7 +20,6 @@ import os import tempfile import unittest -import six from testtools import PlaceHolder, skipIf, TestCase, TestResult from testtools.compat import _b, _u try: @@ -65,21 +64,13 @@ class TestHelpers(TestCase): fd, file_path = tempfile.mkstemp() self.addCleanup(os.remove, file_path) fake_file = os.fdopen(fd, 'r') - if six.PY3: - self.assertEqual(fake_file.buffer, - subunit._unwrap_text(fake_file)) - else: - self.assertEqual(fake_file, subunit._unwrap_text(fake_file)) + self.assertEqual(fake_file.buffer, subunit._unwrap_text(fake_file)) def test__unwrap_text_file_write_mode(self): fd, file_path = tempfile.mkstemp() self.addCleanup(os.remove, file_path) fake_file = os.fdopen(fd, 'w') - if six.PY3: - self.assertEqual(fake_file.buffer, - subunit._unwrap_text(fake_file)) - else: - self.assertEqual(fake_file, subunit._unwrap_text(fake_file)) + self.assertEqual(fake_file.buffer, subunit._unwrap_text(fake_file)) def test__unwrap_text_fileIO_read_mode(self): fd, file_path = tempfile.mkstemp() @@ -157,20 +148,14 @@ class TestTestProtocolServerPipe(unittest.TestCase): protocol.readFrom(pipe) bing = subunit.RemotedTestCase("bing crosby") an_error = subunit.RemotedTestCase("an error") - if six.PY3: - self.assertEqual(client.errors, - [(an_error, _remote_exception_repr + '\n')]) - self.assertEqual( - client.failures, - [(bing, _remote_exception_repr + ": " - + details_to_str({'traceback': text_content(traceback)}) + "\n")]) - else: - self.assertEqual(client.errors, - [(an_error, '_StringException\n')]) - self.assertEqual( - client.failures, - [(bing, "_StringException: " - + details_to_str({'traceback': text_content(traceback)}) + "\n")]) + self.assertEqual( + client.errors, [(an_error, _remote_exception_repr + '\n')], + ) + self.assertEqual( + client.failures, + [(bing, _remote_exception_repr + ": " + + details_to_str({'traceback': text_content(traceback)}) + "\n")], + ) self.assertEqual(client.testsRun, 3) def test_non_test_characters_forwarded_immediately(self): @@ -1024,14 +1009,9 @@ class TestRemotedTestCase(unittest.TestCase): "'A test description'>", "%r" % test) result = unittest.TestResult() test.run(result) - if six.PY3: - self.assertEqual([(test, _remote_exception_repr + ': ' + - "Cannot run RemotedTestCases.\n\n")], - result.errors) - else: - self.assertEqual([(test, "_StringException: " + - "Cannot run RemotedTestCases.\n\n")], - result.errors) + self.assertEqual([(test, _remote_exception_repr + ': ' + + "Cannot run RemotedTestCases.\n\n")], + result.errors) self.assertEqual(1, result.testsRun) another_test = subunit.RemotedTestCase("A test description") self.assertEqual(test, another_test) diff --git a/python/subunit/tests/test_test_results.py b/python/subunit/tests/test_test_results.py index add30bb..a0efa80 100644 --- a/python/subunit/tests/test_test_results.py +++ b/python/subunit/tests/test_test_results.py @@ -380,10 +380,7 @@ class TestByTestResultTests(testtools.TestCase): super(TestByTestResultTests, self).setUp() self.log = [] self.result = subunit.test_results.TestByTestResult(self.on_test) - if sys.version_info >= (3, 0): - self.result._now = iter(range(5)).__next__ - else: - self.result._now = iter(range(5)).next + self.result._now = iter(range(5)).__next__ def assertCalled(self, **kwargs): defaults = { @@ -539,10 +536,7 @@ class TestCsvResult(testtools.TestCase): def test_csv_output(self): stream = StringIO() result = subunit.test_results.CsvResult(stream) - if sys.version_info >= (3, 0): - result._now = iter(range(5)).__next__ - else: - result._now = iter(range(5)).next + result._now = iter(range(5)).__next__ result.startTestRun() result.startTest(self) result.addSuccess(self) diff --git a/python/subunit/v2.py b/python/subunit/v2.py index e8a31d6..2137165 100644 --- a/python/subunit/v2.py +++ b/python/subunit/v2.py @@ -15,10 +15,7 @@ # import codecs -utf_8_decode = codecs.utf_8_decode import datetime -from io import UnsupportedOperation -import os import select import struct import sys @@ -30,6 +27,8 @@ builtins = try_imports(['__builtin__', 'builtins']) import subunit import subunit.iso8601 as iso8601 +utf_8_decode = codecs.utf_8_decode + __all__ = [ 'ByteStreamToStreamResult', 'StreamResultToBytes', @@ -53,7 +52,6 @@ EPOCH = datetime.datetime.utcfromtimestamp(0).replace(tzinfo=iso8601.Utc()) NUL_ELEMENT = b'\0'[0] # Contains True for types for which 'nul in thing' falsely returns false. _nul_test_broken = {} -_PY3 = (sys.version_info >= (3,)) def has_nul(buffer_or_bytes): @@ -232,21 +230,18 @@ class StreamResultToBytes(object): # For now, simplest code: join, crc32, join, output content = b''.join(packet) data = content + struct.pack(FMT_32, zlib.crc32(content) & 0xffffffff) - if _PY3: - # On eventlet 0.17.3, GreenIO.write() can make partial write. - # Use a loop to ensure that all bytes are written. - # See also the eventlet issue: - # https://github.com/eventlet/eventlet/issues/248 - view = memoryview(data) - datalen = len(data) - offset = 0 - while offset < datalen: - written = self.output_stream.write(view[offset:]) - if written is None: - break - offset += written - else: - self.output_stream.write(data) + # On eventlet 0.17.3, GreenIO.write() can make partial write. + # Use a loop to ensure that all bytes are written. + # See also the eventlet issue: + # https://github.com/eventlet/eventlet/issues/248 + view = memoryview(data) + datalen = len(data) + offset = 0 + while offset < datalen: + written = self.output_stream.write(view[offset:]) + if written is None: + break + offset += written self.output_stream.flush() -- cgit v1.2.1