From be0e3553e77d6245b6e36849d242ecacb8461ad4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Fri, 25 Oct 2019 09:14:14 +0200 Subject: [PATCH 01/10] ENH: Show column name in assert_frame_equal The output of the AssertionError is changed: - old: `AssertionError: Attributes of DataFrame.iloc[:, 1] are different` - new: `AssertionError: Attributes of DataFrame.loc[:, 'b'] are different` --- pandas/tests/util/test_assert_frame_equal.py | 12 ++++++------ pandas/util/testing.py | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index 86e5d506e0779..4dbc06b6800f8 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -181,9 +181,9 @@ def test_frame_equal_columns_mismatch(obj_fixture): def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): - msg = """{obj}\\.iloc\\[:, 1\\] are different + msg = """{obj}\\.loc\\[:, 'B'\\] are different -{obj}\\.iloc\\[:, 1\\] values are different \\(33\\.33333 %\\) +{obj}\\.loc\\[:, 'B'\\] values are different \\(33\\.33333 %\\) \\[left\\]: \\[4, 5, 6\\] \\[right\\]: \\[4, 5, 7\\]""".format( obj=obj_fixture @@ -202,18 +202,18 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "e̊"]}), - """{obj}\\.iloc\\[:, 1\\] are different + """{obj}\\.loc\\[:, 'E'\\] are different -{obj}\\.iloc\\[:, 1\\] values are different \\(33\\.33333 %\\) +{obj}\\.loc\\[:, 'E'\\] values are different \\(33\\.33333 %\\) \\[left\\]: \\[é, è, ë\\] \\[right\\]: \\[é, è, e̊\\]""", ), ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["a", "a", "a"], "E": ["e", "e", "e"]}), - """{obj}\\.iloc\\[:, 0\\] are different + """{obj}\\.loc\\[:, 'A'\\] are different -{obj}\\.iloc\\[:, 0\\] values are different \\(100\\.0 %\\) +{obj}\\.loc\\[:, 'A'\\] values are different \\(100\\.0 %\\) \\[left\\]: \\[á, à, ä\\] \\[right\\]: \\[a, a, a\\]""", ), diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 73535e55d4fa5..a7c5ccb8a8768 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1318,7 +1318,7 @@ def assert_frame_equal( >>> assert_frame_equal(df1, df2) Traceback (most recent call last): ... - AssertionError: Attributes of DataFrame.iloc[:, 1] are different + AssertionError: Attributes of DataFrame.loc[:, 'b'] are different Attribute "dtype" are different [left]: int64 @@ -1400,7 +1400,7 @@ def assert_frame_equal( check_names=check_names, check_datetimelike_compat=check_datetimelike_compat, check_categorical=check_categorical, - obj="{obj}.iloc[:, {idx}]".format(obj=obj, idx=i), + obj="{obj}.loc[:, {col!r}]".format(obj=obj, col=col), ) From 369cfa9024b3cc2de6430789fc34853179bba3af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Fri, 25 Oct 2019 16:10:30 +0200 Subject: [PATCH 02/10] Show column iloc and name --- pandas/tests/util/test_assert_frame_equal.py | 12 ++++++------ pandas/util/testing.py | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index 4dbc06b6800f8..1b63431ba6452 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -181,9 +181,9 @@ def test_frame_equal_columns_mismatch(obj_fixture): def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): - msg = """{obj}\\.loc\\[:, 'B'\\] are different + msg = """{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) are different -{obj}\\.loc\\[:, 'B'\\] values are different \\(33\\.33333 %\\) +{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) values are different \\(33\\.33333 %\\) \\[left\\]: \\[4, 5, 6\\] \\[right\\]: \\[4, 5, 7\\]""".format( obj=obj_fixture @@ -202,18 +202,18 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "e̊"]}), - """{obj}\\.loc\\[:, 'E'\\] are different + """{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) -{obj}\\.loc\\[:, 'E'\\] values are different \\(33\\.33333 %\\) +{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) values are different \\(33\\.33333 %\\) \\[left\\]: \\[é, è, ë\\] \\[right\\]: \\[é, è, e̊\\]""", ), ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["a", "a", "a"], "E": ["e", "e", "e"]}), - """{obj}\\.loc\\[:, 'A'\\] are different + """{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) -{obj}\\.loc\\[:, 'A'\\] values are different \\(100\\.0 %\\) +{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) values are different \\(100\\.0 %\\) \\[left\\]: \\[á, à, ä\\] \\[right\\]: \\[a, a, a\\]""", ), diff --git a/pandas/util/testing.py b/pandas/util/testing.py index a7c5ccb8a8768..376df697bcb5b 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1400,7 +1400,7 @@ def assert_frame_equal( check_names=check_names, check_datetimelike_compat=check_datetimelike_compat, check_categorical=check_categorical, - obj="{obj}.loc[:, {col!r}]".format(obj=obj, col=col), + obj="{obj}.iloc[:, {idx}] (column name=\"{col}\")".format(obj=obj, idx=i, col=col), ) From f6c14504173d9aa03e8511a0e17b051735013d92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Fri, 25 Oct 2019 16:12:57 +0200 Subject: [PATCH 03/10] Fix formatting --- pandas/util/testing.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 376df697bcb5b..faa7fb675d966 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1400,7 +1400,9 @@ def assert_frame_equal( check_names=check_names, check_datetimelike_compat=check_datetimelike_compat, check_categorical=check_categorical, - obj="{obj}.iloc[:, {idx}] (column name=\"{col}\")".format(obj=obj, idx=i, col=col), + obj='{obj}.iloc[:, {idx}] (column name="{col}")'.format( + obj=obj, idx=i, col=col + ), ) From f23e97bea166e2186fadca4756b6e7bba50622bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Fri, 25 Oct 2019 16:14:40 +0200 Subject: [PATCH 04/10] Update example --- pandas/util/testing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index faa7fb675d966..4545fbde36972 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1318,7 +1318,7 @@ def assert_frame_equal( >>> assert_frame_equal(df1, df2) Traceback (most recent call last): ... - AssertionError: Attributes of DataFrame.loc[:, 'b'] are different + AssertionError: Attributes of DataFrame.iloc[:, 1] (column name="b") are different Attribute "dtype" are different [left]: int64 From 15770304dee801277196b6c70777c6492cb541ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Mon, 18 Nov 2019 20:30:33 +0100 Subject: [PATCH 05/10] test_frame_equal_unicode: Fix pattern --- pandas/tests/util/test_assert_frame_equal.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index 1b63431ba6452..e2f9fb63c76b1 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -202,7 +202,7 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "e̊"]}), - """{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) + """{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) are different {obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) values are different \\(33\\.33333 %\\) \\[left\\]: \\[é, è, ë\\] @@ -211,7 +211,7 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture): ( DataFrame({"A": ["á", "à", "ä"], "E": ["é", "è", "ë"]}), DataFrame({"A": ["a", "a", "a"], "E": ["e", "e", "e"]}), - """{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) + """{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) are different {obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) values are different \\(100\\.0 %\\) \\[left\\]: \\[á, à, ä\\] From 8416728c3b2dc446976047a90a3001e3074d4141 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Tue, 19 Nov 2019 16:19:47 +0100 Subject: [PATCH 06/10] Use f-strings --- pandas/util/testing.py | 154 +++++++++++++++-------------------------- 1 file changed, 57 insertions(+), 97 deletions(-) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 4545fbde36972..8f1cd7db5e3e9 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -217,9 +217,9 @@ def decompress_file(path, compression): if len(zip_names) == 1: f = zip_file.open(zip_names.pop()) else: - raise ValueError("ZIP file {} error. Only one file per ZIP.".format(path)) + raise ValueError(f"ZIP file {path} error. Only one file per ZIP.") else: - msg = "Unrecognized compression type: {}".format(compression) + msg = f"Unrecognized compression type: {compression}" raise ValueError(msg) try: @@ -265,7 +265,7 @@ def write_to_compressed(compression, path, data, dest="test"): elif compression == "xz": compress_method = _get_lzma_file(lzma) else: - msg = "Unrecognized compression type: {}".format(compression) + msg = f"Unrecognized compression type: {compression}" raise ValueError(msg) if compression == "zip": @@ -317,7 +317,7 @@ def assert_almost_equal( check_exact=False, exact=check_dtype, check_less_precise=check_less_precise, - **kwargs + **kwargs, ) elif isinstance(left, pd.Series): @@ -327,7 +327,7 @@ def assert_almost_equal( check_exact=False, check_dtype=check_dtype, check_less_precise=check_less_precise, - **kwargs + **kwargs, ) elif isinstance(left, pd.DataFrame): @@ -337,7 +337,7 @@ def assert_almost_equal( check_exact=False, check_dtype=check_dtype, check_less_precise=check_less_precise, - **kwargs + **kwargs, ) else: @@ -360,7 +360,7 @@ def assert_almost_equal( right, check_dtype=check_dtype, check_less_precise=check_less_precise, - **kwargs + **kwargs, ) @@ -511,16 +511,12 @@ def ensure_clean(filename=None, return_filelike=False): try: os.close(fd) except OSError: - print( - "Couldn't close file descriptor: {fdesc} (file: {fname})".format( - fdesc=fd, fname=filename - ) - ) + print(f"Couldn't close file descriptor: {fd} (file: {filename})") try: if os.path.exists(filename): os.remove(filename) except OSError as e: - print("Exception on removing file: {error}".format(error=e)) + print(f"Exception on removing file: {e}") @contextmanager @@ -635,14 +631,14 @@ def _get_ilevel_values(index, level): # level comparison if left.nlevels != right.nlevels: - msg1 = "{obj} levels are different".format(obj=obj) - msg2 = "{nlevels}, {left}".format(nlevels=left.nlevels, left=left) - msg3 = "{nlevels}, {right}".format(nlevels=right.nlevels, right=right) + msg1 = f"{obj} levels are different" + msg2 = f"{left.nlevels}, {left}" + msg3 = f"{right.nlevels}, {right}" raise_assert_detail(obj, msg1, msg2, msg3) # length comparison if len(left) != len(right): - msg1 = "{obj} length are different".format(obj=obj) + msg1 = f"{obj} length are different" msg2 = "{length}, {left}".format(length=len(left), left=left) msg3 = "{length}, {right}".format(length=len(right), right=right) raise_assert_detail(obj, msg1, msg2, msg3) @@ -657,7 +653,7 @@ def _get_ilevel_values(index, level): llevel = _get_ilevel_values(left, level) rlevel = _get_ilevel_values(right, level) - lobj = "MultiIndex level [{level}]".format(level=level) + lobj = f"MultiIndex level [{level}]" assert_index_equal( llevel, rlevel, @@ -699,9 +695,7 @@ def _get_ilevel_values(index, level): if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): - assert_categorical_equal( - left.values, right.values, obj="{obj} category".format(obj=obj) - ) + assert_categorical_equal(left.values, right.values, obj=f"{obj} category") def assert_class_equal(left, right, exact=True, obj="Input"): @@ -723,11 +717,11 @@ def repr_class(x): # allow equivalence of Int64Index/RangeIndex types = {type(left).__name__, type(right).__name__} if len(types - {"Int64Index", "RangeIndex"}): - msg = "{obj} classes are not equivalent".format(obj=obj) + msg = f"{obj} classes are not equivalent" raise_assert_detail(obj, msg, repr_class(left), repr_class(right)) elif exact: if type(left) != type(right): - msg = "{obj} classes are different".format(obj=obj) + msg = f"{obj} classes are different" raise_assert_detail(obj, msg, repr_class(left), repr_class(right)) @@ -829,25 +823,20 @@ def assert_categorical_equal( _check_isinstance(left, right, Categorical) if check_category_order: - assert_index_equal( - left.categories, right.categories, obj="{obj}.categories".format(obj=obj) - ) + assert_index_equal(left.categories, right.categories, obj=f"{obj}.categories") assert_numpy_array_equal( - left.codes, - right.codes, - check_dtype=check_dtype, - obj="{obj}.codes".format(obj=obj), + left.codes, right.codes, check_dtype=check_dtype, obj=f"{obj}.codes" ) else: assert_index_equal( left.categories.sort_values(), right.categories.sort_values(), - obj="{obj}.categories".format(obj=obj), + obj=f"{obj}.categories", ) assert_index_equal( left.categories.take(left.codes), right.categories.take(right.codes), - obj="{obj}.values".format(obj=obj), + obj=f"{obj}.values", ) assert_attr_equal("ordered", left, right, obj=obj) @@ -870,21 +859,15 @@ def assert_interval_array_equal(left, right, exact="equiv", obj="IntervalArray") """ _check_isinstance(left, right, IntervalArray) - assert_index_equal( - left.left, right.left, exact=exact, obj="{obj}.left".format(obj=obj) - ) - assert_index_equal( - left.right, right.right, exact=exact, obj="{obj}.left".format(obj=obj) - ) + assert_index_equal(left.left, right.left, exact=exact, obj=f"{obj}.left") + assert_index_equal(left.right, right.right, exact=exact, obj=f"{obj}.left") assert_attr_equal("closed", left, right, obj=obj) def assert_period_array_equal(left, right, obj="PeriodArray"): _check_isinstance(left, right, PeriodArray) - assert_numpy_array_equal( - left._data, right._data, obj="{obj}.values".format(obj=obj) - ) + assert_numpy_array_equal(left._data, right._data, obj=f"{obj}.values") assert_attr_equal("freq", left, right, obj=obj) @@ -892,7 +875,7 @@ def assert_datetime_array_equal(left, right, obj="DatetimeArray"): __tracebackhide__ = True _check_isinstance(left, right, DatetimeArray) - assert_numpy_array_equal(left._data, right._data, obj="{obj}._data".format(obj=obj)) + assert_numpy_array_equal(left._data, right._data, obj=f"{obj}._data") assert_attr_equal("freq", left, right, obj=obj) assert_attr_equal("tz", left, right, obj=obj) @@ -900,7 +883,7 @@ def assert_datetime_array_equal(left, right, obj="DatetimeArray"): def assert_timedelta_array_equal(left, right, obj="TimedeltaArray"): __tracebackhide__ = True _check_isinstance(left, right, TimedeltaArray) - assert_numpy_array_equal(left._data, right._data, obj="{obj}._data".format(obj=obj)) + assert_numpy_array_equal(left._data, right._data, obj=f"{obj}._data") assert_attr_equal("freq", left, right, obj=obj) @@ -917,16 +900,14 @@ def raise_assert_detail(obj, message, left, right, diff=None): elif is_categorical_dtype(right): right = repr(right) - msg = """{obj} are different + msg = f"""{obj} are different {message} [left]: {left} -[right]: {right}""".format( - obj=obj, message=message, left=left, right=right - ) +[right]: {right}""" if diff is not None: - msg += "\n[diff]: {diff}".format(diff=diff) + msg += f"\n[diff]: {diff}" raise AssertionError(msg) @@ -974,21 +955,18 @@ def _get_base(obj): if check_same == "same": if left_base is not right_base: - msg = "{left!r} is not {right!r}".format(left=left_base, right=right_base) + msg = f"{left_base!r} is not {right_base!r}" raise AssertionError(msg) elif check_same == "copy": if left_base is right_base: - msg = "{left!r} is {right!r}".format(left=left_base, right=right_base) + msg = f"{left_base!r} is {right_base!r}" raise AssertionError(msg) def _raise(left, right, err_msg): if err_msg is None: if left.shape != right.shape: raise_assert_detail( - obj, - "{obj} shapes are different".format(obj=obj), - left.shape, - right.shape, + obj, f"{obj} shapes are different", left.shape, right.shape ) diff = 0 @@ -1142,7 +1120,7 @@ def assert_series_equal( check_less_precise=check_less_precise, check_exact=check_exact, check_categorical=check_categorical, - obj="{obj}.index".format(obj=obj), + obj=f"{obj}.index", ) if check_dtype: @@ -1156,16 +1134,14 @@ def assert_series_equal( ): pass else: - assert_attr_equal( - "dtype", left, right, obj="Attributes of {obj}".format(obj=obj) - ) + assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}") if check_exact: assert_numpy_array_equal( left._internal_get_values(), right._internal_get_values(), check_dtype=check_dtype, - obj="{obj}".format(obj=obj), + obj=f"{obj}", ) elif check_datetimelike_compat: # we want to check only if we have compat dtypes @@ -1176,9 +1152,8 @@ def assert_series_equal( # datetimelike may have different objects (e.g. datetime.datetime # vs Timestamp) but will compare equal if not Index(left.values).equals(Index(right.values)): - msg = ( - "[datetimelike_compat=True] {left} is not equal to {right}." - ).format(left=left.values, right=right.values) + msg = f"[datetimelike_compat=True] {left.values} is not equal to {right.values}." + raise AssertionError(msg) else: assert_numpy_array_equal( @@ -1206,7 +1181,7 @@ def assert_series_equal( right._internal_get_values(), check_less_precise=check_less_precise, check_dtype=check_dtype, - obj="{obj}".format(obj=obj), + obj=f"{obj}", ) # metadata comparison @@ -1215,9 +1190,7 @@ def assert_series_equal( if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): - assert_categorical_equal( - left.values, right.values, obj="{obj} category".format(obj=obj) - ) + assert_categorical_equal(left.values, right.values, obj=f"{obj} category") # This could be refactored to use the NDFrame.equals method @@ -1340,10 +1313,7 @@ def assert_frame_equal( # shape comparison if left.shape != right.shape: raise_assert_detail( - obj, - "{obj} shape mismatch".format(obj=obj), - "{shape!r}".format(shape=left.shape), - "{shape!r}".format(shape=right.shape), + obj, f"{obj} shape mismatch", f"{left.shape!r}", f"{right.shape!r}" ) if check_like: @@ -1358,7 +1328,7 @@ def assert_frame_equal( check_less_precise=check_less_precise, check_exact=check_exact, check_categorical=check_categorical, - obj="{obj}.index".format(obj=obj), + obj=f"{obj}.index", ) # column comparison @@ -1370,7 +1340,7 @@ def assert_frame_equal( check_less_precise=check_less_precise, check_exact=check_exact, check_categorical=check_categorical, - obj="{obj}.columns".format(obj=obj), + obj=f"{obj}.columns", ) # compare by blocks @@ -1400,9 +1370,7 @@ def assert_frame_equal( check_names=check_names, check_datetimelike_compat=check_datetimelike_compat, check_categorical=check_categorical, - obj='{obj}.iloc[:, {idx}] (column name="{col}")'.format( - obj=obj, idx=i, col=col - ), + obj=f'{obj}.iloc[:, {i}] (column name="{col}")', ) @@ -1568,7 +1536,7 @@ def assert_sp_array_equal( def assert_contains_all(iterable, dic): for k in iterable: - assert k in dic, "Did not contain item: '{key!r}'".format(key=k) + assert k in dic, f"Did not contain item: '{k!r}'" def assert_copy(iter1, iter2, **eql_kwargs): @@ -1932,8 +1900,8 @@ def makeCustomIndex( return idx elif idx_type is not None: raise ValueError( - '"{idx_type}" is not a legal value for `idx_type`, ' - 'use "i"/"f"/"s"/"u"/"dt/"p"/"td".'.format(idx_type=idx_type) + f'"{idx_type}" is not a legal value for `idx_type`, ' + 'use "i"/"f"/"s"/"u"/"dt/"p"/"td".' ) if len(ndupe_l) < nlevels: @@ -1955,7 +1923,7 @@ def keyfunc(x): div_factor = nentries // ndupe_l[i] + 1 cnt = Counter() for j in range(div_factor): - label = "{prefix}_l{i}_g{j}".format(prefix=prefix, i=i, j=j) + label = f"{prefix}_l{i}_g{j}" cnt[label] = ndupe_l[i] # cute Counter trick result = list(sorted(cnt.elements(), key=keyfunc))[:nentries] @@ -2072,7 +2040,7 @@ def makeCustomDataframe( # by default, generate data based on location if data_gen_f is None: - data_gen_f = lambda r, c: "R{rows}C{cols}".format(rows=r, cols=c) + data_gen_f = lambda r, c: f"R{r}C{c}" data = [[data_gen_f(r, c) for c in range(ncols)] for r in range(nrows)] @@ -2378,7 +2346,7 @@ def wrapper(*args, **kwargs): if errno in skip_errnos: skip( "Skipping test due to known errno" - " and error {error}".format(error=err) + f" and error {err}" ) e_str = str(err) @@ -2386,7 +2354,7 @@ def wrapper(*args, **kwargs): if any(m.lower() in e_str.lower() for m in _skip_on_messages): skip( "Skipping test because exception " - "message is known and error {error}".format(error=err) + f"message is known and error {err}" ) if not isinstance(err, error_classes): @@ -2397,7 +2365,7 @@ def wrapper(*args, **kwargs): else: skip( "Skipping test due to lack of connectivity" - " and error {error}".format(error=err) + f" and error {err}" ) return wrapper @@ -2496,7 +2464,7 @@ def __exit__(self, exc_type, exc_value, trace_back): if not exc_type: exp_name = getattr(expected, "__name__", str(expected)) - raise AssertionError("{name} not raised.".format(name=exp_name)) + raise AssertionError(f"{exp_name} not raised.") return self.exception_matches(exc_type, exc_value, trace_back) @@ -2531,9 +2499,7 @@ def exception_matches(self, exc_type, exc_value, trace_back): val = str(exc_value) if not self.regexp.search(val): - msg = '"{pat}" does not match "{val}"'.format( - pat=self.regexp.pattern, val=val - ) + msg = f'"{self.regexp.pattern}" does not match "{val}"' e = AssertionError(msg) raise_with_traceback(e, trace_back) @@ -2647,12 +2613,8 @@ class for all warnings. To check that no warning is returned, caller = getframeinfo(stack()[2][0]) msg = ( "Warning not set with correct stacklevel. " - "File where warning is raised: {actual} != " - "{caller}. Warning message: {message}" - ).format( - actual=actual_warning.filename, - caller=caller.filename, - message=actual_warning.message, + f"File where warning is raised: {actual_warning.filename} != " + f"{caller.filename}. Warning message: {actual_warning.message}" ) assert actual_warning.filename == caller.filename, msg else: @@ -2665,13 +2627,11 @@ class for all warnings. To check that no warning is returned, ) ) if expected_warning: - msg = "Did not see expected warning of class {name!r}.".format( - name=expected_warning.__name__ - ) + msg = f"Did not see expected warning of class {expected_warning.__name__!r}." assert saw_warning, msg if raise_on_extra_warnings and extra_warnings: raise AssertionError( - "Caused unexpected warning(s): {!r}.".format(extra_warnings) + f"Caused unexpected warning(s): {extra_warnings!r}." ) From 39c58d3659af656ae5d7b2f5b9f84af5926f71f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Thu, 28 Nov 2019 13:08:31 +0100 Subject: [PATCH 07/10] Format source --- pandas/util/testing.py | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 8bed8f0dc3013..340e5b57de58b 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2340,10 +2340,7 @@ def wrapper(*args, **kwargs): errno = getattr(err.reason, "errno", None) if errno in skip_errnos: - skip( - "Skipping test due to known errno" - f" and error {err}" - ) + skip("Skipping test due to known errno" f" and error {err}") e_str = str(err) @@ -2359,10 +2356,7 @@ def wrapper(*args, **kwargs): if raise_on_error or can_connect(url, error_classes): raise else: - skip( - "Skipping test due to lack of connectivity" - f" and error {err}" - ) + skip("Skipping test due to lack of connectivity" f" and error {err}") return wrapper @@ -2623,12 +2617,12 @@ class for all warnings. To check that no warning is returned, ) ) if expected_warning: - msg = f"Did not see expected warning of class {expected_warning.__name__!r}." + msg = ( + f"Did not see expected warning of class {expected_warning.__name__!r}." + ) assert saw_warning, msg if raise_on_extra_warnings and extra_warnings: - raise AssertionError( - f"Caused unexpected warning(s): {extra_warnings!r}." - ) + raise AssertionError(f"Caused unexpected warning(s): {extra_warnings!r}.") class RNGContext: From b73cdf334f3d6699ff72c1ac914749b38d0b535d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Mon, 9 Dec 2019 19:59:39 +0100 Subject: [PATCH 08/10] Remove assert_raises_regex according to #29174 --- pandas/util/testing.py | 135 ----------------------------------------- 1 file changed, 135 deletions(-) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index f1d473866534e..e39759df3618a 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2352,141 +2352,6 @@ def wrapper(*args, **kwargs): with_connectivity_check = network -def assert_raises_regex(_exception, _regexp, _callable=None, *args, **kwargs): - r""" - Check that the specified Exception is raised and that the error message - matches a given regular expression pattern. This may be a regular - expression object or a string containing a regular expression suitable - for use by `re.search()`. This is a port of the `assertRaisesRegexp` - function from unittest in Python 2.7. - - .. deprecated:: 0.24.0 - Use `pytest.raises` instead. - - Examples - -------- - >>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ') - >>> import re - >>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ') - - If an exception of a different type is raised, it bubbles up. - - >>> assert_raises_regex(TypeError, 'literal', int, 'XYZ') - Traceback (most recent call last): - ... - ValueError: invalid literal for int() with base 10: 'XYZ' - >>> dct = dict() - >>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple') - Traceback (most recent call last): - ... - AssertionError: "pear" does not match "'apple'" - - You can also use this in a with statement. - - >>> with assert_raises_regex(TypeError, r'unsupported operand type\(s\)'): - ... 1 + {} - >>> with assert_raises_regex(TypeError, 'banana'): - ... 'apple'[0] = 'b' - Traceback (most recent call last): - ... - AssertionError: "banana" does not match "'str' object does not support \ -item assignment" - """ - warnings.warn( - ( - "assert_raises_regex has been deprecated and will " - "be removed in the next release. Please use " - "`pytest.raises` instead." - ), - FutureWarning, - stacklevel=2, - ) - - manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp) - if _callable is not None: - with manager: - _callable(*args, **kwargs) - else: - return manager - - -class _AssertRaisesContextmanager: - """ - Context manager behind `assert_raises_regex`. - """ - - def __init__(self, exception, regexp=None): - """ - Initialize an _AssertRaisesContextManager instance. - - Parameters - ---------- - exception : class - The expected Exception class. - regexp : str, default None - The regex to compare against the Exception message. - """ - - self.exception = exception - - if regexp is not None and not hasattr(regexp, "search"): - regexp = re.compile(regexp, re.DOTALL) - - self.regexp = regexp - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, trace_back): - expected = self.exception - - if not exc_type: - exp_name = getattr(expected, "__name__", str(expected)) - raise AssertionError(f"{exp_name} not raised.") - - return self.exception_matches(exc_type, exc_value, trace_back) - - def exception_matches(self, exc_type, exc_value, trace_back): - """ - Check that the Exception raised matches the expected Exception - and expected error message regular expression. - - Parameters - ---------- - exc_type : class - The type of Exception raised. - exc_value : Exception - The instance of `exc_type` raised. - trace_back : stack trace object - The traceback object associated with `exc_value`. - - Returns - ------- - is_matched : bool - Whether or not the Exception raised matches the expected - Exception class and expected error message regular expression. - - Raises - ------ - AssertionError : The error message provided does not match - the expected error message regular expression. - """ - - if issubclass(exc_type, self.exception): - if self.regexp is not None: - val = str(exc_value) - - if not self.regexp.search(val): - msg = f'"{self.regexp.pattern}" does not match "{val}"' - e = AssertionError(msg) - raise_with_traceback(e, trace_back) - - return True - else: - # Failed, so allow Exception to bubble up. - return False - - @contextmanager def assert_produces_warning( expected_warning=Warning, From 263128d72d4c3b8146116678c023d23f5b18ef51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon-Martin=20Schr=C3=B6der?= Date: Mon, 9 Dec 2019 20:05:11 +0100 Subject: [PATCH 09/10] Revert divergence from #29938 --- pandas/util/testing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index e39759df3618a..bada31a5dcd51 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1521,7 +1521,7 @@ def assert_sp_array_equal( def assert_contains_all(iterable, dic): for k in iterable: - assert k in dic, f"Did not contain item: '{k!r}'" + assert k in dic, f"Did not contain item: {repr(k)}" def assert_copy(iter1, iter2, **eql_kwargs): From b584a9263ca0144e9c47df823e9523900b60c915 Mon Sep 17 00:00:00 2001 From: Joris Van den Bossche Date: Mon, 6 Jan 2020 21:43:42 +0100 Subject: [PATCH 10/10] flake8 --- pandas/_testing.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/pandas/_testing.py b/pandas/_testing.py index 195b59627326b..2050a18cb48bf 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -825,7 +825,7 @@ def assert_categorical_equal( if check_category_order: assert_index_equal(left.categories, right.categories, obj=f"{obj}.categories") assert_numpy_array_equal( - left.codes, right.codes, check_dtype=check_dtype, obj=f"{obj}.codes" + left.codes, right.codes, check_dtype=check_dtype, obj=f"{obj}.codes", ) else: assert_index_equal( @@ -965,7 +965,7 @@ def _raise(left, right, err_msg): if err_msg is None: if left.shape != right.shape: raise_assert_detail( - obj, f"{obj} shapes are different", left.shape, right.shape + obj, f"{obj} shapes are different", left.shape, right.shape, ) diff = 0 @@ -1149,7 +1149,10 @@ def assert_series_equal( # datetimelike may have different objects (e.g. datetime.datetime # vs Timestamp) but will compare equal if not Index(left.values).equals(Index(right.values)): - msg = f"[datetimelike_compat=True] {left.values} is not equal to {right.values}." + msg = ( + f"[datetimelike_compat=True] {left.values} " + f"is not equal to {right.values}." + ) raise AssertionError(msg) else: assert_numpy_array_equal( @@ -1306,7 +1309,7 @@ def assert_frame_equal( # shape comparison if left.shape != right.shape: raise_assert_detail( - obj, f"{obj} shape mismatch", f"{repr(left.shape)}", f"{repr(right.shape)}" + obj, f"{obj} shape mismatch", f"{repr(left.shape)}", f"{repr(right.shape)}", ) if check_like: @@ -2474,7 +2477,10 @@ class for all warnings. To check that no warning is returned, ) ) if expected_warning: - msg = f"Did not see expected warning of class {repr(expected_warning.__name__)}" + msg = ( + f"Did not see expected warning of class " + f"{repr(expected_warning.__name__)}" + ) assert saw_warning, msg if raise_on_extra_warnings and extra_warnings: raise AssertionError(