Debian Codegraph @

pypy/module/_warnings/test/apptest_warnings.py

raw symbols SCIP
1 # spaceconfig = {"usemodules": ["_warnings"]}
2 import pytest
3
4 import warnings
5 import _warnings
6
7 import io
8 import os
9 import sys
10
11 def test_defaults():
12 assert _warnings._onceregistry == {}
13 assert _warnings._defaultaction == 'default'
14 expected = [('default', None, DeprecationWarning, '__main__', 0),
15 ('ignore', None, DeprecationWarning, None, 0),
16 ('ignore', None, PendingDeprecationWarning, None, 0),
17 ('ignore', None, ImportWarning, None, 0),
18 ('ignore', None, ResourceWarning, None, 0)]
19 try:
20 import pkg_resources
21 except:
22 pass
23 if len(_warnings.filters) == 6:
24 expected.append(('ignore', None, pkg_resources.PEP440Warning, None, 0))
25 assert _warnings.filters == expected
26
27 def test_warn():
28 with warnings.catch_warnings(record=True) as log:
29 _warnings.warn("some message", DeprecationWarning)
30 _warnings.warn("some message", Warning)
31 _warnings.warn(("some message",1), Warning)
32
33 def test_use_builtin__warnings():
34 """Check that the stdlib warnings.py module manages to import our
35 _warnings module. If something is missing, it doesn't, and silently
36 continues. Then things don't reliably work: either the
37 functionality of the pure Python version is subtly different, or
38 more likely we get confusion because of a half-imported _warnings.
39 """
40 assert not hasattr(warnings, '_filters_version')
41
42 def test_lineno():
43 with warnings.catch_warnings(record=True) as w:
44 _warnings.warn("some message", Warning)
45 lineno = sys._getframe().f_lineno - 1 # the line above
46 assert w[-1].lineno == lineno
47
48 def test_warn_explicit():
49 with warnings.catch_warnings(record=True) as log:
50 _warnings.warn_explicit("some message", DeprecationWarning,
51 "<string>", 1, module_globals=globals())
52 _warnings.warn_explicit("some message", Warning,
53 "<string>", 1, module_globals=globals())
54
55 def test_with_source():
56 source = []
57 with warnings.catch_warnings(record=True) as w:
58 _warnings.warn("some message", Warning, source=source)
59 assert w[0].source is source
60
61 def test_default_action():
62 warnings.defaultaction = 'ignore'
63 warnings.resetwarnings()
64 with warnings.catch_warnings(record=True) as w:
65 _warnings.warn_explicit("message", UserWarning, "<test>", 44,
66 registry={})
67 assert len(w) == 0
68 warnings.defaultaction = 'default'
69
70 def test_ignore():
71 warnings.resetwarnings()
72 with warnings.catch_warnings(record=True) as w:
73 __warningregistry__ = {}
74 warnings.filterwarnings("ignore", category=UserWarning)
75 _warnings.warn_explicit("message", UserWarning, "<test>", 44,
76 registry=__warningregistry__)
77 assert len(w) == 0
78 assert list(__warningregistry__) == ['version']
79
80 def test_show_source_line():
81 # Something is wrong with pytest > 4.0.0 (which is the version run for -D
82 # pypy tests: it cannot redirect sys.stderr
83 if getattr(pytest, "__version__", "untranslated")[0] >= '4':
84 pytest.skip("fails on this version of pytest")
85
86 def inner(message, stacklevel=1):
87 warnings.warn(message, stacklevel=stacklevel)
88
89 # With showarning() missing, make sure that output is okay.
90 saved = warnings.showwarning
91 try:
92 del warnings.showwarning
93
94 stderr = sys.stderr
95 try:
96 sys.stderr = io.StringIO()
97 inner('test message')
98 result = sys.stderr.getvalue()
99 finally:
100 sys.stderr = stderr
101
102 assert result.count('\n') == 2
103 assert ' warnings.warn(message, ' in result
104 finally:
105 warnings.showwarning = saved
106
107
108 def test_filename_none():
109 with warnings.catch_warnings(record=True) as log:
110 globals()['__file__'] = 'test.pyc'
111 _warnings.warn('test', UserWarning)
112 globals()['__file__'] = None
113 _warnings.warn('test', UserWarning)
114 assert len(log) == 2
115
116
117 def test_warn_unicode():
118 # Something is wrong with pytest > 4.0.0 (which is the version run for -D
119 # pypy tests: it cannot redirect sys.stderr
120 if getattr(pytest, "__version__", "untranslated")[0] >= '4':
121 pytest.skip("fails on this version of pytest")
122
123 old = sys.stderr, warnings.showwarning
124 with warnings.catch_warnings(record=True) as log:
125 try:
126 class Grab:
127 def write(self, u):
128 self.data.append(u)
129 sys.stderr = Grab()
130 sys.stderr.data = data = []
131 if sys.version_info > (3, 0, 0):
132 # Copy from lib-python/3/warnings.py
133 def orig_showwarning(message, category, filename, lineno, file=None, line=None):
134 msg = warnings.WarningMessage(message, category, filename, lineno, file, line)
135 warnings._showwarnmsg_impl(msg)
136 warnings.showwarning = orig_showwarning
137 _unicode = str
138 else:
139 warnings.showwarning = warnings._show_warning
140 _unicode = unicode
141 # ^^^ disables any catch_warnings() issued by the test runner
142 _warnings.warn_explicit("9238exbexn8", Warning,
143 "<string>", 1421, module_globals=globals())
144 assert data # the warning was not swallowed
145 assert isinstance(''.join(data), str)
146 _warnings.warn_explicit(u"\u1234\u5678", UserWarning,
147 "<str2>", 831, module_globals=globals())
148 assert isinstance(''.join(data), _unicode)
149 assert ''.join(data).endswith(
150 u'<str2>:831: UserWarning: \u1234\u5678\n')
151 finally:
152 sys.stderr, warnings.showwarning = old
153 assert len(log) == 5
154
155
156 def test_bad_category():
157 with raises(TypeError):
158 _warnings.warn("text", 123)
159
160 class Foo:
161 pass
162 with raises(TypeError):
163 _warnings.warn("text", Foo)
164
165
166 def test_surrogate_in_filename():
167 with warnings.catch_warnings(record=True) as log:
168 for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
169 try:
170 os.fsencode(filename)
171 except UnicodeEncodeError:
172 continue
173 _warnings.warn_explicit("text", UserWarning, filename, 1)
174 assert len(log) == 2
175
176
177 def test_issue31285():
178 def get_bad_loader(splitlines_ret_val):
179 class BadLoader:
180 def get_source(self, fullname):
181 class BadSource(str):
182 def splitlines(self):
183 return splitlines_ret_val
184 return BadSource('spam')
185 return BadLoader()
186 # does not raise:
187 with warnings.catch_warnings(record=True) as log:
188 _warnings.warn_explicit(
189 'eggs', UserWarning, 'bar', 1,
190 module_globals={'__loader__': get_bad_loader(42),
191 '__name__': 'foobar'})
192 assert len(log) == 1
193
194 def test_once_is_not_broken():
195 def f():
196 warnings.warn("deprecated", DeprecationWarning, 2)
197
198 with warnings.catch_warnings(record=True) as w:
199 warnings.simplefilter("once")
200 assert len(w) == 0
201 f()
202 assert len(w) == 1
203 f()
204 assert len(w) == 1
205 f()
206 assert len(w) == 1
207
208 def test_filename_from_code():
209 f = eval("lambda: warnings.warn('foo')")
210 with warnings.catch_warnings(record=True) as w:
211 assert len(w) == 0
212 f()
213 print(w[0].__dict__)
214 assert len(w) == 1
215 assert w[0].filename == "<string>"