Avoid `unittest.TestCase` methods

This commit is contained in:
Adam Turner
2023-02-17 23:05:57 +00:00
parent f6435a9bc3
commit dc1a519a1d
4 changed files with 299 additions and 298 deletions

View File

@@ -2,7 +2,6 @@
import http.server
import os
import unittest
from unittest import mock
import pytest
@@ -428,21 +427,21 @@ def test_load_mappings_fallback(tempdir, app, status, warning):
assert isinstance(rn, nodes.reference)
class TestStripBasicAuth(unittest.TestCase):
class TestStripBasicAuth:
"""Tests for sphinx.ext.intersphinx._strip_basic_auth()"""
def test_auth_stripped(self):
"""basic auth creds stripped from URL containing creds"""
url = 'https://user:12345@domain.com/project/objects.inv'
expected = 'https://domain.com/project/objects.inv'
actual = _strip_basic_auth(url)
self.assertEqual(expected, actual)
assert expected == actual
def test_no_auth(self):
"""url unchanged if param doesn't contain basic auth creds"""
url = 'https://domain.com/project/objects.inv'
expected = 'https://domain.com/project/objects.inv'
actual = _strip_basic_auth(url)
self.assertEqual(expected, actual)
assert expected == actual
def test_having_port(self):
"""basic auth creds correctly stripped from URL containing creds even if URL
@@ -450,7 +449,7 @@ class TestStripBasicAuth(unittest.TestCase):
url = 'https://user:12345@domain.com:8080/project/objects.inv'
expected = 'https://domain.com:8080/project/objects.inv'
actual = _strip_basic_auth(url)
self.assertEqual(expected, actual)
assert expected == actual
def test_getsafeurl_authed():

View File

@@ -1,7 +1,9 @@
"""Tests for :mod:`sphinx.ext.napoleon.__init__` module."""
from collections import namedtuple
from unittest import TestCase, mock
from unittest import mock
import pytest
from sphinx.application import Sphinx
from sphinx.ext.napoleon import Config, _process_docstring, _skip_member, setup
@@ -66,7 +68,7 @@ class SampleError(Exception):
SampleNamedTuple = namedtuple('SampleNamedTuple', 'user_id block_type def_id')
class ProcessDocstringTest(TestCase):
class TestProcessDocstring:
def test_modify_in_place(self):
lines = ['Summary line.',
'',
@@ -81,10 +83,10 @@ class ProcessDocstringTest(TestCase):
'',
':param arg1: arg1 description',
'']
self.assertEqual(expected, lines)
assert expected == lines
class SetupTest(TestCase):
class TestSetup:
def test_unknown_app_type(self):
setup(object())
@@ -100,7 +102,7 @@ class SetupTest(TestCase):
):
has_config = True
if not has_config:
self.fail('Config value was not added to app %s' % name)
pytest.fail('Config value was not added to app %s' % name)
has_process_docstring = False
has_skip_member = False
@@ -117,93 +119,90 @@ class SetupTest(TestCase):
):
has_skip_member = True
if not has_process_docstring:
self.fail('autodoc-process-docstring never connected')
pytest.fail('autodoc-process-docstring never connected')
if not has_skip_member:
self.fail('autodoc-skip-member never connected')
pytest.fail('autodoc-skip-member never connected')
class SkipMemberTest(TestCase):
def assertSkip(self, what, member, obj, expect_default_skip, config_name):
class TestSkipMember:
def assert_skip(self, what, member, obj, expect_default_skip, config_name):
skip = True
app = mock.Mock()
app.config = Config()
setattr(app.config, config_name, True)
if expect_default_skip:
self.assertEqual(None, _skip_member(app, what, member, obj, skip,
mock.Mock()))
assert None is _skip_member(app, what, member, obj, skip, mock.Mock())
else:
self.assertIs(_skip_member(app, what, member, obj, skip,
mock.Mock()), False)
assert _skip_member(app, what, member, obj, skip, mock.Mock()) is False
setattr(app.config, config_name, False)
self.assertEqual(None, _skip_member(app, what, member, obj, skip,
mock.Mock()))
assert None is _skip_member(app, what, member, obj, skip, mock.Mock())
def test_namedtuple(self):
# Since python 3.7, namedtuple._asdict() has not been documented
# because there is no way to check the method is a member of the
# namedtuple class. This testcase confirms only it does not
# raise an error on building document (refs: #1455)
self.assertSkip('class', '_asdict',
SampleNamedTuple._asdict, True,
'napoleon_include_private_with_doc')
self.assert_skip('class', '_asdict',
SampleNamedTuple._asdict, True,
'napoleon_include_private_with_doc')
def test_class_private_doc(self):
self.assertSkip('class', '_private_doc',
SampleClass._private_doc, False,
'napoleon_include_private_with_doc')
self.assert_skip('class', '_private_doc',
SampleClass._private_doc, False,
'napoleon_include_private_with_doc')
def test_class_private_undoc(self):
self.assertSkip('class', '_private_undoc',
SampleClass._private_undoc, True,
'napoleon_include_private_with_doc')
self.assert_skip('class', '_private_undoc',
SampleClass._private_undoc, True,
'napoleon_include_private_with_doc')
def test_class_special_doc(self):
self.assertSkip('class', '__special_doc__',
SampleClass.__special_doc__, False,
'napoleon_include_special_with_doc')
self.assert_skip('class', '__special_doc__',
SampleClass.__special_doc__, False,
'napoleon_include_special_with_doc')
def test_class_special_undoc(self):
self.assertSkip('class', '__special_undoc__',
SampleClass.__special_undoc__, True,
'napoleon_include_special_with_doc')
self.assert_skip('class', '__special_undoc__',
SampleClass.__special_undoc__, True,
'napoleon_include_special_with_doc')
def test_class_decorated_doc(self):
self.assertSkip('class', '__decorated_func__',
SampleClass.__decorated_func__, False,
'napoleon_include_special_with_doc')
self.assert_skip('class', '__decorated_func__',
SampleClass.__decorated_func__, False,
'napoleon_include_special_with_doc')
def test_exception_private_doc(self):
self.assertSkip('exception', '_private_doc',
SampleError._private_doc, False,
'napoleon_include_private_with_doc')
self.assert_skip('exception', '_private_doc',
SampleError._private_doc, False,
'napoleon_include_private_with_doc')
def test_exception_private_undoc(self):
self.assertSkip('exception', '_private_undoc',
SampleError._private_undoc, True,
'napoleon_include_private_with_doc')
self.assert_skip('exception', '_private_undoc',
SampleError._private_undoc, True,
'napoleon_include_private_with_doc')
def test_exception_special_doc(self):
self.assertSkip('exception', '__special_doc__',
SampleError.__special_doc__, False,
'napoleon_include_special_with_doc')
self.assert_skip('exception', '__special_doc__',
SampleError.__special_doc__, False,
'napoleon_include_special_with_doc')
def test_exception_special_undoc(self):
self.assertSkip('exception', '__special_undoc__',
SampleError.__special_undoc__, True,
'napoleon_include_special_with_doc')
self.assert_skip('exception', '__special_undoc__',
SampleError.__special_undoc__, True,
'napoleon_include_special_with_doc')
def test_module_private_doc(self):
self.assertSkip('module', '_private_doc', _private_doc, False,
'napoleon_include_private_with_doc')
self.assert_skip('module', '_private_doc', _private_doc, False,
'napoleon_include_private_with_doc')
def test_module_private_undoc(self):
self.assertSkip('module', '_private_undoc', _private_undoc, True,
'napoleon_include_private_with_doc')
self.assert_skip('module', '_private_undoc', _private_undoc, True,
'napoleon_include_private_with_doc')
def test_module_special_doc(self):
self.assertSkip('module', '__special_doc__', __special_doc__, False,
'napoleon_include_special_with_doc')
self.assert_skip('module', '__special_doc__', __special_doc__, False,
'napoleon_include_special_with_doc')
def test_module_special_undoc(self):
self.assertSkip('module', '__special_undoc__', __special_undoc__, True,
'napoleon_include_special_with_doc')
self.assert_skip('module', '__special_undoc__', __special_undoc__, True,
'napoleon_include_special_with_doc')

View File

@@ -5,7 +5,7 @@ from collections import namedtuple
from contextlib import contextmanager
from inspect import cleandoc
from textwrap import dedent
from unittest import TestCase, mock
from unittest import mock
import pytest
@@ -44,11 +44,7 @@ class NamedtupleSubclass(namedtuple('NamedtupleSubclass', ('attr1', 'attr2'))):
return super().__new__(cls, attr1, attr2)
class BaseDocstringTest(TestCase):
pass
class NamedtupleSubclassTest(BaseDocstringTest):
class TestNamedtupleSubclass:
def test_attributes_docstring(self):
config = Config()
actual = str(NumpyDocstring(cleandoc(NamedtupleSubclass.__doc__),
@@ -76,10 +72,10 @@ Sample namedtuple subclass
:type: Type
"""
self.assertEqual(expected, actual)
assert expected == actual
class InlineAttributeTest(BaseDocstringTest):
class TestInlineAttribute:
def test_class_data_member(self):
config = Config()
@@ -95,7 +91,7 @@ class InlineAttributeTest(BaseDocstringTest):
- a: b""")
self.assertEqual(expected, actual)
assert expected == actual
def test_class_data_member_inline(self):
config = Config()
@@ -106,7 +102,7 @@ class InlineAttributeTest(BaseDocstringTest):
data member description with :ref:`reference`
:type: b""")
self.assertEqual(expected, actual)
assert expected == actual
def test_class_data_member_inline_no_type(self):
config = Config()
@@ -115,7 +111,7 @@ class InlineAttributeTest(BaseDocstringTest):
what='attribute', name='some_data', obj=0))
expected = """data with ``a : in code`` and :ref:`reference` and no type"""
self.assertEqual(expected, actual)
assert expected == actual
def test_class_data_member_inline_ref_in_type(self):
config = Config()
@@ -126,10 +122,10 @@ class InlineAttributeTest(BaseDocstringTest):
data member description
:type: :class:`int`""")
self.assertEqual(expected, actual)
assert expected == actual
class GoogleDocstringTest(BaseDocstringTest):
class TestGoogleDocstring:
docstrings = [(
"""Single line summary""",
"""Single line summary""",
@@ -426,14 +422,14 @@ class GoogleDocstringTest(BaseDocstringTest):
" \n"
" and this is the second line\n"
)
self.assertEqual(expect, actual)
assert expect == actual
# Single line
actual = str(GoogleDocstring(f"{section}:\n"
" this is a single line\n",
config))
expect = f".. {admonition}:: this is a single line\n"
self.assertEqual(expect, actual)
assert expect == actual
def test_docstrings(self):
config = Config(
@@ -444,7 +440,7 @@ class GoogleDocstringTest(BaseDocstringTest):
for docstring, expected in self.docstrings:
actual = str(GoogleDocstring(dedent(docstring), config))
expected = dedent(expected)
self.assertEqual(expected, actual)
assert expected == actual
def test_parameters_with_class_reference(self):
docstring = """\
@@ -480,7 +476,7 @@ This class should only be used by runtimes.
:param scope_ids: Identifiers needed to resolve scopes.
:type scope_ids: :class:`ScopeIds`
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_attributes_with_class_reference(self):
docstring = """\
@@ -496,7 +492,7 @@ Attributes:
:type: :class:`numpy.ndarray`
"""
self.assertEqual(expected, actual)
assert expected == actual
docstring = """\
Attributes:
@@ -527,7 +523,7 @@ Attributes:
:ivar bar: blah blah
:vartype bar: str
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_code_block_in_returns_section(self):
docstring = """
@@ -547,7 +543,7 @@ Returns:
:rtype: foobar
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
assert expected == actual
def test_colon_in_return_type(self):
docstring = """Example property.
@@ -563,7 +559,7 @@ Returns:
:rtype: :py:class:`~.module.submodule.SomeClass`
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
assert expected == actual
def test_xrefs_in_return_type(self):
docstring = """Example Function
@@ -579,7 +575,7 @@ Returns:
:rtype: :class:`numpy.ndarray`
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
assert expected == actual
def test_raises_types(self):
docstrings = [("""
@@ -749,7 +745,7 @@ Example Function
""")]
for docstring, expected in docstrings:
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
assert expected == actual
def test_kwargs_in_arguments(self):
docstring = """Allows to create attributes binded to this device.
@@ -780,7 +776,7 @@ Code sample for usage::
example above.
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
assert expected == actual
def test_section_header_formatting(self):
docstrings = [("""
@@ -834,7 +830,7 @@ Summary line
""")]
for docstring, expected in docstrings:
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
assert expected == actual
def test_list_in_parameter_description(self):
docstring = """One line summary.
@@ -1017,7 +1013,7 @@ Parameters:
"""
config = Config(napoleon_use_param=True)
actual = str(GoogleDocstring(docstring, config))
self.assertEqual(expected, actual)
assert expected == actual
expected = """One line summary.
@@ -1113,7 +1109,7 @@ Parameters:
"""
config = Config(napoleon_use_param=False)
actual = str(GoogleDocstring(docstring, config))
self.assertEqual(expected, actual)
assert expected == actual
def test_custom_generic_sections(self):
@@ -1152,7 +1148,7 @@ Returns Style:
for docstring, expected in docstrings:
actual = str(GoogleDocstring(docstring, testConfig))
self.assertEqual(expected, actual)
assert expected == actual
def test_noindex(self):
docstring = """
@@ -1180,7 +1176,7 @@ Methods:
config = Config()
actual = str(GoogleDocstring(docstring, config=config, app=None, what='module',
options={'noindex': True}))
self.assertEqual(expected, actual)
assert expected == actual
def test_keywords_with_types(self):
docstring = """\
@@ -1196,7 +1192,7 @@ Do as you please
:keyword gotham_is_yours: shall interfere.
:kwtype gotham_is_yours: None
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_pep526_annotations(self):
# Test class attributes annotations
@@ -1220,7 +1216,7 @@ Sample class with PEP 526 annotations and google docstring
:type: str
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_preprocess_types(self):
docstring = """\
@@ -1235,7 +1231,7 @@ Do as you please
:Yields: *str* -- Extended
"""
self.assertEqual(expected, actual)
assert expected == actual
config = Config(napoleon_preprocess_types=True)
actual = str(GoogleDocstring(docstring, config))
@@ -1244,10 +1240,10 @@ Do as you please
:Yields: :class:`str` -- Extended
"""
self.assertEqual(expected, actual)
assert expected == actual
class NumpyDocstringTest(BaseDocstringTest):
class TestNumpyDocstring:
docstrings = [(
"""Single line summary""",
"""Single line summary""",
@@ -1488,7 +1484,7 @@ class NumpyDocstringTest(BaseDocstringTest):
" \n"
" and this is the second line\n"
)
self.assertEqual(expect, actual)
assert expect == actual
# Single line
actual = str(NumpyDocstring(f"{section}\n"
@@ -1496,7 +1492,7 @@ class NumpyDocstringTest(BaseDocstringTest):
f" this is a single line\n",
config))
expect = f".. {admonition}:: this is a single line\n"
self.assertEqual(expect, actual)
assert expect == actual
def test_docstrings(self):
config = Config(
@@ -1507,7 +1503,7 @@ class NumpyDocstringTest(BaseDocstringTest):
for docstring, expected in self.docstrings:
actual = str(NumpyDocstring(dedent(docstring), config))
expected = dedent(expected)
self.assertEqual(expected, actual)
assert expected == actual
def test_type_preprocessor(self):
docstring = dedent("""
@@ -1528,7 +1524,7 @@ class NumpyDocstringTest(BaseDocstringTest):
:Parameters: **arg1** (*str*) -- Extended
description of arg1
""")
self.assertEqual(expected, actual)
assert expected == actual
def test_parameters_with_class_reference(self):
docstring = """\
@@ -1549,7 +1545,7 @@ param2 : :class:`MyClass <name.space.MyClass>` instance
:Other Parameters: **param2** (:class:`MyClass <name.space.MyClass>` instance)
"""
self.assertEqual(expected, actual)
assert expected == actual
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(docstring, config))
@@ -1560,7 +1556,7 @@ param2 : :class:`MyClass <name.space.MyClass>` instance
:param param2:
:type param2: :class:`MyClass <name.space.MyClass>` instance
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_multiple_parameters(self):
docstring = """\
@@ -1576,7 +1572,7 @@ x1, x2 : array_like
expected = """\
:Parameters: **x1, x2** (*array_like*) -- Input arrays, description of ``x1``, ``x2``.
"""
self.assertEqual(expected, actual)
assert expected == actual
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(dedent(docstring), config))
@@ -1586,7 +1582,7 @@ x1, x2 : array_like
:param x2: Input arrays, description of ``x1``, ``x2``.
:type x2: array_like
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_parameters_without_class_reference(self):
docstring = """\
@@ -1601,7 +1597,7 @@ param1 : MyClass instance
expected = """\
:Parameters: **param1** (*MyClass instance*)
"""
self.assertEqual(expected, actual)
assert expected == actual
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(dedent(docstring), config))
@@ -1609,7 +1605,7 @@ param1 : MyClass instance
:param param1:
:type param1: MyClass instance
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_see_also_refs(self):
docstring = """\
@@ -1634,7 +1630,7 @@ numpy.multivariate_normal(mean, cov, shape=None, spam=None)
:obj:`otherfunc`
relationship
"""
self.assertEqual(expected, actual)
assert expected == actual
docstring = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
@@ -1660,7 +1656,7 @@ numpy.multivariate_normal(mean, cov, shape=None, spam=None)
:obj:`otherfunc`
relationship
"""
self.assertEqual(expected, actual)
assert expected == actual
docstring = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
@@ -1689,7 +1685,7 @@ numpy.multivariate_normal(mean, cov, shape=None, spam=None)
:func:`~my_package.otherfunc`
relationship
"""
self.assertEqual(expected, actual)
assert expected == actual
def test_colon_in_return_type(self):
docstring = """
@@ -1712,7 +1708,7 @@ Summary
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
assert expected == actual
def test_underscore_in_attribute(self):
docstring = """
@@ -1732,7 +1728,7 @@ arg_ : type
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "class"))
self.assertEqual(expected, actual)
assert expected == actual
def test_underscore_in_attribute_strip_signature_backslash(self):
docstring = """
@@ -1753,7 +1749,7 @@ arg_ : type
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "class"))
self.assertEqual(expected, actual)
assert expected == actual
def test_return_types(self):
docstring = dedent("""
@@ -1776,7 +1772,7 @@ arg_ : type
napoleon_type_aliases=translations,
)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
assert expected == actual
def test_yield_types(self):
docstring = dedent("""
@@ -1799,7 +1795,7 @@ arg_ : type
config = Config(napoleon_type_aliases=translations, napoleon_preprocess_types=True)
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
assert expected == actual
def test_raises_types(self):
docstrings = [("""
@@ -2012,7 +2008,7 @@ Example Function
config = Config(napoleon_type_aliases=translations, napoleon_preprocess_types=True)
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
assert expected == actual
def test_xrefs_in_return_type(self):
docstring = """
@@ -2034,7 +2030,7 @@ Example Function
config = Config()
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
assert expected == actual
def test_section_header_underline_length(self):
docstrings = [("""
@@ -2106,7 +2102,7 @@ body
""")]
for docstring, expected in docstrings:
actual = str(NumpyDocstring(docstring))
self.assertEqual(expected, actual)
assert expected == actual
def test_list_in_parameter_description(self):
docstring = """One line summary.
@@ -2280,7 +2276,7 @@ definition_after_normal_text : int
"""
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
assert expected == actual
expected = """One line summary.
@@ -2372,7 +2368,7 @@ definition_after_normal_text : int
"""
config = Config(napoleon_use_param=False, napoleon_preprocess_types=True)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
assert expected == actual
def test_token_type(self):
tokens = (
@@ -2397,7 +2393,7 @@ definition_after_normal_text : int
for token, expected in tokens:
actual = _token_type(token)
self.assertEqual(expected, actual)
assert expected == actual
def test_tokenize_type_spec(self):
specs = (
@@ -2438,7 +2434,7 @@ definition_after_normal_text : int
for spec, expected in zip(specs, tokens):
actual = _tokenize_type_spec(spec)
self.assertEqual(expected, actual)
assert expected == actual
def test_recombine_set_tokens(self):
tokens = (
@@ -2457,7 +2453,7 @@ definition_after_normal_text : int
for tokens_, expected in zip(tokens, combined_tokens):
actual = _recombine_set_tokens(tokens_)
self.assertEqual(expected, actual)
assert expected == actual
def test_recombine_set_tokens_invalid(self):
tokens = (
@@ -2473,7 +2469,7 @@ definition_after_normal_text : int
for tokens_, expected in zip(tokens, combined_tokens):
actual = _recombine_set_tokens(tokens_)
self.assertEqual(expected, actual)
assert expected == actual
def test_convert_numpy_type_spec(self):
translations = {
@@ -2508,7 +2504,7 @@ definition_after_normal_text : int
for spec, expected in zip(specs, converted):
actual = _convert_numpy_type_spec(spec, translations=translations)
self.assertEqual(expected, actual)
assert expected == actual
def test_parameter_types(self):
docstring = dedent("""\
@@ -2565,7 +2561,7 @@ definition_after_normal_text : int
napoleon_type_aliases=translations,
)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
assert expected == actual
@contextmanager

