Commit e966b871 authored by Jason Madden's avatar Jason Madden

More warning cleanup.

parent 85638668
...@@ -23,3 +23,6 @@ else: ...@@ -23,3 +23,6 @@ else:
print('ls: %r' % p2.stdout.read()) print('ls: %r' % p2.stdout.read())
else: else:
print('ls: job is still running') print('ls: job is still running')
p1.stdout.close()
p2.stdout.close()
...@@ -46,6 +46,18 @@ else: ...@@ -46,6 +46,18 @@ else:
reraise = reraise # export reraise = reraise # export
exc_clear = sys.exc_clear exc_clear = sys.exc_clear
## import locks
try:
# In Python 3.4 and newer in CPython and PyPy3,
# imp.acquire_lock and imp.release_lock are delegated to
# '_imp'. (Which is also used by importlib.) 'imp' itself is
# deprecated. Avoid that warning.
import _imp as imp
except ImportError:
import imp
imp_acquire_lock = imp.acquire_lock
imp_release_lock = imp.release_lock
## Functions ## Functions
if PY3: if PY3:
iteritems = dict.items iteritems = dict.items
......
...@@ -9,12 +9,14 @@ ...@@ -9,12 +9,14 @@
from __future__ import absolute_import, print_function from __future__ import absolute_import, print_function
import imp
import importlib import importlib
import sys import sys
from gevent._compat import PY3 from gevent._compat import PY3
from gevent._compat import iteritems from gevent._compat import iteritems
from gevent._compat import imp_acquire_lock
from gevent._compat import imp_release_lock
from gevent.builtins import __import__ as _import from gevent.builtins import __import__ as _import
...@@ -92,10 +94,10 @@ class _SysModulesPatcher(object): ...@@ -92,10 +94,10 @@ class _SysModulesPatcher(object):
try: try:
self._restore() self._restore()
finally: finally:
imp.release_lock() imp_release_lock()
def __enter__(self): def __enter__(self):
imp.acquire_lock() imp_acquire_lock()
self._save() self._save()
self._replace() self._replace()
......
...@@ -2,10 +2,13 @@ ...@@ -2,10 +2,13 @@
"""gevent friendly implementations of builtin functions.""" """gevent friendly implementations of builtin functions."""
from __future__ import absolute_import from __future__ import absolute_import
import imp # deprecated since 3.4; issues PendingDeprecationWarning in 3.5
import sys import sys
import weakref import weakref
from gevent.lock import RLock from gevent.lock import RLock
from gevent._compat import imp_acquire_lock
from gevent._compat import imp_release_lock
# Normally we'd have the "expected" case inside the try # Normally we'd have the "expected" case inside the try
# (Python 3, because Python 3 is the way forward). But # (Python 3, because Python 3 is the way forward). But
...@@ -86,7 +89,7 @@ def __import__(*args, **kwargs): ...@@ -86,7 +89,7 @@ def __import__(*args, **kwargs):
return _import(*args, **kwargs) return _import(*args, **kwargs)
module_lock = __module_lock(args[0]) # Get a lock for the module name module_lock = __module_lock(args[0]) # Get a lock for the module name
imp.acquire_lock() imp_acquire_lock()
try: try:
module_lock.acquire() module_lock.acquire()
try: try:
...@@ -94,7 +97,7 @@ def __import__(*args, **kwargs): ...@@ -94,7 +97,7 @@ def __import__(*args, **kwargs):
finally: finally:
module_lock.release() module_lock.release()
finally: finally:
imp.release_lock() imp_release_lock()
return result return result
......
...@@ -15,6 +15,7 @@ from greentest.util import log ...@@ -15,6 +15,7 @@ from greentest.util import log
from greentest.sysinfo import RUNNING_ON_CI from greentest.sysinfo import RUNNING_ON_CI
from greentest.sysinfo import PYPY from greentest.sysinfo import PYPY
from greentest.sysinfo import PY3 from greentest.sysinfo import PY3
from greentest.sysinfo import PY2
from greentest.sysinfo import RESOLVER_ARES from greentest.sysinfo import RESOLVER_ARES
from greentest.sysinfo import LIBUV from greentest.sysinfo import LIBUV
from greentest import six from greentest import six
...@@ -225,7 +226,11 @@ def discover(tests=None, ignore_files=None, ...@@ -225,7 +226,11 @@ def discover(tests=None, ignore_files=None,
continue continue
to_process.append((cmd, options)) to_process.append((cmd, options))
else: else:
cmd = [sys.executable, '-u', filename] cmd = [sys.executable, '-u']
if PYPY and PY2:
# Doesn't seem to be an env var for this
cmd.extend(('-X', 'track-resources'))
cmd.append(filename)
options = DEFAULT_RUN_OPTIONS.copy() options = DEFAULT_RUN_OPTIONS.copy()
options.update(TEST_FILE_OPTIONS.get(filename, {})) options.update(TEST_FILE_OPTIONS.get(filename, {}))
to_process.append((cmd, options)) to_process.append((cmd, options))
...@@ -327,6 +332,42 @@ def print_list(lst): ...@@ -327,6 +332,42 @@ def print_list(lst):
for name in lst: for name in lst:
log(' - %s', name) log(' - %s', name)
def _setup_environ():
if 'PYTHONWARNINGS' not in os.environ and not sys.warnoptions:
# Enable default warnings such as ResourceWarning.
# On Python 3[.6], the system site.py module has
# "open(fullname, 'rU')" which produces the warning that
# 'U' is deprecated, so ignore warnings from site.py
# importlib/_bootstrap.py likes to spit out "ImportWarning:
# can't resolve package from __spec__ or __package__, falling
# back on __name__ and __path__". I have no idea what that means, but it seems harmless
# and is annoying.
os.environ['PYTHONWARNINGS'] = 'default,ignore:::site:,ignore:::importlib._bootstrap:,ignore:::importlib._bootstrap_external:'
if 'PYTHONFAULTHANDLER' not in os.environ:
os.environ['PYTHONFAULTHANDLER'] = 'true'
if 'GEVENT_DEBUG' not in os.environ:
os.environ['GEVENT_DEBUG'] = 'debug'
if 'PYTHONTRACEMALLOC' not in os.environ:
os.environ['PYTHONTRACEMALLOC'] = '10'
if 'PYTHONDEVMODE' not in os.environ:
# Python 3.7
os.environ['PYTHONDEVMODE'] = '1'
if 'PYTHONMALLOC' not in os.environ:
# Python 3.6
os.environ['PYTHONMALLOC'] = 'debug'
if (sys.version_info == (3, 7, 0, 'beta', 2)
and (os.environ.get("PYTHONDEVMODE") or os.environ.get('PYTHONMALLOC'))):
# See https://twitter.com/ossmkitty/status/970693025130311680
# https://bugs.python.org/issue33005
os.environ.pop('PYTHONDEVMODE', None)
os.environ.pop('PYTHONMALLOC', None)
def main(): def main():
import argparse import argparse
...@@ -357,32 +398,7 @@ def main(): ...@@ -357,32 +398,7 @@ def main():
os.environ['COVERAGE_FILE'] = os.path.abspath(".") + os.sep + ".coverage" os.environ['COVERAGE_FILE'] = os.path.abspath(".") + os.sep + ".coverage"
print("Enabling coverage to", os.environ['COVERAGE_FILE']) print("Enabling coverage to", os.environ['COVERAGE_FILE'])
_setup_environ()
if 'PYTHONWARNINGS' not in os.environ and not sys.warnoptions:
# Enable default warnings such as ResourceWarning.
# On Python 3[.6], the system site.py module has
# "open(fullname, 'rU')" which produces the warning that
# 'U' is deprecated, so ignore warnings from site.py
# importlib/_bootstrap.py likes to spit out "ImportWarning:
# can't resolve package from __spec__ or __package__, falling
# back on __name__ and __path__". I have no idea what that means, but it seems harmless
# and is annoying.
os.environ['PYTHONWARNINGS'] = 'default,ignore:::site:,ignore:::importlib._bootstrap:,ignore:::importlib._bootstrap_external:'
if 'PYTHONFAULTHANDLER' not in os.environ:
os.environ['PYTHONFAULTHANDLER'] = 'true'
if 'GEVENT_DEBUG' not in os.environ:
os.environ['GEVENT_DEBUG'] = 'debug'
if 'PYTHONTRACEMALLOC' not in os.environ:
os.environ['PYTHONTRACEMALLOC'] = '10'
if 'PYTHONDEVMODE' not in os.environ:
# Python 3.7
os.environ['PYTHONDEVMODE'] = '1'
if options.config: if options.config:
config = {} config = {}
......
...@@ -170,7 +170,27 @@ class RunResult(object): ...@@ -170,7 +170,27 @@ class RunResult(object):
return self.code return self.code
lock = threading.Lock() def _should_show_warning_output(out):
if b'Warning' in out:
# Strip out some patterns we specifically do not
# care about.
# from test.support for monkey-patched tests
out = out.replace(b'Warning -- reap_children', b'NADA')
out = out.replace(b"Warning -- threading_cleanup", b'NADA')
# The below *could* be done with sophisticated enough warning
# filters passed to the children
# collections.abc is the new home; setuptools uses the old one,
# as does dnspython
out = out.replace(b"DeprecationWarning: Using or importing the ABCs", b'NADA')
# libuv poor timer resolution
out = out.replace(b'UserWarning: libuv only supports', b'NADA')
# Packages on Python 2
out = out.replace(b'ImportWarning: Not importing directory', b'NADA')
return b'Warning' in out
output_lock = threading.Lock()
def run(command, **kwargs): def run(command, **kwargs):
...@@ -195,9 +215,9 @@ def run(command, **kwargs): ...@@ -195,9 +215,9 @@ def run(command, **kwargs):
finally: finally:
kill(popen) kill(popen)
assert not err assert not err
with lock: # pylint:disable=not-context-manager with output_lock: # pylint:disable=not-context-manager
failed = bool(result) failed = bool(result)
if out and (failed or verbose or b'ResourceWarning' in out): if out and (failed or verbose or _should_show_warning_output(out)):
out = out.strip().decode('utf-8', 'ignore') out = out.strip().decode('utf-8', 'ignore')
if out: if out:
out = ' ' + out.replace('\n', '\n ') out = ' ' + out.replace('\n', '\n ')
......
...@@ -241,14 +241,6 @@ if sys.version_info[:2] >= (3, 4) and APPVEYOR: ...@@ -241,14 +241,6 @@ if sys.version_info[:2] >= (3, 4) and APPVEYOR:
'FLAKY test_selectors.py' 'FLAKY test_selectors.py'
] ]
if sys.version_info == (3, 7, 0, 'beta', 2) and os.environ.get("PYTHONDEVMODE"):
# These crash when in devmode.
# See https://twitter.com/ossmkitty/status/970693025130311680
# https://bugs.python.org/issue33005
FAILING_TESTS += [
'test__monkey_sigchld_2.py',
'test__monkey_sigchld_3.py'
]
if COVERAGE: if COVERAGE:
# The gevent concurrency plugin tends to slow things # The gevent concurrency plugin tends to slow things
......
...@@ -12,6 +12,12 @@ from greentest.sysinfo import PY3 ...@@ -12,6 +12,12 @@ from greentest.sysinfo import PY3
from greentest.flaky import reraiseFlakyTestRaceConditionLibuv from greentest.flaky import reraiseFlakyTestRaceConditionLibuv
from greentest.skipping import skipOnLibuvOnCIOnPyPy from greentest.skipping import skipOnLibuvOnCIOnPyPy
try:
ResourceWarning
except NameError:
class ResourceWarning(Warning):
"Python 2 fallback"
class Test(greentest.TestCase): class Test(greentest.TestCase):
...@@ -38,8 +44,12 @@ class Test(greentest.TestCase): ...@@ -38,8 +44,12 @@ class Test(greentest.TestCase):
import traceback import traceback
traceback.print_exc() traceback.print_exc()
del s # Deliberately getting ResourceWarning with FileObject(Thread) under Py3 import warnings
gc.collect() # PyPy with warnings.catch_warnings():
warnings.simplefilter('ignore', ResourceWarning)
# Deliberately getting ResourceWarning with FileObject(Thread) under Py3
del s
gc.collect() # PyPy
if kwargs.get("close", True): if kwargs.get("close", True):
with self.assertRaises((OSError, IOError)): with self.assertRaises((OSError, IOError)):
...@@ -71,11 +81,16 @@ class Test(greentest.TestCase): ...@@ -71,11 +81,16 @@ class Test(greentest.TestCase):
self._test_del(close=False) self._test_del(close=False)
def test_newlines(self): def test_newlines(self):
import warnings
r, w = os.pipe() r, w = os.pipe()
lines = [b'line1\n', b'line2\r', b'line3\r\n', b'line4\r\nline5', b'\nline6'] lines = [b'line1\n', b'line2\r', b'line3\r\n', b'line4\r\nline5', b'\nline6']
g = gevent.spawn(writer, FileObject(w, 'wb'), lines) g = gevent.spawn(writer, FileObject(w, 'wb'), lines)
try: try:
fobj = FileObject(r, 'rU') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
# U is deprecated in Python 3, shows up on FileObjectThread
fobj = FileObject(r, 'rU')
result = fobj.read() result = fobj.read()
fobj.close() fobj.close()
self.assertEqual('line1\nline2\nline3\nline4\nline5\nline6', result) self.assertEqual('line1\nline2\nline3\nline4\nline5\nline6', result)
......
...@@ -45,7 +45,8 @@ if hasattr(signal, 'SIGCHLD'): ...@@ -45,7 +45,8 @@ if hasattr(signal, 'SIGCHLD'):
popen.stderr.read() popen.stderr.read()
popen.stdout.read() popen.stdout.read()
popen.wait() # This hangs if it doesn't. popen.wait() # This hangs if it doesn't.
popen.stderr.close()
popen.stdout.close()
sys.exit(0) sys.exit(0)
else: else:
print("No SIGCHLD, not testing") print("No SIGCHLD, not testing")
...@@ -27,10 +27,7 @@ python_universal_newlines = hasattr(sys.stdout, 'newlines') ...@@ -27,10 +27,7 @@ python_universal_newlines = hasattr(sys.stdout, 'newlines')
# The stdlib of Python 3 on Windows doesn't properly handle universal newlines # The stdlib of Python 3 on Windows doesn't properly handle universal newlines
# (it produces broken results compared to Python 2) # (it produces broken results compared to Python 2)
# See gevent.subprocess for more details. # See gevent.subprocess for more details.
if PY3 and subprocess.mswindows: python_universal_newlines_broken = PY3 and subprocess.mswindows
python_universal_newlines_broken = True
else:
python_universal_newlines_broken = False
class Test(greentest.TestCase): class Test(greentest.TestCase):
...@@ -61,6 +58,7 @@ class Test(greentest.TestCase): ...@@ -61,6 +58,7 @@ class Test(greentest.TestCase):
p = subprocess.Popen([sys.executable, "-c", "print()"], p = subprocess.Popen([sys.executable, "-c", "print()"],
stdout=subprocess.PIPE) stdout=subprocess.PIPE)
p.wait() p.wait()
p.stdout.close()
del p del p
if PYPY: if PYPY:
gc.collect() gc.collect()
...@@ -206,7 +204,7 @@ class Test(greentest.TestCase): ...@@ -206,7 +204,7 @@ class Test(greentest.TestCase):
os.close(w) os.close(w)
def test_issue148(self): def test_issue148(self):
for i in range(7): for _ in range(7):
try: try:
subprocess.Popen('this_name_must_not_exist') subprocess.Popen('this_name_must_not_exist')
except OSError as ex: except OSError as ex:
......
...@@ -372,20 +372,24 @@ class ThreadTests(unittest.TestCase): ...@@ -372,20 +372,24 @@ class ThreadTests(unittest.TestCase):
# Try hard to trigger #1703448: a thread is still returned in # Try hard to trigger #1703448: a thread is still returned in
# threading.enumerate() after it has been join()ed. # threading.enumerate() after it has been join()ed.
enum = threading.enumerate enum = threading.enumerate
old_interval = sys.getcheckinterval() import warnings
try: with warnings.catch_warnings():
for i in xrange(1, 100): warnings.simplefilter('ignore', DeprecationWarning)
# Try a couple times at each thread-switching interval # get/set checkinterval are deprecated in Python 3
# to get more interleavings. old_interval = sys.getcheckinterval()
sys.setcheckinterval(i // 5) try:
t = threading.Thread(target=lambda: None) for i in xrange(1, 100):
t.start() # Try a couple times at each thread-switching interval
t.join() # to get more interleavings.
l = enum() sys.setcheckinterval(i // 5)
self.assertFalse(t in l, t = threading.Thread(target=lambda: None)
"#1703448 triggered after %d trials: %s" % (i, l)) t.start()
finally: t.join()
sys.setcheckinterval(old_interval) l = enum()
self.assertFalse(t in l,
"#1703448 triggered after %d trials: %s" % (i, l))
finally:
sys.setcheckinterval(old_interval)
if not hasattr(sys, 'pypy_version_info'): if not hasattr(sys, 'pypy_version_info'):
def test_no_refcycle_through_target(self): def test_no_refcycle_through_target(self):
...@@ -436,6 +440,7 @@ class ThreadJoinOnShutdown(unittest.TestCase): ...@@ -436,6 +440,7 @@ class ThreadJoinOnShutdown(unittest.TestCase):
p = subprocess.Popen([sys.executable, "-W", "ignore", "-c", script], stdout=subprocess.PIPE) p = subprocess.Popen([sys.executable, "-W", "ignore", "-c", script], stdout=subprocess.PIPE)
rc = p.wait() rc = p.wait()
data = p.stdout.read().replace(b'\r', b'') data = p.stdout.read().replace(b'\r', b'')
p.stdout.close()
self.assertEqual(data, b"end of main\nend of thread\n") self.assertEqual(data, b"end of main\nend of thread\n")
self.assertNotEqual(rc, 2, b"interpreter was blocked") self.assertNotEqual(rc, 2, b"interpreter was blocked")
self.assertEqual(rc, 0, b"Unexpected error") self.assertEqual(rc, 0, b"Unexpected error")
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment