Skip to content

Instantly share code, notes, and snippets.

@elyezer
Created April 5, 2017 19:16
Show Gist options
  • Save elyezer/a973eee50a8b192e19e9d4f183ad21d4 to your computer and use it in GitHub Desktop.
Save elyezer/a973eee50a8b192e19e9d4f183ad21d4 to your computer and use it in GitHub Desktop.
Sample code written by @Ichimonji10 to play around with warning suppression behaviour.
# coding=utf-8
"""Play around with warning suppression behaviour.
The standard library's unittest test runner prepends the following rules to
``warnings.filters`` before a test method executes:
.. code-block:: python
('module', re.compile('Please use assert\\w+ instead.', re.IGNORECASE), <class 'DeprecationWarning'>, re.compile(''), 0),
('default', None, <class 'Warning'>, None, 0),
The second rule is important. First, notice that the rule has an action of
"default," which will "print the first occurrence of matching warnings for each
location where the warning is issued." Second, notice the class of "Warning,"
which is a parent class of
``requests.packages.urllib3.exceptions.DependencyWarning``:
.. code-block:: python
inspect.getmro(requests.packages.urllib3.exceptions.DependencyWarning)
(
<class 'requests.packages.urllib3.exceptions.DependencyWarning'>,
<class 'requests.packages.urllib3.exceptions.HTTPWarning'>,
<class 'Warning'>,
<class 'Exception'>,
<class 'BaseException'>,
<class 'object'>
)
"""
import unittest
import warnings
from pprint import pprint
import requests
def print_filters(label):
print(label)
pprint(warnings.filters)
print()
print()
# This filter goes to the stop of the filters stack.
warnings.simplefilter(
'ignore',
requests.packages.urllib3.exceptions.InsecureRequestWarning,
)
print_filters('in test_foo/test_unit.py:')
class MyTestCase(unittest.TestCase):
"""Test an insecure HTTPS request."""
def test_my_request(self):
"""Make an insecure HTTPS request."""
# The filter is now buried under the rules added by unittest.
print_filters('in test_foo/test_unit.py::MyTestCase.test_my_request:')
# This brings our filter back to the top of the stack of rules.
warnings.simplefilter(
'ignore',
requests.packages.urllib3.exceptions.InsecureRequestWarning,
)
print_filters('in test_foo/test_unit.py::MyTestCase.test_my_request:')
requests.get('https://fedora-24-pulp-2-12/pulp/api/v2', verify=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment