Skip to content

Commit 57ecd38

Browse files
committed
add context manager for failed tests
1 parent 35be479 commit 57ecd38

File tree

3 files changed

+58
-5
lines changed

3 files changed

+58
-5
lines changed

fastcore/_nbdev.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"TEST_IMAGE": "00_test.ipynb",
1818
"TEST_IMAGE_BW": "00_test.ipynb",
1919
"test_fig_exists": "00_test.ipynb",
20+
"TestFail": "00_test.ipynb",
2021
"defaults": "01_foundation.ipynb",
2122
"copy_func": "01_foundation.ipynb",
2223
"patch_to": "01_foundation.ipynb",

fastcore/test.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_test.ipynb (unless otherwise specified).
22

33
__all__ = ['test_fail', 'test', 'nequals', 'test_eq', 'test_eq_type', 'test_ne', 'is_close', 'test_close', 'test_is',
4-
'test_shuffled', 'test_stdout', 'test_warns', 'TEST_IMAGE', 'TEST_IMAGE_BW', 'test_fig_exists']
4+
'test_shuffled', 'test_stdout', 'test_warns', 'TEST_IMAGE', 'TEST_IMAGE_BW', 'test_fig_exists', 'TestFail']
55

66
# Cell
77
from .imports import *
8+
from .utils import *
89
from collections import Counter
910
from contextlib import redirect_stdout
1011

@@ -95,4 +96,16 @@ def test_warns(f, show=False):
9596
# Cell
9697
def test_fig_exists(ax):
9798
"Test there is a figure displayed in `ax`"
98-
assert ax and len(ax.figure.canvas.tostring_argb())
99+
assert ax and len(ax.figure.canvas.tostring_argb())
100+
101+
# Cell
102+
class TestFail():
103+
"A context manager to allow you to test if an exception (e) is raised. Optionally, search the exception's error message with regex."
104+
def __init__(self, ex:Exception, regex:str=None):store_attr()
105+
def __enter__(self): pass
106+
def __exit__(self, type, value, traceback):
107+
if isinstance(value, self.ex):
108+
if self.regex:
109+
assert re.search(self.regex, ' '.join(value.args)) is not None, f"Did not find regex:{self.regex} in Exception message."
110+
return True
111+
else: raise TypeError(f"An error of {self.ex} was not raised.")

nbs/00_test.ipynb

Lines changed: 42 additions & 3 deletions
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)