diff options
author | Yilei Yang <yileiyang@google.com> | 2022-01-24 12:08:19 -0800 |
---|---|---|
committer | Copybara-Service <copybara-worker@google.com> | 2022-01-24 12:08:51 -0800 |
commit | c7c6f8b2918bb280b290a640ebb608753ca79a6f (patch) | |
tree | 0b0db093d730fc2400d6f04b348154f4bfc3467b | |
parent | d12ab3ba5dba65e1c828bdb7427d15ae28641c13 (diff) | |
download | absl-py-c7c6f8b2918bb280b290a640ebb608753ca79a6f.tar.gz |
Remove PY2-ism in absl's own unit tests.
PiperOrigin-RevId: 423878454
Change-Id: Iadc82651ecd39954cfd2af6b4bae2a98388fd75b
-rw-r--r-- | absl/BUILD | 2 | ||||
-rw-r--r-- | absl/flags/BUILD | 7 | ||||
-rw-r--r-- | absl/flags/tests/_argument_parser_test.py | 14 | ||||
-rw-r--r-- | absl/flags/tests/_flagvalues_test.py | 17 | ||||
-rw-r--r-- | absl/flags/tests/argparse_flags_test.py | 12 | ||||
-rw-r--r-- | absl/flags/tests/flags_helpxml_test.py | 20 | ||||
-rw-r--r-- | absl/flags/tests/flags_test.py | 34 | ||||
-rw-r--r-- | absl/logging/BUILD | 6 | ||||
-rw-r--r-- | absl/logging/tests/logging_functional_test.py | 99 | ||||
-rw-r--r-- | absl/logging/tests/logging_functional_test_helper.py | 13 | ||||
-rw-r--r-- | absl/logging/tests/logging_test.py | 49 | ||||
-rw-r--r-- | absl/testing/BUILD | 4 | ||||
-rw-r--r-- | absl/testing/tests/absltest_test.py | 102 | ||||
-rw-r--r-- | absl/testing/tests/parameterized_test.py | 8 | ||||
-rw-r--r-- | absl/testing/tests/xml_reporter_test.py | 100 | ||||
-rw-r--r-- | absl/tests/app_test.py | 45 |
16 files changed, 126 insertions, 406 deletions
@@ -65,8 +65,6 @@ py_test( "//absl/testing:_bazelize_command", "//absl/testing:absltest", "//absl/testing:flagsaver", - "@mock_archive//:mock", - "@six_archive//:six", ], ) diff --git a/absl/flags/BUILD b/absl/flags/BUILD index 326fe0b..d54af1d 100644 --- a/absl/flags/BUILD +++ b/absl/flags/BUILD @@ -124,7 +124,6 @@ py_test( ":_argument_parser", "//absl/testing:absltest", "//absl/testing:parameterized", - "@six_archive//:six", ], ) @@ -158,8 +157,6 @@ py_test( "//absl/logging", "//absl/testing:absltest", "//absl/testing:parameterized", - "@mock_archive//:mock", - "@six_archive//:six", ], ) @@ -206,8 +203,6 @@ py_test( "//absl/testing:_bazelize_command", "//absl/testing:absltest", "//absl/testing:parameterized", - "@mock_archive//:mock", - "@six_archive//:six", ], ) @@ -248,7 +243,6 @@ py_test( ":flags", ":tests/module_bar", "//absl/testing:absltest", - "@six_archive//:six", ], ) @@ -280,7 +274,6 @@ py_test( ":tests/module_baz", ":tests/module_foo", "//absl/testing:absltest", - "@six_archive//:six", ], ) diff --git a/absl/flags/tests/_argument_parser_test.py b/absl/flags/tests/_argument_parser_test.py index 5373838..4281c3f 100644 --- a/absl/flags/tests/_argument_parser_test.py +++ b/absl/flags/tests/_argument_parser_test.py @@ -16,15 +16,11 @@ Most of the argument parsers are covered in the flags_test.py. """ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import enum + from absl.flags import _argument_parser from absl.testing import absltest from absl.testing import parameterized -import six class ArgumentParserTest(absltest.TestCase): @@ -48,14 +44,12 @@ class ArgumentParserTest(absltest.TestCase): class BooleanParserTest(absltest.TestCase): def setUp(self): + super().setUp() self.parser = _argument_parser.BooleanParser() def test_parse_bytes(self): - if six.PY2: - self.assertTrue(self.parser.parse(b'true')) - else: - with self.assertRaises(TypeError): - self.parser.parse(b'true') + with self.assertRaises(TypeError): + self.parser.parse(b'true') def test_parse_str(self): self.assertTrue(self.parser.parse('true')) diff --git a/absl/flags/tests/_flagvalues_test.py b/absl/flags/tests/_flagvalues_test.py index 6dd3e5c..46639f2 100644 --- a/absl/flags/tests/_flagvalues_test.py +++ b/absl/flags/tests/_flagvalues_test.py @@ -14,15 +14,11 @@ """Tests for flags.FlagValues class.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import collections import copy import pickle import types -import unittest +from unittest import mock from absl import logging from absl.flags import _defines @@ -33,8 +29,6 @@ from absl.flags import _validators from absl.flags.tests import module_foo from absl.testing import absltest from absl.testing import parameterized -import mock -import six class FlagValuesTest(absltest.TestCase): @@ -853,15 +847,6 @@ class UnparsedFlagAccessTest(absltest.TestCase): with self.assertRaises(_exceptions.UnparsedFlagAccessError): _ = fv.name - @unittest.skipIf(six.PY3, 'Python 2 only test') - def test_hasattr_logs_in_py2(self): - fv = _flagvalues.FlagValues() - _defines.DEFINE_string('name', 'default', 'help', flag_values=fv) - with mock.patch.object(_flagvalues.logging, 'error') as mock_error: - self.assertFalse(hasattr(fv, 'name')) - mock_error.assert_called_once() - - @unittest.skipIf(six.PY2, 'Python 3 only test') def test_hasattr_raises_in_py3(self): fv = _flagvalues.FlagValues() _defines.DEFINE_string('name', 'default', 'help', flag_values=fv) diff --git a/absl/flags/tests/argparse_flags_test.py b/absl/flags/tests/argparse_flags_test.py index a2bcbe5..5e6f49a 100644 --- a/absl/flags/tests/argparse_flags_test.py +++ b/absl/flags/tests/argparse_flags_test.py @@ -14,14 +14,12 @@ """Tests for absl.flags.argparse_flags.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - +import io import os import subprocess import sys import tempfile +from unittest import mock from absl import flags from absl import logging @@ -29,8 +27,6 @@ from absl.flags import argparse_flags from absl.testing import _bazelize_command from absl.testing import absltest from absl.testing import parameterized -import mock -import six class ArgparseFlagsTest(parameterized.TestCase): @@ -149,7 +145,7 @@ class ArgparseFlagsTest(parameterized.TestCase): def test_dashes(self, argument, expected): parser = argparse_flags.ArgumentParser( inherited_absl_flags=self._absl_flags) - if isinstance(expected, six.string_types): + if isinstance(expected, str): parser.parse_args([argument]) self.assertEqual(self._absl_flags.absl_string, expected) else: @@ -286,7 +282,7 @@ class ArgparseFlagsTest(parameterized.TestCase): parser = argparse_flags.ArgumentParser( inherited_absl_flags=self._absl_flags) with self.assertRaises(SystemExit),\ - mock.patch.object(sys, 'stdout', new=six.StringIO()) as mock_stdout: + mock.patch.object(sys, 'stdout', new=io.StringIO()) as mock_stdout: parser.parse_args(['--helpfull']) stdout_message = mock_stdout.getvalue() logging.info('captured stdout message:\n%s', stdout_message) diff --git a/absl/flags/tests/flags_helpxml_test.py b/absl/flags/tests/flags_helpxml_test.py index 2f5ca17..424c3dd 100644 --- a/absl/flags/tests/flags_helpxml_test.py +++ b/absl/flags/tests/flags_helpxml_test.py @@ -14,10 +14,6 @@ """Unit tests for the XML-format help generated by the flags.py module.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import enum import io import os @@ -30,7 +26,6 @@ from absl import flags from absl.flags import _helpers from absl.flags.tests import module_bar from absl.testing import absltest -import six class CreateXMLDOMElement(absltest.TestCase): @@ -49,15 +44,10 @@ class CreateXMLDOMElement(absltest.TestCase): # If the value is bytes with invalid unicode: bytes_with_invalid_unicodes = b'\x81\xff' - if six.PY2: - # In python 2 the string representation is invalid unicode so they are - # stripped. - self._check('tag', bytes_with_invalid_unicodes, b'<tag></tag>\n') - else: - # In python 3 the string representation is "b'\x81\xff'" so they are kept - # as "b'\x81\xff'". - self._check('tag', bytes_with_invalid_unicodes, - b"<tag>b'\\x81\\xff'</tag>\n") + # In python 3 the string representation is "b'\x81\xff'" so they are kept + # as "b'\x81\xff'". + self._check('tag', bytes_with_invalid_unicodes, + b"<tag>b'\\x81\\xff'</tag>\n") # Some unicode chars are illegal in xml # (http://www.w3.org/TR/REC-xml/#charsets): @@ -629,7 +619,7 @@ class WriteHelpInXMLFormatTest(absltest.TestCase): flags.declare_key_flag('tmod_bar_u', flag_values=fv) # Generate flag help in XML format in the StringIO sio. - sio = io.StringIO() if six.PY3 else io.BytesIO() + sio = io.StringIO() fv.write_help_in_xml_format(sio) # Check that we got the expected result. diff --git a/absl/flags/tests/flags_test.py b/absl/flags/tests/flags_test.py index b76fc86..75a61d5 100644 --- a/absl/flags/tests/flags_test.py +++ b/absl/flags/tests/flags_test.py @@ -13,10 +13,6 @@ # limitations under the License. """Tests for absl.flags used as a package.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import contextlib import enum import io @@ -33,7 +29,6 @@ from absl.flags.tests import module_bar from absl.flags.tests import module_baz from absl.flags.tests import module_foo from absl.testing import absltest -import six FLAGS = flags.FLAGS @@ -117,8 +112,7 @@ class AliasFlagsTest(absltest.TestCase): def assert_alias_mirrors_aliased(self, alias, aliased, ignore_due_to_bug=()): # A few sanity checks to avoid false success - if six.PY3: - self.assertIn('FlagAlias', alias.__class__.__qualname__) + self.assertIn('FlagAlias', alias.__class__.__qualname__) self.assertIsNot(alias, aliased) self.assertNotEqual(aliased.name, alias.name) @@ -541,7 +535,7 @@ class FlagsUnitTest(absltest.TestCase): argv = ('./program', '--x', '0x1234567890ABCDEF1234567890ABCDEF') argv = FLAGS(argv) self.assertEqual(FLAGS.x, 0x1234567890ABCDEF1234567890ABCDEF) - self.assertIsInstance(FLAGS.x, six.integer_types) + self.assertIsInstance(FLAGS.x, int) argv = ('./program', '--x', '0o12345') argv = FLAGS(argv) @@ -1727,11 +1721,9 @@ class UnicodeFlagsTest(absltest.TestCase): b'help:\xC3\xAD'.decode('utf-8'), flag_values=fv) - outfile = io.StringIO() if six.PY3 else io.BytesIO() + outfile = io.StringIO() fv.write_help_in_xml_format(outfile) actual_output = outfile.getvalue() - if six.PY2: - actual_output = actual_output.decode('utf-8') # The xml output is large, so we just check parts of it. self.assertIn( @@ -1740,20 +1732,12 @@ class UnicodeFlagsTest(absltest.TestCase): b' <default>\xc3\x80\xc3\xbd</default>\n' b' <current>\xc3\x80\xc3\xbd</current>'.decode('utf-8'), actual_output) - if six.PY2: - self.assertIn( - b'<name>unicode2</name>\n' - b' <meaning>help:\xc3\xad</meaning>\n' - b' <default>abc,\xc3\x80,\xc3\xbd</default>\n' - b" <current>['abc', u'\\xc0', u'\\xfd']" - b'</current>'.decode('utf-8'), actual_output) - else: - self.assertIn( - b'<name>unicode2</name>\n' - b' <meaning>help:\xc3\xad</meaning>\n' - b' <default>abc,\xc3\x80,\xc3\xbd</default>\n' - b" <current>['abc', '\xc3\x80', '\xc3\xbd']" - b'</current>'.decode('utf-8'), actual_output) + self.assertIn( + b'<name>unicode2</name>\n' + b' <meaning>help:\xc3\xad</meaning>\n' + b' <default>abc,\xc3\x80,\xc3\xbd</default>\n' + b" <current>['abc', '\xc3\x80', '\xc3\xbd']" + b'</current>'.decode('utf-8'), actual_output) self.assertIn( b'<name>non_unicode</name>\n' b' <meaning>help:\xc3\xad</meaning>\n' diff --git a/absl/logging/BUILD b/absl/logging/BUILD index 9c7b2d3..d83a2b6 100644 --- a/absl/logging/BUILD +++ b/absl/logging/BUILD @@ -45,8 +45,6 @@ py_test( "//absl/testing:absltest", "//absl/testing:flagsaver", "//absl/testing:parameterized", - "@mock_archive//:mock", - "@six_archive//:six", ], ) @@ -85,8 +83,6 @@ py_binary( ":logging", "//absl:app", "//absl/flags", - "@mock_archive//:mock", - "@six_archive//:six", ], ) @@ -100,10 +96,8 @@ py_test( srcs_version = "PY3", deps = [ ":logging", - "//absl/flags", "//absl/testing:_bazelize_command", "//absl/testing:absltest", "//absl/testing:parameterized", - "@six_archive//:six", ], ) diff --git a/absl/logging/tests/logging_functional_test.py b/absl/logging/tests/logging_functional_test.py index 565555c..faa0de4 100644 --- a/absl/logging/tests/logging_functional_test.py +++ b/absl/logging/tests/logging_functional_test.py @@ -14,10 +14,6 @@ """Functional tests for absl.logging.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import fnmatch import os import re @@ -30,7 +26,7 @@ from absl import logging from absl.testing import _bazelize_command from absl.testing import absltest from absl.testing import parameterized -import six + _PY_VLOG3_LOG_MESSAGE = """\ I1231 23:59:59.000000 12345 logging_functional_test_helper.py:62] This line is VLOG level 3 @@ -178,11 +174,10 @@ def _get_fatal_log_expectation(testcase, message, include_stacktrace): expected_logs = format_string % message if include_stacktrace: expected_logs += 'Stack trace:\n' - if six.PY3: - faulthandler_start = 'Fatal Python error: Aborted' - testcase.assertIn(faulthandler_start, logs) - log_message = logs.split(faulthandler_start)[0] - testcase.assertEqual(_munge_log(expected_logs), _munge_log(log_message)) + faulthandler_start = 'Fatal Python error: Aborted' + testcase.assertIn(faulthandler_start, logs) + log_message = logs.split(faulthandler_start)[0] + testcase.assertEqual(_munge_log(expected_logs), _munge_log(log_message)) return assert_logs @@ -310,10 +305,8 @@ class FunctionalTest(parameterized.TestCase): logs.append(_PY_ERROR_LOG_MESSAGE) expected_logs = ''.join(logs) - if six.PY3: - # In Python 3 class types are represented a bit differently - expected_logs = expected_logs.replace( - "<type 'exceptions.OSError'>", "<class 'OSError'>") + expected_logs = expected_logs.replace( + "<type 'exceptions.OSError'>", "<class 'OSError'>") return expected_logs def setUp(self): @@ -434,11 +427,7 @@ class FunctionalTest(parameterized.TestCase): actual = output else: path = os.path.join(self._log_dir, basename) - if six.PY2: - f = open(path) - else: - f = open(path, encoding='utf-8') - with f: + with open(path, encoding='utf-8') as f: actual = f.read() if callable(expected): @@ -673,34 +662,11 @@ E0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] std error log def test_none_exc_info_py_logging(self): - if six.PY2: - expected_stderr = '' - expected_info = '''\ -I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] None exc_info -None -''' - else: - if sys.version_info[0:2] == (3, 4): - # Python 3.4 is different. - def expected_stderr(stderr): - regex = r'''--- Logging error --- -Traceback \(most recent call last\): -.* -Message: 'None exc_info' -Arguments: \(\)''' - if not re.search(regex, stderr, flags=re.DOTALL | re.MULTILINE): - self.fail('Cannot find regex "%s" in stderr:\n%s' % (regex, stderr)) - expected_info = '' - else: - expected_stderr = '' - expected_info = '''\ + expected_stderr = '' + expected_info = '''\ I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] None exc_info ''' - # Python 3.5.0 to 3.5.2 are different too. - if (3, 5, 0) <= sys.version_info[:3] <= (3, 5, 2): - expected_info += 'NoneType\n' - else: - expected_info += 'NoneType: None\n' + expected_info += 'NoneType: None\n' expected_logs = [ ['stderr', None, expected_stderr], @@ -722,33 +688,7 @@ I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] None exc_info match, 'Cannot find stderr message for test {}'.format(name)) return match.group(1) - def assert_stderr_python2(stderr): - """Verifies that it writes correct information to stderr for Python 2. - - For unicode errors, it logs the exception with a stack trace to stderr. - - Args: - stderr: the message from stderr. - """ - # Successful logs: - for name in ('unicode', 'unicode % unicode', 'bytes % bytes'): - self.assertEqual('', get_stderr_message(stderr, name)) - - # UnicodeDecodeError errors: - for name in ( - 'unicode % bytes', 'bytes % unicode', 'unicode % iso8859-15'): - self.assertIn('UnicodeDecodeError', - get_stderr_message(stderr, name)) - self.assertIn('Traceback (most recent call last):', - get_stderr_message(stderr, name)) - - # UnicodeEncodeError errors: - self.assertIn('UnicodeEncodeError', - get_stderr_message(stderr, 'str % exception')) - self.assertIn('Traceback (most recent call last):', - get_stderr_message(stderr, 'str % exception')) - - def assert_stderr_python3(stderr): + def assert_stderr(stderr): """Verifies that it writes correct information to stderr for Python 3. There are no unicode errors in Python 3. @@ -764,20 +704,9 @@ I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] None exc_info logging.info('name = %s', name) self.assertEqual('', get_stderr_message(stderr, name)) - expected_logs = [[ - 'stderr', None, - assert_stderr_python2 if six.PY2 else assert_stderr_python3]] + expected_logs = [['stderr', None, assert_stderr]] - if six.PY2: - # In Python 2, only successfully formatted messages are logged. - info_log = u'''\ -I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] G\u00eete: Ch\u00e2tonnaye -I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] G\u00eete: Ch\u00e2tonnaye -I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] G\u00eete: Ch\u00e2tonnaye -'''.encode('utf-8') - else: - # In Python 3, all messages are formatted successfully and logged. - info_log = u'''\ + info_log = u'''\ I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] G\u00eete: Ch\u00e2tonnaye I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] G\u00eete: Ch\u00e2tonnaye I0000 00:00:00.000000 12345 logging_functional_test_helper.py:123] b'G\\xc3\\xaete: b'Ch\\xc3\\xa2tonnaye'' diff --git a/absl/logging/tests/logging_functional_test_helper.py b/absl/logging/tests/logging_functional_test_helper.py index 904ddb3..0eccc74 100644 --- a/absl/logging/tests/logging_functional_test_helper.py +++ b/absl/logging/tests/logging_functional_test_helper.py @@ -14,22 +14,17 @@ """Helper script for logging_functional_test.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import logging as std_logging import os import sys import threading import time import timeit +from unittest import mock from absl import app from absl import flags from absl import logging -import mock -from six.moves import xrange # pylint: disable=redefined-builtin FLAGS = flags.FLAGS @@ -71,14 +66,14 @@ def _test_do_logging(): 2) mock_timer.return_value = mock_timer() + .2 - for i in xrange(1, 5): + for i in range(1, 5): logging.log_first_n(logging.INFO, 'Info first %d of %d', 2, i, 2) logging.log_every_n(logging.INFO, 'Info %d (every %d)', 3, i, 3) logging.vlog(-1, 'This line is VLOG level -1') logging.log(-1, 'This line is log level -1') logging.warning('Worrying Stuff') - for i in xrange(1, 5): + for i in range(1, 5): logging.log_first_n(logging.WARNING, 'Warn first %d of %d', 2, i, 2) logging.log_every_n(logging.WARNING, 'Warn %d (every %d)', 3, i, 3) @@ -103,7 +98,7 @@ def _test_do_logging(): logging.error('No traceback', exc_info=saved_exc_info[:2] + (None,)) logging.error('Alarming Stuff') - for i in xrange(1, 5): + for i in range(1, 5): logging.log_first_n(logging.ERROR, 'Error first %d of %d', 2, i, 2) logging.log_every_n(logging.ERROR, 'Error %d (every %d)', 3, i, 3) logging.flush() diff --git a/absl/logging/tests/logging_test.py b/absl/logging/tests/logging_test.py index 821588b..9f867e8 100644 --- a/absl/logging/tests/logging_test.py +++ b/absl/logging/tests/logging_test.py @@ -14,10 +14,6 @@ """Unit tests for absl.logging.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import contextlib import functools import getpass @@ -32,20 +28,16 @@ import threading import time import traceback import unittest +from unittest import mock from absl import flags from absl import logging from absl.testing import absltest from absl.testing import flagsaver from absl.testing import parameterized -import mock -import six -from six.moves import range # pylint: disable=redefined-builtin FLAGS = flags.FLAGS -_StreamIO = io.StringIO if six.PY3 else io.BytesIO # pylint: disable=invalid-name - class ConfigurationTest(absltest.TestCase): """Tests the initial logging configuration.""" @@ -53,10 +45,10 @@ class ConfigurationTest(absltest.TestCase): def test_logger_and_handler(self): absl_logger = std_logging.getLogger('absl') self.assertIs(absl_logger, logging.get_absl_logger()) - self.assertTrue(isinstance(absl_logger, logging.ABSLLogger)) - self.assertTrue( - isinstance(logging.get_absl_handler().python_handler.formatter, - logging.PythonFormatter)) + self.assertIsInstance(absl_logger, logging.ABSLLogger) + self.assertIsInstance( + logging.get_absl_handler().python_handler.formatter, + logging.PythonFormatter) class LoggerLevelsTest(parameterized.TestCase): @@ -100,7 +92,6 @@ class LoggerLevelsTest(parameterized.TestCase): actual = {r.getMessage() for r in cm.records} self.assertEqual(set(expected_msgs), actual) - @unittest.skipIf(six.PY2, 'Py2 is missing assertLogs') def test_setting_levels(self): # Other tests change the root logging level, so we can't # assume it's the default. @@ -137,6 +128,7 @@ class PythonHandlerTest(absltest.TestCase): """Tests the PythonHandler class.""" def setUp(self): + super().setUp() (year, month, day, hour, minute, sec, dunno, dayofyear, dst_flag) = (1979, 10, 21, 18, 17, 16, 3, 15, 0) self.now_tuple = (year, month, day, hour, minute, sec, @@ -145,6 +137,7 @@ class PythonHandlerTest(absltest.TestCase): def tearDown(self): mock.patch.stopall() + super().tearDown() @flagsaver.flagsaver(logtostderr=False) def test_set_google_log_file_no_log_to_stderr(self): @@ -236,7 +229,7 @@ class PythonHandlerTest(absltest.TestCase): self.python_handler._log_to_stderr.assert_called_once_with(record) def test_emit(self): - stream = _StreamIO() + stream = io.StringIO() handler = logging.PythonHandler(stream) handler.stderr_threshold = std_logging.FATAL record = std_logging.LogRecord( @@ -246,8 +239,8 @@ class PythonHandlerTest(absltest.TestCase): @flagsaver.flagsaver(stderrthreshold='debug') def test_emit_and_stderr_threshold(self): - mock_stderr = _StreamIO() - stream = _StreamIO() + mock_stderr = io.StringIO() + stream = io.StringIO() handler = logging.PythonHandler(stream) record = std_logging.LogRecord( 'name', std_logging.INFO, 'path', 12, 'logging_msg', [], False) @@ -258,8 +251,8 @@ class PythonHandlerTest(absltest.TestCase): @flagsaver.flagsaver(alsologtostderr=True) def test_emit_also_log_to_stderr(self): - mock_stderr = _StreamIO() - stream = _StreamIO() + mock_stderr = io.StringIO() + stream = io.StringIO() handler = logging.PythonHandler(stream) handler.stderr_threshold = std_logging.FATAL record = std_logging.LogRecord( @@ -270,7 +263,7 @@ class PythonHandlerTest(absltest.TestCase): self.assertEqual(1, mock_stderr.getvalue().count('logging_msg')) def test_emit_on_stderr(self): - mock_stderr = _StreamIO() + mock_stderr = io.StringIO() with mock.patch.object(sys, 'stderr', new=mock_stderr) as mock_stderr: handler = logging.PythonHandler() handler.stderr_threshold = std_logging.INFO @@ -280,7 +273,7 @@ class PythonHandlerTest(absltest.TestCase): self.assertEqual(1, mock_stderr.getvalue().count('logging_msg')) def test_emit_fatal_absl(self): - stream = _StreamIO() + stream = io.StringIO() handler = logging.PythonHandler(stream) record = std_logging.LogRecord( 'name', std_logging.FATAL, 'path', 12, 'logging_msg', [], False) @@ -292,7 +285,7 @@ class PythonHandlerTest(absltest.TestCase): mock_flush.assert_called() # flush is also called by super class. def test_emit_fatal_non_absl(self): - stream = _StreamIO() + stream = io.StringIO() handler = logging.PythonHandler(stream) record = std_logging.LogRecord( 'name', std_logging.FATAL, 'path', 12, 'logging_msg', [], False) @@ -537,13 +530,6 @@ class ABSLLoggerTest(absltest.TestCase): self.logger.findCaller(stack_info=True)) print_stack.assert_called_once() - @unittest.skipIf(six.PY3, 'Testing Python 2 specific behavior.') - def test_find_caller_python2(self): - """Ensure that we only return three items for base class compatibility.""" - self.set_up_mock_frames() - self.logger.register_frame_to_skip('myfile.py', 'Method1') - self.assertEqual(('myfile.py', 125, 'Method2'), self.logger.findCaller()) - def test_critical(self): with mock.patch.object(self.logger, 'log'): self.logger.critical(self.message) @@ -756,8 +742,7 @@ class LoggingTest(absltest.TestCase): mock.patch.object(os.path, 'isdir'): os.path.exists.return_value = False os.path.isdir.return_value = False - exception_class = OSError if six.PY2 else FileNotFoundError - with self.assertRaises(exception_class): + with self.assertRaises(FileNotFoundError): logging.find_log_dir() def test_find_log_dir_and_names_with_args(self): @@ -824,7 +809,7 @@ class LoggingTest(absltest.TestCase): program_name=program_name, log_dir=log_dir)) def test_errors_in_logging(self): - with mock.patch.object(sys, 'stderr', new=_StreamIO()) as stderr: + with mock.patch.object(sys, 'stderr', new=io.StringIO()) as stderr: logging.info('not enough args: %s %s', 'foo') # pylint: disable=logging-too-few-args self.assertIn('Traceback (most recent call last):', stderr.getvalue()) self.assertIn('TypeError', stderr.getvalue()) diff --git a/absl/testing/BUILD b/absl/testing/BUILD index d85b84c..de77bcc 100644 --- a/absl/testing/BUILD +++ b/absl/testing/BUILD @@ -193,7 +193,6 @@ py_test( ":absltest", ":parameterized", ":tests/absltest_env", - "@six_archive//:six", ], ) @@ -230,7 +229,6 @@ py_test( ":absltest", ":parameterized", "//absl:_collections_abc", - "@six_archive//:six", ], ) @@ -246,8 +244,6 @@ py_test( ":parameterized", ":xml_reporter", "//absl/logging", - "@mock_archive//:mock", - "@six_archive//:six", ], ) diff --git a/absl/testing/tests/absltest_test.py b/absl/testing/tests/absltest_test.py index 6e8503c..48eeca8 100644 --- a/absl/testing/tests/absltest_test.py +++ b/absl/testing/tests/absltest_test.py @@ -14,19 +14,15 @@ """Tests for absltest.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import collections import contextlib import io import os +import pathlib import re import stat import string import subprocess -import sys import tempfile import unittest @@ -34,14 +30,6 @@ from absl.testing import _bazelize_command from absl.testing import absltest from absl.testing import parameterized from absl.testing.tests import absltest_env -import six - -try: - import pathlib -except ImportError: # PY2 - pathlib = None - -PY_VERSION_2 = sys.version_info[0] == 2 class HelperMixin(object): @@ -52,7 +40,7 @@ class HelperMixin(object): def run_helper(self, test_id, args, env_overrides, expect_success): env = absltest_env.inherited_env() - for key, value in six.iteritems(env_overrides): + for key, value in env_overrides.items(): if value is None: if key in env: del env[key] @@ -266,11 +254,6 @@ class TestCaseTest(absltest.TestCase, HelperMixin): # Test that sequences of unhashable objects can be tested for sameness: self.assertSameElements([[1, 2], [3, 4]], [[3, 4], [1, 2]]) - if PY_VERSION_2: - # dict's are no longer valid for < comparison in Python 3 making them - # unsortable (yay, sanity!). But we need to preserve this old behavior - # when running under Python 2. - self.assertSameElements([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}]) self.assertRaises(AssertionError, self.assertSameElements, [[1]], [[2]]) def test_assert_items_equal_hotfix(self): @@ -838,14 +821,10 @@ test case ? +++++++++++++++++++++ + own implementation that does not subclass from TestCase, of course. """ - types = (str, unicode) if PY_VERSION_2 else (str,) - - for type1 in types: - for type2 in types: - self.assertRaisesWithLiteralMatch(AssertionError, sample_text_error, - self.assertMultiLineEqual, - type1(sample_text), - type2(revised_sample_text)) + self.assertRaisesWithLiteralMatch(AssertionError, sample_text_error, + self.assertMultiLineEqual, + sample_text, + revised_sample_text) self.assertRaises(AssertionError, self.assertMultiLineEqual, (1, 2), 'str') self.assertRaises(AssertionError, self.assertMultiLineEqual, 'str', (1, 2)) @@ -1091,10 +1070,6 @@ test case self.assertTotallyOrdered([1], [2]) self.assertTotallyOrdered([1, 1, 1]) self.assertTotallyOrdered([(1, 1)], [(1, 2)], [(2, 1)]) - if PY_VERSION_2: - # In Python 3 comparing different types of elements is not supported. - self.assertTotallyOrdered([None], [1], [2]) - self.assertTotallyOrdered([1, 1, 1], ['a string']) # From the docstring. class A(object): @@ -1149,30 +1124,15 @@ test case """Like A, but not hashable.""" __hash__ = None - if PY_VERSION_2: - self.assertTotallyOrdered( - [None], # None should come before everything else. - [1], # Integers sort earlier. - [A(1, 'a')], - [A(2, 'b')], # 2 is after 1. - [ - A(3, 'c'), - B(3, 'd'), - B(3, 'e') # The second argument is irrelevant. - ], - [A(4, 'z')], - ['foo']) # Strings sort last. - else: - # Python 3 does not define ordering across different types. - self.assertTotallyOrdered( - [A(1, 'a')], - [A(2, 'b')], # 2 is after 1. - [ - A(3, 'c'), - B(3, 'd'), - B(3, 'e') # The second argument is irrelevant. - ], - [A(4, 'z')]) + self.assertTotallyOrdered( + [A(1, 'a')], + [A(2, 'b')], # 2 is after 1. + [ + A(3, 'c'), + B(3, 'd'), + B(3, 'e') # The second argument is irrelevant. + ], + [A(4, 'z')]) # Invalid. msg = 'This is a useful message' @@ -1224,10 +1184,7 @@ test case def test_assert_url_equal_different(self): msg = 'This is a useful message' - if PY_VERSION_2: - whole_msg = "'a' != 'b' : This is a useful message" - else: - whole_msg = 'This is a useful message:\n- a\n+ b\n' + whole_msg = 'This is a useful message:\n- a\n+ b\n' self.assertRaisesWithLiteralMatch(AssertionError, whole_msg, self.assertUrlEqual, 'http://a', 'http://b', msg=msg) @@ -1267,9 +1224,6 @@ test case {'one': 1}) self.assertSameStructure(collections.OrderedDict({'one': 1}), collections.defaultdict(None, {'one': 1})) - # int and long should always be treated as the same type. - if PY_VERSION_2: - self.assertSameStructure({long(3): 3}, {3: long(3)}) def test_same_structure_different(self): # Different type @@ -1483,8 +1437,7 @@ class GetCommandStderrTestCase(absltest.TestCase): absltest.get_command_stderr( ['cat', os.path.join(tmpdir, 'file.txt')], env=_env_for_command_tests())[1]) - if not PY_VERSION_2: - stderr = stderr.decode('utf-8') + stderr = stderr.decode('utf-8') self.assertRegex(stderr, 'No such file or directory') @@ -1497,7 +1450,6 @@ def cm_for_test(obj): obj.cm_state = 'exited' -@absltest.skipIf(six.PY2, 'Python 2 does not have ExitStack') class EnterContextTest(absltest.TestCase): def setUp(self): @@ -1672,25 +1624,18 @@ class EqualityAssertionTest(absltest.TestCase): self.assertEqual(same_a, same_b) self.assertEquals(same_a, same_b) self.failUnlessEqual(same_a, same_b) - if PY_VERSION_2: - # Python 3 removes the global cmp function - self.assertEqual(0, cmp(same_a, same_b)) self.assertFalse(same_a == different) self.assertTrue(same_a != different) self.assertNotEqual(same_a, different) self.assertNotEquals(same_a, different) self.failIfEqual(same_a, different) - if PY_VERSION_2: - self.assertNotEqual(0, cmp(same_a, different)) self.assertFalse(same_b == different) self.assertTrue(same_b != different) self.assertNotEqual(same_b, different) self.assertNotEquals(same_b, different) self.failIfEqual(same_b, different) - if PY_VERSION_2: - self.assertNotEqual(0, cmp(same_b, different)) def test_comparison_with_eq(self): same_a = self.EqualityTestsWithEq(42) @@ -1705,15 +1650,9 @@ class EqualityAssertionTest(absltest.TestCase): self._perform_apple_apple_orange_checks(same_a, same_b, different) def test_comparison_with_cmp_or_lt_eq(self): - if PY_VERSION_2: - # In Python 3; the __cmp__ method is no longer special. - cmp_or_lteq_class = self.EqualityTestsWithCmp - else: - cmp_or_lteq_class = self.EqualityTestsWithLtEq - - same_a = cmp_or_lteq_class(42) - same_b = cmp_or_lteq_class(42) - different = cmp_or_lteq_class(1769) + same_a = self.EqualityTestsWithLtEq(42) + same_b = self.EqualityTestsWithLtEq(42) + different = self.EqualityTestsWithLtEq(1769) self._perform_apple_apple_orange_checks(same_a, same_b, different) @@ -2102,7 +2041,6 @@ class TempFileTest(absltest.TestCase, HelperMixin): os.chmod(os.path.dirname(path), stat.S_IEXEC) # The test should pass, even though that file cannot be deleted in teardown. - @absltest.skipUnless(getattr(os, 'PathLike', None), 'Testing os.PathLike') def test_temp_file_path_like(self): tempdir = self.create_tempdir('foo') self.assertIsInstance(tempdir, os.PathLike) diff --git a/absl/testing/tests/parameterized_test.py b/absl/testing/tests/parameterized_test.py index ebfa72b..7f63d01 100644 --- a/absl/testing/tests/parameterized_test.py +++ b/absl/testing/tests/parameterized_test.py @@ -14,18 +14,12 @@ """Tests for absl.testing.parameterized.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import sys import unittest from absl._collections_abc import abc from absl.testing import absltest from absl.testing import parameterized -import six -from six.moves import range # pylint: disable=redefined-builtin class MyOwnClass(object): @@ -1044,7 +1038,7 @@ class CoopMetaclassCreationTest(absltest.TestCase): def __init__(cls, name, bases, dct): type.__init__(cls, name, bases, dct) - for member_name, obj in six.iteritems(dct): + for member_name, obj in dct.items(): if member_name.startswith('test'): setattr(cls, member_name, lambda self, f=obj: _decorate_with_side_effects(f, self)) diff --git a/absl/testing/tests/xml_reporter_test.py b/absl/testing/tests/xml_reporter_test.py index 1b66924..0261f64 100644 --- a/absl/testing/tests/xml_reporter_test.py +++ b/absl/testing/tests/xml_reporter_test.py @@ -12,11 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - import datetime +import io import os import re import subprocess @@ -25,6 +22,7 @@ import tempfile import threading import time import unittest +from unittest import mock from xml.etree import ElementTree from xml.parsers import expat @@ -33,11 +31,9 @@ from absl.testing import _bazelize_command from absl.testing import absltest from absl.testing import parameterized from absl.testing import xml_reporter -import mock -import six -class StringIOWriteLn(six.StringIO): +class StringIOWriteLn(io.StringIO): def writeln(self, line): self.write(line + '\n') @@ -67,14 +63,16 @@ def xml_escaped_exception_type(exception_type): OUTPUT_STRING = '\n'.join([ r'<\?xml version="1.0"\?>', - '<testsuites name="" tests="%(tests)d" failures="%(failures)d"' - ' errors="%(errors)d" time="%(run_time).1f" timestamp="%(start_time)s">', - '<testsuite name="%(suite_name)s" tests="%(tests)d"' - ' failures="%(failures)d" errors="%(errors)d" time="%(run_time).1f" timestamp="%(start_time)s">', - ' <testcase name="%(test_name)s" status="%(status)s" result="%(result)s"' - ' time="%(run_time).1f" classname="%(classname)s"' - ' timestamp="%(start_time)s">%(message)s', ' </testcase>', '</testsuite>', - '</testsuites>' + ('<testsuites name="" tests="%(tests)d" failures="%(failures)d"' + ' errors="%(errors)d" time="%(run_time).1f" timestamp="%(start_time)s">'), + ('<testsuite name="%(suite_name)s" tests="%(tests)d"' + ' failures="%(failures)d" errors="%(errors)d" time="%(run_time).1f"' + ' timestamp="%(start_time)s">'), + (' <testcase name="%(test_name)s" status="%(status)s" result="%(result)s"' + ' time="%(run_time).1f" classname="%(classname)s"' + ' timestamp="%(start_time)s">%(message)s'), + ' </testcase>', '</testsuite>', + '</testsuites>', ]) FAILURE_MESSAGE = r""" @@ -97,8 +95,8 @@ UNICODE_MESSAGE = r""" raise AssertionError\(u'\\xe9'\) AssertionError: {0} \]\]></%s>""".format( - r'\\xe9' if six.PY2 else r'\xe9', - xml_escaped_exception_type(AssertionError)) + r'\xe9', + xml_escaped_exception_type(AssertionError)) NEWLINE_MESSAGE = r""" <%s message="{0}" type="{1}"><!\[CDATA\[Traceback \(most recent call last\): @@ -113,9 +111,10 @@ AssertionError: {3} UNEXPECTED_SUCCESS_MESSAGE = '\n'.join([ '', - r' <error message="" type=""><!\[CDATA\[Test case ' - r'__main__.MockTest.unexpectedly_passing_test should have failed, ' - r'but passed.\]\]></error>']) + (r' <error message="" type=""><!\[CDATA\[Test case ' + r'__main__.MockTest.unexpectedly_passing_test should have failed, ' + r'but passed.\]\]></error>'), +]) UNICODE_ERROR_MESSAGE = UNICODE_MESSAGE % ('error', 'error') NEWLINE_ERROR_MESSAGE = NEWLINE_MESSAGE % ('error', 'error') @@ -124,8 +123,9 @@ NEWLINE_ERROR_MESSAGE = NEWLINE_MESSAGE % ('error', 'error') class TextAndXMLTestResultTest(absltest.TestCase): def setUp(self): + super().setUp() self.stream = StringIOWriteLn() - self.xml_stream = six.StringIO() + self.xml_stream = io.StringIO() def _make_result(self, times): timer = mock.Mock() @@ -1060,50 +1060,24 @@ class XmlReporterFixtureTest(absltest.TestCase): 'error': 'test Errored!'}]}]) def test_set_up_failure(self): - if six.PY2: - # A failure in setUp() produces an error (not a failure), which is - # inconsistent with the Python unittest documentation. In Python - # 2.7, the bug appears to be in unittest.TestCase.run() method. - # Although it correctly checks for a SkipTest exception, it does - # not check for a failureException. - self._run_test( - flag='--set_up_fail', - num_errors=1, - num_failures=0, - suites=[{'name': 'FailableTest', - 'cases': [{'name': 'test', - 'classname': '__main__.FailableTest', - 'error': 'setUp Failed!'}]}]) - else: - self._run_test( - flag='--set_up_fail', - num_errors=0, - num_failures=1, - suites=[{'name': 'FailableTest', - 'cases': [{'name': 'test', - 'classname': '__main__.FailableTest', - 'failure': 'setUp Failed!'}]}]) + self._run_test( + flag='--set_up_fail', + num_errors=0, + num_failures=1, + suites=[{'name': 'FailableTest', + 'cases': [{'name': 'test', + 'classname': '__main__.FailableTest', + 'failure': 'setUp Failed!'}]}]) def test_tear_down_failure(self): - if six.PY2: - # See comment in test_set_up_failure(). - self._run_test( - flag='--tear_down_fail', - num_errors=1, - num_failures=0, - suites=[{'name': 'FailableTest', - 'cases': [{'name': 'test', - 'classname': '__main__.FailableTest', - 'error': 'tearDown Failed!'}]}]) - else: - self._run_test( - flag='--tear_down_fail', - num_errors=0, - num_failures=1, - suites=[{'name': 'FailableTest', - 'cases': [{'name': 'test', - 'classname': '__main__.FailableTest', - 'failure': 'tearDown Failed!'}]}]) + self._run_test( + flag='--tear_down_fail', + num_errors=0, + num_failures=1, + suites=[{'name': 'FailableTest', + 'cases': [{'name': 'test', + 'classname': '__main__.FailableTest', + 'failure': 'tearDown Failed!'}]}]) def test_test_fail(self): self._run_test( diff --git a/absl/tests/app_test.py b/absl/tests/app_test.py index 20f0725..1d8b764 100644 --- a/absl/tests/app_test.py +++ b/absl/tests/app_test.py @@ -14,20 +14,16 @@ """Tests for app.py.""" -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import codecs import contextlib import copy import enum +import io import os import re import subprocess import sys import tempfile -import unittest +from unittest import mock from absl import app from absl import flags @@ -35,14 +31,10 @@ from absl.testing import _bazelize_command from absl.testing import absltest from absl.testing import flagsaver from absl.tests import app_test_helper -import mock -import six FLAGS = flags.FLAGS -# six.StringIO best reflects the normal behavior of stdout for both py2 and 3. -mock_stdio_type = six.StringIO _newline_regex = re.compile('(\r\n)|\r') @@ -67,7 +59,7 @@ class UnitTests(absltest.TestCase): def test_usage(self): with mock.patch.object( - sys, 'stderr', new=mock_stdio_type()) as mock_stderr: + sys, 'stderr', new=io.StringIO()) as mock_stderr: app.usage() self.assertIn(__doc__, mock_stderr.getvalue()) # Assert that flags are written to stderr. @@ -75,34 +67,25 @@ class UnitTests(absltest.TestCase): def test_usage_shorthelp(self): with mock.patch.object( - sys, 'stderr', new=mock_stdio_type()) as mock_stderr: + sys, 'stderr', new=io.StringIO()) as mock_stderr: app.usage(shorthelp=True) # Assert that flags are NOT written to stderr. self.assertNotIn(' --', mock_stderr.getvalue()) def test_usage_writeto_stderr(self): with mock.patch.object( - sys, 'stdout', new=mock_stdio_type()) as mock_stdout: + sys, 'stdout', new=io.StringIO()) as mock_stdout: app.usage(writeto_stdout=True) self.assertIn(__doc__, mock_stdout.getvalue()) def test_usage_detailed_error(self): with mock.patch.object( - sys, 'stderr', new=mock_stdio_type()) as mock_stderr: + sys, 'stderr', new=io.StringIO()) as mock_stderr: app.usage(detailed_error='BAZBAZ') self.assertIn('BAZBAZ', mock_stderr.getvalue()) def test_usage_exitcode(self): - - # The test environment may not have the correct output encoding, - # and we can't really change it once we've started the test, - # so we have to replace it with one that understands unicode. - if six.PY2: - stderr = codecs.getwriter('utf8')(sys.stderr) - else: - stderr = sys.stderr - - with mock.patch.object(sys, 'stderr', new=stderr): + with mock.patch.object(sys, 'stderr', new=sys.stderr): try: app.usage(exitcode=2) self.fail('app.usage(exitcode=1) should raise SystemExit') @@ -112,7 +95,7 @@ class UnitTests(absltest.TestCase): def test_usage_expands_docstring(self): with patch_main_module_docstring('Name: %s, %%s'): with mock.patch.object( - sys, 'stderr', new=mock_stdio_type()) as mock_stderr: + sys, 'stderr', new=io.StringIO()) as mock_stderr: app.usage() self.assertIn('Name: {}, %s'.format(sys.argv[0]), mock_stderr.getvalue()) @@ -120,7 +103,7 @@ class UnitTests(absltest.TestCase): def test_usage_does_not_expand_bad_docstring(self): with patch_main_module_docstring('Name: %s, %%s, %@'): with mock.patch.object( - sys, 'stderr', new=mock_stdio_type()) as mock_stderr: + sys, 'stderr', new=io.StringIO()) as mock_stderr: app.usage() self.assertIn('Name: %s, %%s, %@', mock_stderr.getvalue()) @@ -210,13 +193,7 @@ class FunctionalTests(absltest.TestCase): self.assertIn(u'smile:\U0001F604', stdout) - if six.PY2: - # Default values get repr'd, which causes unicode strings to incorrectly - # render with their escaped values. - self.assertIn(repr(u'thumb:\U0001F44D'), stdout) - else: - # In Python 3, the repr() of a unicode string isn't escaped. - self.assertIn(u'thumb:\U0001F44D', stdout) + self.assertIn(u'thumb:\U0001F44D', stdout) def test_helpshort(self): _, _, stderr = self.run_helper( @@ -253,8 +230,6 @@ class FunctionalTests(absltest.TestCase): with open(os.path.join(tmpdir, 'STATUS')) as status_file: self.assertIn('MyException:', status_file.read()) - @unittest.skipIf(six.PY2, - 'By default, faulthandler is only available in Python 3.') def test_faulthandler_dumps_stack_on_sigsegv(self): return_code, _, _ = self.run_helper( False, |