View File

@@ -1,7 +1,6 @@
"""Tests for :mod:`sphinx.ext.napoleon.iterators` module."""
import sys
from unittest import TestCase
import pytest
@@ -12,303 +11,310 @@ with pytest.warns(DeprecationWarning,
from sphinx.ext.napoleon.iterators import modify_iter, peek_iter
class ModuleIsDeprecatedTest(TestCase):
class TestModuleIsDeprecated:
def test_module_is_deprecated(self):
sys.modules.pop("sphinx.ext.napoleon.iterators")
with self.assertWarns(RemovedInSphinx70Warning):
with pytest.warns(RemovedInSphinx70Warning,
match="sphinx.ext.napoleon.iterators is deprecated."):
import sphinx.ext.napoleon.iterators # noqa: F401
class BaseIteratorsTest(TestCase):
def assertEqualTwice(self, expected, func, *args):
self.assertEqual(expected, func(*args))
self.assertEqual(expected, func(*args))
def assertFalseTwice(self, func, *args):
self.assertFalse(func(*args))
self.assertFalse(func(*args))
def assertNext(self, it, expected, is_last):
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(expected, it.peek)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(expected, it.peek)
self.assertTrueTwice(it.has_next)
self.assertEqual(expected, next(it))
if is_last:
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next)
else:
self.assertTrueTwice(it.has_next)
def assertRaisesTwice(self, exc, func, *args):
self.assertRaises(exc, func, *args)
self.assertRaises(exc, func, *args)
def assertTrueTwice(self, func, *args):
self.assertTrue(func(*args))
self.assertTrue(func(*args))
def _assert_equal_twice(expected, func, *args):
assert expected == func(*args)
assert expected == func(*args)
class PeekIterTest(BaseIteratorsTest):
def _assert_false_twice(func, *args):
assert not func(*args)
assert not func(*args)
def _assert_next(it, expected, is_last):
_assert_true_twice(it.has_next)
_assert_equal_twice(expected, it.peek)
_assert_true_twice(it.has_next)
_assert_equal_twice(expected, it.peek)
_assert_true_twice(it.has_next)
assert expected == next(it)
if is_last:
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next)
else:
_assert_true_twice(it.has_next)
def _assert_raises_twice(exc, func, *args):
with pytest.raises(exc):
func(*args)
with pytest.raises(exc):
func(*args)
def _assert_true_twice(func, *args):
assert func(*args)
assert func(*args)
class TestPeekIter:
def test_init_with_sentinel(self):
a = iter(['1', '2', 'DONE'])
sentinel = 'DONE'
self.assertRaises(TypeError, peek_iter, a, sentinel)
with pytest.raises(TypeError):
peek_iter(a, sentinel)
def get_next():
return next(a)
it = peek_iter(get_next, sentinel)
self.assertEqual(it.sentinel, sentinel)
self.assertNext(it, '1', is_last=False)
self.assertNext(it, '2', is_last=True)
assert it.sentinel == sentinel
_assert_next(it, '1', is_last=False)
_assert_next(it, '2', is_last=True)
def test_iter(self):
a = ['1', '2', '3']
it = peek_iter(a)
self.assertTrue(it is it.__iter__())
assert it is it.__iter__()
a = []
b = list(peek_iter(a))
self.assertEqual([], b)
assert [] == b
a = ['1']
b = list(peek_iter(a))
self.assertEqual(['1'], b)
assert ["1"] == b
a = ['1', '2']
b = list(peek_iter(a))
self.assertEqual(['1', '2'], b)
assert ["1", "2"] == b
a = ['1', '2', '3']
b = list(peek_iter(a))
self.assertEqual(['1', '2', '3'], b)
assert ["1", "2", "3"] == b
def test_next_with_multi(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 2)
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 2)
a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 2)
self.assertTrueTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 2)
_assert_true_twice(it.has_next)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqual(['1', '2'], it.next(2))
self.assertFalseTwice(it.has_next)
_assert_true_twice(it.has_next)
assert ["1", "2"] == it.next(2)
_assert_false_twice(it.has_next)
a = ['1', '2', '3']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqual(['1', '2'], it.next(2))
self.assertTrueTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 2)
self.assertTrueTwice(it.has_next)
_assert_true_twice(it.has_next)
assert ["1", "2"] == it.next(2)
_assert_true_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 2)
_assert_true_twice(it.has_next)
a = ['1', '2', '3', '4']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqual(['1', '2'], it.next(2))
self.assertTrueTwice(it.has_next)
self.assertEqual(['3', '4'], it.next(2))
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 2)
self.assertFalseTwice(it.has_next)
_assert_true_twice(it.has_next)
assert ["1", "2"] == it.next(2)
_assert_true_twice(it.has_next)
assert ["3", "4"] == it.next(2)
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 2)
_assert_false_twice(it.has_next)
def test_next_with_none(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next)
self.assertFalseTwice(it.has_next)
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next)
_assert_false_twice(it.has_next)
a = ['1']
it = peek_iter(a)
self.assertEqual('1', it.__next__())
assert it.__next__() == "1"
a = ['1']
it = peek_iter(a)
self.assertNext(it, '1', is_last=True)
_assert_next(it, '1', is_last=True)
a = ['1', '2']
it = peek_iter(a)
self.assertNext(it, '1', is_last=False)
self.assertNext(it, '2', is_last=True)
_assert_next(it, '1', is_last=False)
_assert_next(it, '2', is_last=True)
a = ['1', '2', '3']
it = peek_iter(a)
self.assertNext(it, '1', is_last=False)
self.assertNext(it, '2', is_last=False)
self.assertNext(it, '3', is_last=True)
_assert_next(it, '1', is_last=False)
_assert_next(it, '2', is_last=False)
_assert_next(it, '3', is_last=True)
def test_next_with_one(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 1)
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 1)
a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqual(['1'], it.next(1))
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 1)
_assert_true_twice(it.has_next)
assert ["1"] == it.next(1)
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 1)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqual(['1'], it.next(1))
self.assertTrueTwice(it.has_next)
self.assertEqual(['2'], it.next(1))
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 1)
_assert_true_twice(it.has_next)
assert ["1"] == it.next(1)
_assert_true_twice(it.has_next)
assert ["2"] == it.next(1)
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 1)
def test_next_with_zero(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertRaisesTwice(StopIteration, it.next, 0)
_assert_false_twice(it.has_next)
_assert_raises_twice(StopIteration, it.next, 0)
a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.next, 0)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.next, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.next, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.next, 0)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.next, 0)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.next, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.next, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.next, 0)
def test_peek_with_multi(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertEqualTwice([it.sentinel, it.sentinel], it.peek, 2)
self.assertFalseTwice(it.has_next)
_assert_false_twice(it.has_next)
_assert_equal_twice([it.sentinel, it.sentinel], it.peek, 2)
_assert_false_twice(it.has_next)
a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', it.sentinel], it.peek, 2)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', it.sentinel, it.sentinel], it.peek, 3)
self.assertTrueTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', it.sentinel], it.peek, 2)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', it.sentinel, it.sentinel], it.peek, 3)
_assert_true_twice(it.has_next)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', '2'], it.peek, 2)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', '2', it.sentinel], it.peek, 3)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', '2', it.sentinel, it.sentinel], it.peek, 4)
self.assertTrueTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', '2'], it.peek, 2)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', '2', it.sentinel], it.peek, 3)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', '2', it.sentinel, it.sentinel], it.peek, 4)
_assert_true_twice(it.has_next)
a = ['1', '2', '3']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', '2'], it.peek, 2)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', '2', '3'], it.peek, 3)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1', '2', '3', it.sentinel], it.peek, 4)
self.assertTrueTwice(it.has_next)
self.assertEqual('1', next(it))
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['2', '3'], it.peek, 2)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['2', '3', it.sentinel], it.peek, 3)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['2', '3', it.sentinel, it.sentinel], it.peek, 4)
self.assertTrueTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', '2'], it.peek, 2)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', '2', '3'], it.peek, 3)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1', '2', '3', it.sentinel], it.peek, 4)
_assert_true_twice(it.has_next)
assert next(it) == "1"
_assert_true_twice(it.has_next)
_assert_equal_twice(['2', '3'], it.peek, 2)
_assert_true_twice(it.has_next)
_assert_equal_twice(['2', '3', it.sentinel], it.peek, 3)
_assert_true_twice(it.has_next)
_assert_equal_twice(['2', '3', it.sentinel, it.sentinel], it.peek, 4)
_assert_true_twice(it.has_next)
def test_peek_with_none(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertEqualTwice(it.sentinel, it.peek)
self.assertFalseTwice(it.has_next)
_assert_false_twice(it.has_next)
_assert_equal_twice(it.sentinel, it.peek)
_assert_false_twice(it.has_next)
a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice('1', it.peek)
self.assertEqual('1', next(it))
self.assertFalseTwice(it.has_next)
self.assertEqualTwice(it.sentinel, it.peek)
self.assertFalseTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_equal_twice('1', it.peek)
assert next(it) == "1"
_assert_false_twice(it.has_next)
_assert_equal_twice(it.sentinel, it.peek)
_assert_false_twice(it.has_next)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice('1', it.peek)
self.assertEqual('1', next(it))
self.assertTrueTwice(it.has_next)
self.assertEqualTwice('2', it.peek)
self.assertEqual('2', next(it))
self.assertFalseTwice(it.has_next)
self.assertEqualTwice(it.sentinel, it.peek)
self.assertFalseTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_equal_twice('1', it.peek)
assert next(it) == "1"
_assert_true_twice(it.has_next)
_assert_equal_twice('2', it.peek)
assert next(it) == "2"
_assert_false_twice(it.has_next)
_assert_equal_twice(it.sentinel, it.peek)
_assert_false_twice(it.has_next)
def test_peek_with_one(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertEqualTwice([it.sentinel], it.peek, 1)
self.assertFalseTwice(it.has_next)
_assert_false_twice(it.has_next)
_assert_equal_twice([it.sentinel], it.peek, 1)
_assert_false_twice(it.has_next)
a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1'], it.peek, 1)
self.assertEqual('1', next(it))
self.assertFalseTwice(it.has_next)
self.assertEqualTwice([it.sentinel], it.peek, 1)
self.assertFalseTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1'], it.peek, 1)
assert next(it) == "1"
_assert_false_twice(it.has_next)
_assert_equal_twice([it.sentinel], it.peek, 1)
_assert_false_twice(it.has_next)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['1'], it.peek, 1)
self.assertEqual('1', next(it))
self.assertTrueTwice(it.has_next)
self.assertEqualTwice(['2'], it.peek, 1)
self.assertEqual('2', next(it))
self.assertFalseTwice(it.has_next)
self.assertEqualTwice([it.sentinel], it.peek, 1)
self.assertFalseTwice(it.has_next)
_assert_true_twice(it.has_next)
_assert_equal_twice(['1'], it.peek, 1)
assert next(it) == "1"
_assert_true_twice(it.has_next)
_assert_equal_twice(['2'], it.peek, 1)
assert next(it) == "2"
_assert_false_twice(it.has_next)
_assert_equal_twice([it.sentinel], it.peek, 1)
_assert_false_twice(it.has_next)
def test_peek_with_zero(self):
a = []
it = peek_iter(a)
self.assertFalseTwice(it.has_next)
self.assertEqualTwice([], it.peek, 0)
_assert_false_twice(it.has_next)
_assert_equal_twice([], it.peek, 0)
a = ['1']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.peek, 0)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.peek, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.peek, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.peek, 0)
a = ['1', '2']
it = peek_iter(a)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.peek, 0)
self.assertTrueTwice(it.has_next)
self.assertEqualTwice([], it.peek, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.peek, 0)
_assert_true_twice(it.has_next)
_assert_equal_twice([], it.peek, 0)
class ModifyIterTest(BaseIteratorsTest):
class TestModifyIter:
def test_init_with_sentinel_args(self):
a = iter(['1', '2', '3', 'DONE'])
sentinel = 'DONE'
@@ -317,7 +323,7 @@ class ModifyIterTest(BaseIteratorsTest):
return next(a)
it = modify_iter(get_next, sentinel, int)
expected = [1, 2, 3]
self.assertEqual(expected, list(it))
assert expected == list(it)
def test_init_with_sentinel_kwargs(self):
a = iter([1, 2, 3, 4])
@@ -327,25 +333,26 @@ class ModifyIterTest(BaseIteratorsTest):
return next(a)
it = modify_iter(get_next, sentinel, modifier=str)
expected = ['1', '2', '3']
self.assertEqual(expected, list(it))
assert expected == list(it)
def test_modifier_default(self):
a = ['', ' ', ' a ', 'b ', ' c', ' ', '']
it = modify_iter(a)
expected = ['', ' ', ' a ', 'b ', ' c', ' ', '']
self.assertEqual(expected, list(it))
assert expected == list(it)
def test_modifier_not_callable(self):
self.assertRaises(TypeError, modify_iter, [1], modifier='not_callable')
with pytest.raises(TypeError):
modify_iter([1], modifier='not_callable')
def test_modifier_rstrip(self):
a = ['', ' ', ' a ', 'b ', ' c', ' ', '']
it = modify_iter(a, modifier=lambda s: s.rstrip())
expected = ['', '', ' a', 'b', ' c', '', '']
self.assertEqual(expected, list(it))
assert expected == list(it)
def test_modifier_rstrip_unicode(self):
a = ['', ' ', ' a ', 'b ', ' c', ' ', '']
it = modify_iter(a, modifier=lambda s: s.rstrip())
expected = ['', '', ' a', 'b', ' c', '', '']
self.assertEqual(expected, list(it))
assert expected == list(it)