Wrapper for asserting warnings, optionally with pattern matching. Can be used as context manager or with callable: with assert_warns(UserWarning): warnings.warn("test", UserWarning) assert_warns(UserWarning, callable, arg1, arg2, kwarg=value)
(exception=Warning, *args, glob=None, regex=None, match_case=None, **kwargs)
| 134 | |
| 135 | |
| 136 | def assert_warns(exception=Warning, *args, glob=None, regex=None, match_case=None, **kwargs): |
| 137 | """ |
| 138 | Wrapper for asserting warnings, optionally with pattern matching. |
| 139 | |
| 140 | Can be used as context manager or with callable: |
| 141 | with assert_warns(UserWarning): |
| 142 | warnings.warn("test", UserWarning) |
| 143 | |
| 144 | assert_warns(UserWarning, callable, arg1, arg2, kwarg=value) |
| 145 | """ |
| 146 | if glob is None and regex is None: |
| 147 | # Use unittest's assertWarns |
| 148 | if args: |
| 149 | # Called with callable |
| 150 | callable_func = args[0] |
| 151 | callable_args = args[1:] |
| 152 | with _test_case.assertWarns(exception): |
| 153 | callable_func(*callable_args, **kwargs) |
| 154 | else: |
| 155 | # Used as context manager |
| 156 | return _test_case.assertWarns(exception) |
| 157 | else: |
| 158 | pattern = get_pattern(glob, regex, match_case) |
| 159 | # Use unittest's assertWarnsRegex |
| 160 | if args: |
| 161 | # Called with callable |
| 162 | callable_func = args[0] |
| 163 | callable_args = args[1:] |
| 164 | with _test_case.assertWarnsRegex(exception, pattern): |
| 165 | callable_func(*callable_args, **kwargs) |
| 166 | else: |
| 167 | # Used as context manager |
| 168 | return _test_case.assertWarnsRegex(exception, pattern) |
| 169 | |
| 170 | |
| 171 | def raises(exception, glob=None, regex=None, match_case=None): |