From 8dc737556341caeba0a09f15e6c0737a5724bd66 Mon Sep 17 00:00:00 2001 From: Yilei Yang Date: Tue, 26 Oct 2021 13:36:40 -0700 Subject: [PATCH 1/2] Remove the unittest3_backport code now that we have dropped Python 2 support. Also removed a few `six.PY2` protected methods in absltest since the linter recognizes the super class and reports the use of deprecated methods errors. PiperOrigin-RevId: 405723651 Change-Id: I60835dd7b30695c7c35613080621a0cbdebe890f --- absl/testing/BUILD | 6 - absl/testing/_pretty_print_reporter.py | 3 +- absl/testing/absltest.py | 26 +- absl/testing/tests/xml_reporter_test.py | 30 +- absl/testing/xml_reporter.py | 9 +- absl/third_party/__init__.py | 0 absl/third_party/unittest3_backport/BUILD | 46 --- absl/third_party/unittest3_backport/LICENSE | 255 ---------------- .../unittest3_backport/__init__.py | 8 - absl/third_party/unittest3_backport/case.py | 273 ------------------ absl/third_party/unittest3_backport/result.py | 25 -- .../tests/unittest3_backport_test.py | 193 ------------- 12 files changed, 14 insertions(+), 860 deletions(-) delete mode 100644 absl/third_party/__init__.py delete mode 100644 absl/third_party/unittest3_backport/BUILD delete mode 100644 absl/third_party/unittest3_backport/LICENSE delete mode 100644 absl/third_party/unittest3_backport/__init__.py delete mode 100644 absl/third_party/unittest3_backport/case.py delete mode 100644 absl/third_party/unittest3_backport/result.py delete mode 100644 absl/third_party/unittest3_backport/tests/unittest3_backport_test.py diff --git a/absl/testing/BUILD b/absl/testing/BUILD index 4ed9126c..cfc06900 100644 --- a/absl/testing/BUILD +++ b/absl/testing/BUILD @@ -33,7 +33,6 @@ py_library( "//absl:app", "//absl/flags", "//absl/logging", - "//absl/third_party/unittest3_backport", "@six_archive//:six", ], ) @@ -72,7 +71,6 @@ py_library( visibility = ["//visibility:public"], deps = [ ":_pretty_print_reporter", - "//absl/third_party/unittest3_backport", "@six_archive//:six", ], ) @@ -92,9 +90,6 @@ py_library( name = "_pretty_print_reporter", srcs = ["_pretty_print_reporter.py"], srcs_version = "PY2AND3", - deps = [ - "//absl/third_party/unittest3_backport", - ], ) py_library( @@ -275,7 +270,6 @@ py_test( ":parameterized", ":xml_reporter", "//absl/logging", - "//absl/third_party/unittest3_backport", "@mock_archive//:mock", "@six_archive//:six", ], diff --git a/absl/testing/_pretty_print_reporter.py b/absl/testing/_pretty_print_reporter.py index 913e509a..ef039340 100644 --- a/absl/testing/_pretty_print_reporter.py +++ b/absl/testing/_pretty_print_reporter.py @@ -19,10 +19,9 @@ from __future__ import print_function import unittest -from absl.third_party import unittest3_backport -class TextTestResult(unittest3_backport.TextTestResult): +class TextTestResult(unittest.TextTestResult): """TestResult class that provides the default text result formatting.""" def __init__(self, stream, descriptions, verbosity): diff --git a/absl/testing/absltest.py b/absl/testing/absltest.py index 39fa1c95..47796635 100644 --- a/absl/testing/absltest.py +++ b/absl/testing/absltest.py @@ -60,7 +60,6 @@ from absl._collections_abc import abc from absl.testing import _pretty_print_reporter from absl.testing import xml_reporter -from absl.third_party import unittest3_backport import six from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin @@ -81,11 +80,8 @@ # Unbounded TypeVar for general usage _T = typing.TypeVar('_T') - if six.PY2: - _OutcomeType = unittest3_backport.case._Outcome - else: - import unittest.case - _OutcomeType = unittest.case._Outcome # pytype: disable=module-attr + import unittest.case + _OutcomeType = unittest.case._Outcome # pytype: disable=module-attr if six.PY3: @@ -593,7 +589,7 @@ def __get__(self, obj, type_): return func.__get__(obj, type_) # pytype: disable=attribute-error -class TestCase(unittest3_backport.TestCase): +class TestCase(unittest.TestCase): """Extension of unittest.TestCase providing more power.""" # When to cleanup files/directories created by our `create_tempfile()` and @@ -1198,18 +1194,6 @@ def assertBetween(self, value, minv, maxv, msg=None): self.assertTrue(minv <= value, msg) self.assertTrue(maxv >= value, msg) - # Backport these names so that Py2 code can be written in Py3 style. - if six.PY2: - - def assertRegex(self, *args, **kwargs): - return self.assertRegexpMatches(*args, **kwargs) - - def assertRaisesRegex(self, *args, **kwargs): - return self.assertRaisesRegexp(*args, **kwargs) - - def assertNotRegex(self, *args, **kwargs): - return self.assertNotRegexpMatches(*args, **kwargs) - def assertRegexMatch(self, actual_str, regexes, message=None): r"""Asserts that at least one regex in regexes matches str. @@ -1625,7 +1609,7 @@ def CheckEqual(a, b): '%r unexpectedly less than %r' % (b, a))) self.assertLessEqual(a, b, msg) - self.assertLessEqual(b, a, msg) + self.assertLessEqual(b, a, msg) # pylint: disable=arguments-out-of-order self.assertFalse(a > b, self._formatMessage(msg, '%r unexpectedly greater than %r' % @@ -1635,7 +1619,7 @@ def CheckEqual(a, b): '%r unexpectedly greater than %r' % (b, a))) self.assertGreaterEqual(a, b, msg) - self.assertGreaterEqual(b, a, msg) + self.assertGreaterEqual(b, a, msg) # pylint: disable=arguments-out-of-order msg = kwargs.get('msg') diff --git a/absl/testing/tests/xml_reporter_test.py b/absl/testing/tests/xml_reporter_test.py index 2220e993..1b669240 100644 --- a/absl/testing/tests/xml_reporter_test.py +++ b/absl/testing/tests/xml_reporter_test.py @@ -33,7 +33,6 @@ from absl.testing import absltest from absl.testing import parameterized from absl.testing import xml_reporter -from absl.third_party import unittest3_backport import mock import six @@ -198,10 +197,7 @@ def test_with_passing_subtest(self): result = self._make_result((start_time, start_time, end_time, end_time)) test = MockTest('__main__.MockTest.passing_test') - if six.PY3: - subtest = unittest.case._SubTest(test, 'msg', None) - else: - subtest = unittest3_backport.case._SubTest(test, 'msg', None) + subtest = unittest.case._SubTest(test, 'msg', None) result.startTestRun() result.startTest(test) result.addSubTest(test, subtest, None) @@ -231,15 +227,7 @@ def test_with_passing_subtest_with_dots_in_parameter_name(self): result = self._make_result((start_time, start_time, end_time, end_time)) test = MockTest('__main__.MockTest.passing_test') - if six.PY3: - subtest = unittest.case._SubTest(test, 'msg', {'case': 'a.b.c'}) - else: - # In Python 3 subTest uses a ChainMap to hold the parameters, but ChainMap - # does not exist in Python 2, so a list of dict is used to simulate the - # behavior of a ChainMap. This is why a list is provided as a parameter - # here. - subtest = unittest3_backport.case._SubTest(test, 'msg', - [{'case': 'a.b.c'}]) + subtest = unittest.case._SubTest(test, 'msg', {'case': 'a.b.c'}) result.startTestRun() result.startTest(test) result.addSubTest(test, subtest, None) @@ -346,10 +334,7 @@ def test_with_failing_subtest(self): result = self._make_result((start_time, start_time, end_time, end_time)) test = MockTest('__main__.MockTest.failing_test') - if six.PY3: - subtest = unittest.case._SubTest(test, 'msg', None) - else: - subtest = unittest3_backport.case._SubTest(test, 'msg', None) + subtest = unittest.case._SubTest(test, 'msg', None) result.startTestRun() result.startTest(test) result.addSubTest(test, subtest, self.get_sample_failure()) @@ -412,10 +397,7 @@ def test_with_error_subtest(self): result = self._make_result((start_time, start_time, end_time, end_time)) test = MockTest('__main__.MockTest.error_test') - if six.PY3: - subtest = unittest.case._SubTest(test, 'msg', None) - else: - subtest = unittest3_backport.case._SubTest(test, 'msg', None) + subtest = unittest.case._SubTest(test, 'msg', None) result.startTestRun() result.startTest(test) result.addSubTest(test, subtest, self.get_sample_error()) @@ -900,10 +882,10 @@ def test_add_failure_during_stop_test(self): result.startTestRun() result.startTest(test) - # Replace parent stopTest method from unittest3_backport.TextTestResult with + # Replace parent stopTest method from unittest.TextTestResult with # a version that calls self.addFailure(). with mock.patch.object( - unittest3_backport.TextTestResult, + unittest.TextTestResult, 'stopTest', side_effect=lambda t: result.addFailure(t, self.get_sample_failure())): # Run stopTest in a separate thread since we are looking to verify that diff --git a/absl/testing/xml_reporter.py b/absl/testing/xml_reporter.py index 5cdbbf4f..754e6d40 100644 --- a/absl/testing/xml_reporter.py +++ b/absl/testing/xml_reporter.py @@ -27,7 +27,6 @@ import unittest from xml.sax import saxutils from absl.testing import _pretty_print_reporter -from absl.third_party import unittest3_backport import six @@ -166,8 +165,7 @@ def __init__(self, test): full_class_name = match.group(2) else: class_name = unittest.util.strclass(test.__class__) - if ((six.PY3 and isinstance(test, unittest.case._SubTest)) or - (six.PY2 and isinstance(test, unittest3_backport.case._SubTest))): + if isinstance(test, unittest.case._SubTest): # If the test case is a _SubTest, the real TestCase instance is # available as _SubTest.test_case. class_name = unittest.util.strclass(test.test_case.__class__) @@ -249,10 +247,7 @@ def add_test_case_result(self, test_case_result): # _ErrorHolder is a special case created by unittest for class / module # level functions. suite_name = test_case_result.full_class_name.rsplit('.')[-1] - if ((six.PY3 and - isinstance(test_case_result.test, unittest.case._SubTest)) or - (six.PY2 and - isinstance(test_case_result.test, unittest3_backport.case._SubTest))): + if isinstance(test_case_result.test, unittest.case._SubTest): # If the test case is a _SubTest, the real TestCase instance is # available as _SubTest.test_case. suite_name = type(test_case_result.test.test_case).__name__ diff --git a/absl/third_party/__init__.py b/absl/third_party/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/absl/third_party/unittest3_backport/BUILD b/absl/third_party/unittest3_backport/BUILD deleted file mode 100644 index 1d29df98..00000000 --- a/absl/third_party/unittest3_backport/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -licenses(["notice"]) # New BSD, Python Software Foundation - -exports_files(["LICENSE"]) - -py_library( - name = "unittest3_backport", - srcs = ["__init__.py"], - srcs_version = "PY2AND3", - visibility = ["//absl/testing:__pkg__"], - deps = [ - ":case", - ":result", - ], -) - -py_library( - name = "case", - srcs = ["case.py"], - srcs_version = "PY2AND3", - deps = [ - "@six_archive//:six", - ], -) - -py_library( - name = "result", - srcs = ["result.py"], - srcs_version = "PY2AND3", - deps = [ - "@six_archive//:six", - ], -) - -py_test( - name = "tests/unittest3_backport_test", - size = "small", - srcs = ["tests/unittest3_backport_test.py"], - python_version = "PY3", - srcs_version = "PY3", - deps = [ - "//absl/testing:absltest", - "//absl/testing:xml_reporter", - "@mock_archive//:mock", - "@six_archive//:six", - ], -) diff --git a/absl/third_party/unittest3_backport/LICENSE b/absl/third_party/unittest3_backport/LICENSE deleted file mode 100644 index 5e14120d..00000000 --- a/absl/third_party/unittest3_backport/LICENSE +++ /dev/null @@ -1,255 +0,0 @@ -A. HISTORY OF THE SOFTWARE -========================== - -Python was created in the early 1990s by Guido van Rossum at Stichting -Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands -as a successor of a language called ABC. Guido remains Python's -principal author, although it includes many contributions from others. - -In 1995, Guido continued his work on Python at the Corporation for -National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) -in Reston, Virginia where he released several versions of the -software. - -In May 2000, Guido and the Python core development team moved to -BeOpen.com to form the BeOpen PythonLabs team. In October of the same -year, the PythonLabs team moved to Digital Creations (now Zope -Corporation, see http://www.zope.com). In 2001, the Python Software -Foundation (PSF, see http://www.python.org/psf/) was formed, a -non-profit organization created specifically to own Python-related -Intellectual Property. Zope Corporation is a sponsoring member of -the PSF. - -All Python releases are Open Source (see http://www.opensource.org for -the Open Source Definition). Historically, most, but not all, Python -releases have also been GPL-compatible; the table below summarizes -the various releases. - - Release Derived Year Owner GPL- - from compatible? (1) - - 0.9.0 thru 1.2 1991-1995 CWI yes - 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes - 1.6 1.5.2 2000 CNRI no - 2.0 1.6 2000 BeOpen.com no - 1.6.1 1.6 2001 CNRI yes (2) - 2.1 2.0+1.6.1 2001 PSF no - 2.0.1 2.0+1.6.1 2001 PSF yes - 2.1.1 2.1+2.0.1 2001 PSF yes - 2.1.2 2.1.1 2002 PSF yes - 2.1.3 2.1.2 2002 PSF yes - 2.2 and above 2.1.1 2001-now PSF yes - -Footnotes: - -(1) GPL-compatible doesn't mean that we're distributing Python under - the GPL. All Python licenses, unlike the GPL, let you distribute - a modified version without making your changes open source. The - GPL-compatible licenses make it possible to combine Python with - other software that is released under the GPL; the others don't. - -(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, - because its license has a choice of law clause. According to - CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 - is "not incompatible" with the GPL. - -Thanks to the many outside volunteers who have worked under Guido's -direction to make these releases possible. - - -B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON -=============================================================== - -PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 --------------------------------------------- - -1. This LICENSE AGREEMENT is between the Python Software Foundation -("PSF"), and the Individual or Organization ("Licensee") accessing and -otherwise using this software ("Python") in source or binary form and -its associated documentation. - -2. Subject to the terms and conditions of this License Agreement, PSF hereby -grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, -analyze, test, perform and/or display publicly, prepare derivative works, -distribute, and otherwise use Python alone or in any derivative version, -provided, however, that PSF's License Agreement and PSF's notice of copyright, -i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, -2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation; All Rights -Reserved" are retained in Python alone or in any derivative version prepared by -Licensee. - -3. In the event Licensee prepares a derivative work that is based on -or incorporates Python or any part thereof, and wants to make -the derivative work available to others as provided herein, then -Licensee hereby agrees to include in any such work a brief summary of -the changes made to Python. - -4. PSF is making Python available to Licensee on an "AS IS" -basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR -IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND -DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS -FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT -INFRINGE ANY THIRD PARTY RIGHTS. - -5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON -FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS -A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, -OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. - -6. This License Agreement will automatically terminate upon a material -breach of its terms and conditions. - -7. Nothing in this License Agreement shall be deemed to create any -relationship of agency, partnership, or joint venture between PSF and -Licensee. This License Agreement does not grant permission to use PSF -trademarks or trade name in a trademark sense to endorse or promote -products or services of Licensee, or any third party. - -8. By copying, installing or otherwise using Python, Licensee -agrees to be bound by the terms and conditions of this License -Agreement. - - -BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 -------------------------------------------- - -BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 - -1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an -office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the -Individual or Organization ("Licensee") accessing and otherwise using -this software in source or binary form and its associated -documentation ("the Software"). - -2. Subject to the terms and conditions of this BeOpen Python License -Agreement, BeOpen hereby grants Licensee a non-exclusive, -royalty-free, world-wide license to reproduce, analyze, test, perform -and/or display publicly, prepare derivative works, distribute, and -otherwise use the Software alone or in any derivative version, -provided, however, that the BeOpen Python License is retained in the -Software, alone or in any derivative version prepared by Licensee. - -3. BeOpen is making the Software available to Licensee on an "AS IS" -basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR -IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND -DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS -FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT -INFRINGE ANY THIRD PARTY RIGHTS. - -4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE -SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS -AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY -DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. - -5. This License Agreement will automatically terminate upon a material -breach of its terms and conditions. - -6. This License Agreement shall be governed by and interpreted in all -respects by the law of the State of California, excluding conflict of -law provisions. Nothing in this License Agreement shall be deemed to -create any relationship of agency, partnership, or joint venture -between BeOpen and Licensee. This License Agreement does not grant -permission to use BeOpen trademarks or trade names in a trademark -sense to endorse or promote products or services of Licensee, or any -third party. As an exception, the "BeOpen Python" logos available at -http://www.pythonlabs.com/logos.html may be used according to the -permissions granted on that web page. - -7. By copying, installing or otherwise using the software, Licensee -agrees to be bound by the terms and conditions of this License -Agreement. - - -CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 ---------------------------------------- - -1. This LICENSE AGREEMENT is between the Corporation for National -Research Initiatives, having an office at 1895 Preston White Drive, -Reston, VA 20191 ("CNRI"), and the Individual or Organization -("Licensee") accessing and otherwise using Python 1.6.1 software in -source or binary form and its associated documentation. - -2. Subject to the terms and conditions of this License Agreement, CNRI -hereby grants Licensee a nonexclusive, royalty-free, world-wide -license to reproduce, analyze, test, perform and/or display publicly, -prepare derivative works, distribute, and otherwise use Python 1.6.1 -alone or in any derivative version, provided, however, that CNRI's -License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) -1995-2001 Corporation for National Research Initiatives; All Rights -Reserved" are retained in Python 1.6.1 alone or in any derivative -version prepared by Licensee. Alternately, in lieu of CNRI's License -Agreement, Licensee may substitute the following text (omitting the -quotes): "Python 1.6.1 is made available subject to the terms and -conditions in CNRI's License Agreement. This Agreement together with -Python 1.6.1 may be located on the Internet using the following -unique, persistent identifier (known as a handle): 1895.22/1013. This -Agreement may also be obtained from a proxy server on the Internet -using the following URL: http://hdl.handle.net/1895.22/1013". - -3. In the event Licensee prepares a derivative work that is based on -or incorporates Python 1.6.1 or any part thereof, and wants to make -the derivative work available to others as provided herein, then -Licensee hereby agrees to include in any such work a brief summary of -the changes made to Python 1.6.1. - -4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" -basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR -IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND -DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS -FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT -INFRINGE ANY THIRD PARTY RIGHTS. - -5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON -1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS -A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, -OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. - -6. This License Agreement will automatically terminate upon a material -breach of its terms and conditions. - -7. This License Agreement shall be governed by the federal -intellectual property law of the United States, including without -limitation the federal copyright law, and, to the extent such -U.S. federal law does not apply, by the law of the Commonwealth of -Virginia, excluding Virginia's conflict of law provisions. -Notwithstanding the foregoing, with regard to derivative works based -on Python 1.6.1 that incorporate non-separable material that was -previously distributed under the GNU General Public License (GPL), the -law of the Commonwealth of Virginia shall govern this License -Agreement only as to issues arising under or with respect to -Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this -License Agreement shall be deemed to create any relationship of -agency, partnership, or joint venture between CNRI and Licensee. This -License Agreement does not grant permission to use CNRI trademarks or -trade name in a trademark sense to endorse or promote products or -services of Licensee, or any third party. - -8. By clicking on the "ACCEPT" button where indicated, or by copying, -installing or otherwise using Python 1.6.1, Licensee agrees to be -bound by the terms and conditions of this License Agreement. - - ACCEPT - - -CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 --------------------------------------------------- - -Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, -The Netherlands. All rights reserved. - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in -supporting documentation, and that the name of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior -permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE -FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/absl/third_party/unittest3_backport/__init__.py b/absl/third_party/unittest3_backport/__init__.py deleted file mode 100644 index e54b41ac..00000000 --- a/absl/third_party/unittest3_backport/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Backport Python3 subTest to absl.TestCase when running Python 2.7.""" - -from __future__ import absolute_import - -__all__ = ('TextTestResult', 'TestCase') - -from .case import TestCase -from .result import TextTestResult diff --git a/absl/third_party/unittest3_backport/case.py b/absl/third_party/unittest3_backport/case.py deleted file mode 100644 index 5029f7b5..00000000 --- a/absl/third_party/unittest3_backport/case.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Backport Python3 unittest.TestCase to absl when running Python 2.7.""" - -from __future__ import absolute_import - -import contextlib -import sys -import unittest -import warnings - -import six - -# pylint: disable=invalid-name - -if six.PY2: - _subtest_msg_sentinel = object() - - class _ShouldStop(Exception): - """The test should stop.""" - - class _Outcome(object): - - def __init__(self, result=None): - self.expecting_failure = False - self.result = result - self.result_supports_subtests = hasattr(result, 'addSubTest') - self.success = True - self.skipped = [] - self.expectedFailure = None - self.errors = [] - self.errors_setup_and_teardown = [] - - @contextlib.contextmanager - def testPartExecutor(self, test_case, is_setup_or_teardown=False): - old_success = self.success - self.success = True - try: - yield - except KeyboardInterrupt: - raise - except unittest.SkipTest as e: - self.success = False - self.skipped.append((test_case, str(e))) - except _ShouldStop: - pass - except unittest.case._ExpectedFailure as e: - self.success = False - self.expecting_failure = True - self.expectedFailure = e.exc_info - except unittest.case._UnexpectedSuccess: - self.expecting_failure = True - # We need to catch everything here, including SystemExit. - # KeyboardInterrupt was passed through above. - except: # pylint: disable=bare-except - self.success = False - if is_setup_or_teardown: - self.errors_setup_and_teardown.append((test_case, sys.exc_info())) - else: - self.errors.append((test_case, sys.exc_info())) - else: - if self.result_supports_subtests and self.success: - self.errors.append((test_case, None)) - finally: - self.success = self.success and old_success - - -class TestCase(unittest.TestCase): - - if six.PY2: - - def __init__(self, methodName='runTest'): - super(TestCase, self).__init__(methodName) - self._subtest = None - self._outcome = None - - def _addSkip(self, result, reason, test_case=None): - addSkip = getattr(result, 'addSkip', None) - if addSkip is not None: - if test_case: - addSkip(test_case, reason) - else: - addSkip(self, reason) - else: - warnings.warn('TestResult has no addSkip method, skips not reported', - RuntimeWarning, 2) - if test_case: - result.addSuccess(test_case) - else: - result.addSuccess(self) - - def _feedErrorsToResult(self, result, errors, setup_or_teardown=False): - if setup_or_teardown: - # Both failures and errors happen in setup or teardown phase are - # regarded as errors in Python 2. - for test, exc_info in errors: - result.addError(test, exc_info) - else: - for test, exc_info in errors: - if isinstance(test, _SubTest): - result.addSubTest(test.test_case, test, exc_info) - elif exc_info is not None: - if issubclass(exc_info[0], self.failureException): - result.addFailure(test, exc_info) - else: - result.addError(test, exc_info) - - def _addExpectedFailure(self, result, exc_info): - try: - addExpectedFailure = result.addExpectedFailure - except AttributeError: - warnings.warn(('TestResult has no addExpectedFailure method, ' - 'reporting as passes'), RuntimeWarning) - result.addSuccess(self) - else: - addExpectedFailure(self, exc_info) - - def _addUnexpectedSuccess(self, result): - try: - addUnexpectedSuccess = result.addUnexpectedSuccess - except AttributeError: - warnings.warn(('TestResult has no addUnexpectedSuccess method, ' - 'reporting as failure'), RuntimeWarning) - # We need to pass an actual exception and traceback to addFailure, - # otherwise the legacy result can choke. - try: - raise unittest.case._UnexpectedSuccess - except unittest.case._UnexpectedSuccess: - result.addFailure(self, sys.exc_info()) - else: - addUnexpectedSuccess(self) - - def run(self, result=None): - orig_result = result - if result is None: - result = self.defaultTestResult() - startTestRun = getattr(result, 'startTestRun', None) - if startTestRun is not None: - startTestRun() - - self._resultForDoCleanups = result - result.startTest(self) - - testMethod = getattr(self, self._testMethodName) - if (getattr(self.__class__, '__unittest_skip__', False) or - getattr(testMethod, '__unittest_skip__', False)): - # If the class or method was skipped. - try: - skip_why = (getattr(self.__class__, '__unittest_skip_why__', '') - or getattr(testMethod, '__unittest_skip_why__', '')) - self._addSkip(result, skip_why, self) - finally: - result.stopTest(self) - return - outcome = _Outcome(result) - expecting_failure = False - try: - self._outcome = outcome - - with outcome.testPartExecutor(self, is_setup_or_teardown=True): - self.setUp() - if outcome.success: - with outcome.testPartExecutor(self): - testMethod() - expecting_failure = outcome.expecting_failure - outcome.expecting_failure = False - # The logic here is a little different from the implementation in - # Python3. - # In Python3, if a testcase is expecting failure, even if it - # fails, outcome.success is True. This implementation does not work - # for Python2. In Python2, if a subtest fails, it does not know - # whether its parent test is expecting failure, and will set - # outcome.success to False. Now the logic is that no matter whether a - # testcase is expecting failure, if it fails, outcome.success is False - if expecting_failure: - if outcome.success: - self._addUnexpectedSuccess(result) - else: - self._addExpectedFailure(result, outcome.expectedFailure) - - with outcome.testPartExecutor(self, is_setup_or_teardown=True): - self.tearDown() - for test, reason in outcome.skipped: - self._addSkip(result, reason, test) - self._feedErrorsToResult(result, outcome.errors_setup_and_teardown, - setup_or_teardown=True) - self._feedErrorsToResult(result, outcome.errors) - - self.doCleanups() - if not expecting_failure and outcome.success: - result.addSuccess(self) - return result - finally: - result.stopTest(self) - if orig_result is None: - stopTestRun = getattr(result, 'stopTestRun', None) - if stopTestRun is not None: - stopTestRun() # pylint: disable=not-callable - - # explicitly break reference cycles: - # outcome.errors -> frame -> outcome -> outcome.errors - # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure - outcome.errors = [] - outcome.expectedFailure = None - - # clear the outcome, no more needed - self._outcome = None - - @contextlib.contextmanager - def subTest(self, msg=_subtest_msg_sentinel, **params): - """Return a context manager that will run the enclosed subtest.""" - - if not self._outcome.result_supports_subtests: - yield - return - parent = self._subtest - - # use a list to simulate the behavior of a ChainMap - if parent is None: - params_map = [params] - else: - params_map = list(parent.params) - params_map.append(params) - self._subtest = _SubTest(self, msg, params_map) - try: - with self._outcome.testPartExecutor(self._subtest): - yield - if not self._outcome.success: - result = self._outcome.result - if result is not None and result.failfast: - raise _ShouldStop - elif self._outcome.expectedFailure: - # If the test is expecting a failure, we really want to - # stop now and register the expected failure. - raise _ShouldStop - finally: - self._subtest = parent - - -if six.PY2: - class _SubTest(TestCase): - - def __init__(self, test_case, message, params): - super(_SubTest, self).__init__() - self._message = message - self.test_case = test_case - self.params = params - self.failureException = test_case.failureException - - def runTest(self): - raise NotImplementedError('subtests cannot be run directly') - - def _subDescription(self): - parts = [] - if self._message is not _subtest_msg_sentinel: - parts.append('[{}]'.format(self._message)) - if self.params: - params_merged = {} - for dictionary in self.params: - params_merged.update(dictionary) - params_desc = ', '.join( - '{}={!r}'.format(k, v) - for (k, v) in sorted(params_merged.items())) - parts.append('({})'.format(params_desc)) - return ' '.join(parts) or '()' - - def id(self): - return '{} {}'.format(self.test_case.id(), self._subDescription()) - - def shortDescription(self): - """Returns a one-line description of the subtest.""" - return self.test_case.shortDescription() - - def __str__(self): - return '{} {}'.format(self.test_case, self._subDescription()) diff --git a/absl/third_party/unittest3_backport/result.py b/absl/third_party/unittest3_backport/result.py deleted file mode 100644 index 7500bef5..00000000 --- a/absl/third_party/unittest3_backport/result.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Backport Python3 unittest.TextTestResult to absl when running Python 2.7.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import unittest - -import six - - -class TextTestResult(unittest.TextTestResult): - - if six.PY2: - - def addSubTest(self, test, subtest, err): # pylint: disable=invalid-name - if err is not None: - if getattr(self, 'failfast', False): - self.stop() - subtest_error_details = (subtest, self._exc_info_to_string(err, test)) - if issubclass(err[0], test.failureException): - self.failures.append(subtest_error_details) - else: - self.errors.append(subtest_error_details) - self._mirrorOutput = True diff --git a/absl/third_party/unittest3_backport/tests/unittest3_backport_test.py b/absl/third_party/unittest3_backport/tests/unittest3_backport_test.py deleted file mode 100644 index b18d4cb3..00000000 --- a/absl/third_party/unittest3_backport/tests/unittest3_backport_test.py +++ /dev/null @@ -1,193 +0,0 @@ -"""Tests for absl.third_party.unittest3_backport.""" - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import unittest - -from absl.testing import absltest -from absl.testing import xml_reporter -import mock -import six - - -class MockTestResult(xml_reporter._TextAndXMLTestResult): - - def __init__(self): - super(MockTestResult, self).__init__(six.StringIO(), six.StringIO(), - 'description', False) - self.subtest_success = [] - self.subtest_failure = [] - - def addSubTest(self, test, subtest, err): # pylint: disable=invalid-name - super(MockTestResult, self).addSubTest(test, subtest, err) - - if six.PY2: - params = {} - for param in subtest.params: - for param_name, param_value in param.items(): - params[param_name] = param_value - else: - params = dict(subtest.params) - if err is not None: - self.addSubTestFailure(params) - else: - self.addSubTestSuccess(params) - - def addSubTestFailure(self, params): # pylint: disable=invalid-name - self.subtest_failure.append(params) - - def addSubTestSuccess(self, params): # pylint: disable=invalid-name - self.subtest_success.append(params) - - -class MockTestResultWithoutSubTest(xml_reporter._TextAndXMLTestResult): - # hasattr(MockTestResultWithoutSubTest, addSubTest) return False - - def __init__(self): - super(MockTestResultWithoutSubTest, self).__init__(six.StringIO(), - six.StringIO(), - 'description', - False) - - @property - def addSubTest(self): # pylint: disable=invalid-name - raise AttributeError - - -class Unittest3BackportTest(absltest.TestCase): - - def test_subtest_pass(self): - - class Foo(absltest.TestCase): - - def runTest(self): - for i in [1, 2]: - with self.subTest(i=i): - for j in [2, 3]: - with self.subTest(j=j): - pass - - result = MockTestResult() - Foo().run(result) - expected_success = [{'i': 1, 'j': 2}, {'i': 1, 'j': 3}, {'i': 1}, - {'i': 2, 'j': 2}, {'i': 2, 'j': 3}, {'i': 2}] - self.assertListEqual(result.subtest_success, expected_success) - - def test_subtest_fail(self): - class Foo(absltest.TestCase): - - def runTest(self): - for i in [1, 2]: - with self.subTest(i=i): - for j in [2, 3]: - with self.subTest(j=j): - if j == 2: - self.fail('failure') - - result = MockTestResult() - Foo().run(result) - - # The first layer subtest result is only added to the output when it is a - # success - expected_success = [{'i': 1, 'j': 3}, {'i': 2, 'j': 3}] - expected_failure = [{'i': 1, 'j': 2}, {'i': 2, 'j': 2}] - self.assertListEqual(expected_success, result.subtest_success) - self.assertListEqual(expected_failure, result.subtest_failure) - - def test_subtest_expected_failure(self): - class Foo(absltest.TestCase): - - @unittest.expectedFailure - def runTest(self): - for i in [1, 2, 3]: - with self.subTest(i=i): - self.assertEqual(i, 2) - - foo = Foo() - with mock.patch.object(foo, '_addExpectedFailure', - autospec=True) as mock_subtest_expected_failure: - result = MockTestResult() - foo.run(result) - self.assertEqual(mock_subtest_expected_failure.call_count, 1) - - def test_subtest_unexpected_success(self): - class Foo(absltest.TestCase): - - @unittest.expectedFailure - def runTest(self): - for i in [1, 2, 3]: - with self.subTest(i=i): - self.assertEqual(i, i) - - foo = Foo() - with mock.patch.object(foo, '_addUnexpectedSuccess', - autospec=True) as mock_subtest_unexpected_success: - result = MockTestResult() - foo.run(result) - self.assertEqual(mock_subtest_unexpected_success.call_count, 1) - - def test_subtest_fail_fast(self): - # Ensure failfast works with subtest - - class Foo(absltest.TestCase): - - def runTest(self): - with self.subTest(i=1): - self.fail('failure') - with self.subTest(i=2): - self.fail('failure') - self.fail('failure') - - result = MockTestResult() - result.failfast = True - Foo().run(result) - expected_failure = [{'i': 1}] - self.assertListEqual(expected_failure, result.subtest_failure) - - def test_subtest_skip(self): - # When a test case is skipped, addSubTest should not be called - - class Foo(absltest.TestCase): - - @unittest.skip('no reason') - def runTest(self): - for i in [1, 2, 3]: - with self.subTest(i=i): - self.assertEqual(i, i) - - foo = Foo() - result = MockTestResult() - - with mock.patch.object(foo, '_addSkip', autospec=True) as mock_test_skip: - with mock.patch.object(result, 'addSubTestSuccess', - autospec=True) as mock_subtest_success: - foo.run(result) - self.assertEqual(mock_test_skip.call_count, 1) - self.assertEqual(mock_subtest_success.call_count, 0) - - @mock.patch.object(MockTestResultWithoutSubTest, 'addFailure', autospec=True) - def test_subtest_legacy(self, mock_test_fail): - # When the result object does not have addSubTest method, - # text execution stops after the first subtest failure. - - class Foo(absltest.TestCase): - - def runTest(self): - for i in [1, 2, 3]: - with self.subTest(i=i): - if i == 1: - self.fail('failure') - for j in [2, 3]: - with self.subTest(j=j): - if i * j == 6: - raise RuntimeError('raised by Foo.test') - - result = MockTestResultWithoutSubTest() - - Foo().run(result) - self.assertEqual(mock_test_fail.call_count, 1) - -if __name__ == '__main__': - absltest.main() From e17cfb5682589257364f9e6d1d54019ce5626f46 Mon Sep 17 00:00:00 2001 From: Yilei Yang Date: Tue, 26 Oct 2021 14:41:13 -0700 Subject: [PATCH 2/2] Remove unused _absl_test_platform_deps. PiperOrigin-RevId: 405738888 Change-Id: I8d74a26f6ef33d8e0b3fabb8a5f1227e65e81ef9 --- absl/testing/BUILD | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/absl/testing/BUILD b/absl/testing/BUILD index cfc06900..e63e966d 100644 --- a/absl/testing/BUILD +++ b/absl/testing/BUILD @@ -1,26 +1,5 @@ licenses(["notice"]) # Apache 2.0 -config_setting( - name = "osx", - constraint_values = ["//third_party/bazel_platforms/os:osx"], -) - -config_setting( - name = "ios", - flag_values = {"//tools/cpp:cc_target_os": "apple"}, -) - -_absl_test_platform_deps = select({ - ":osx": [], - ":ios": [], - # TODO(b/75911467): Remove after :osx works in host mode - "//tools/cc_target_os:platform_macos": [], - "//conditions:default": [ - "//third_party/py/faulthandler", - "//third_party/py/readline", # Enables arrow keys and tab-completion in (pdb). - ], -}) - py_library( name = "absltest", srcs = ["absltest.py"],