diff options
author | Christoph Reiter <creiter@src.gnome.org> | 2015-06-18 13:36:52 +0200 |
---|---|---|
committer | Christoph Reiter <creiter@src.gnome.org> | 2015-07-02 20:50:20 +0200 |
commit | fea15145c2a3e6aac73350241a982a095e16c7d8 (patch) | |
tree | 24a94006c93409178457c8ab91ffd637c47fcd1a /tests | |
parent | 619777730891b42b98da556c3aa9ca5a1b3f617b (diff) | |
download | pygobject-fea15145c2a3e6aac73350241a982a095e16c7d8.tar.gz |
tests: Silence various error messages and warnings.
This silences glib warnings which are due to testing
of error handling, deprecation warnings which we ignore
since we want to continue testing deprecated code and
other error output of code which is supposed to fail.
To reduce code duplication and make things easier
this introduces a shared helper module containing
various context managers and decorators which allow
testing and silencing of warnings and errors.
https://bugzilla.gnome.org/show_bug.cgi?id=751156
Diffstat (limited to 'tests')
-rw-r--r-- | tests/Makefile.am | 1 | ||||
-rw-r--r-- | tests/compat_test_pygtk.py | 27 | ||||
-rw-r--r-- | tests/compathelper.py | 8 | ||||
-rw-r--r-- | tests/helper.py | 132 | ||||
-rw-r--r-- | tests/test_everything.py | 28 | ||||
-rw-r--r-- | tests/test_gi.py | 6 | ||||
-rw-r--r-- | tests/test_gio.py | 3 | ||||
-rw-r--r-- | tests/test_iochannel.py | 20 | ||||
-rw-r--r-- | tests/test_overrides_gdk.py | 18 | ||||
-rw-r--r-- | tests/test_overrides_gtk.py | 20 | ||||
-rw-r--r-- | tests/test_properties.py | 21 | ||||
-rw-r--r-- | tests/test_repository.py | 13 | ||||
-rw-r--r-- | tests/test_signal.py | 24 | ||||
-rw-r--r-- | tests/test_source.py | 8 |
14 files changed, 231 insertions, 98 deletions
diff --git a/tests/Makefile.am b/tests/Makefile.am index 07eae975..b36ff519 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -75,6 +75,7 @@ testhelper.la: $(testhelper_la_OBJECTS) $(testhelper_la_DEPENDENCIES) all: $(check_LTLIBRARIES:.la=.$(OS_EXT)) EXTRA_DIST = \ + helper.py \ compathelper.py \ runtests.py \ runtests-windows.py \ diff --git a/tests/compat_test_pygtk.py b/tests/compat_test_pygtk.py index b2e7a111..dbe3c9ae 100644 --- a/tests/compat_test_pygtk.py +++ b/tests/compat_test_pygtk.py @@ -2,11 +2,9 @@ # vim: tabstop=4 shiftwidth=4 expandtab import unittest -import contextlib import base64 import gi -from gi.repository import GLib try: try: @@ -32,14 +30,7 @@ try: except ImportError: Gtk = None - -@contextlib.contextmanager -def ignore_glib_warnings(): - """Temporarily change GLib logging to not bail on warnings.""" - old_mask = GLib.log_set_always_fatal( - GLib.LogLevelFlags.LEVEL_CRITICAL | GLib.LogLevelFlags.LEVEL_ERROR) - yield - GLib.log_set_always_fatal(old_mask) +from helper import capture_gi_deprecation_warnings, capture_glib_warnings @unittest.skipUnless(Gtk, 'Gtk not available') @@ -81,12 +72,13 @@ class TestGTKCompat(unittest.TestCase): def test_style(self): widget = gtk.Button() - self.assertTrue(isinstance(widget.style.base[gtk.STATE_NORMAL], - gtk.gdk.Color)) + with capture_gi_deprecation_warnings(): + self.assertTrue(isinstance(widget.style.base[gtk.STATE_NORMAL], + gtk.gdk.Color)) def test_alignment(self): # Creation of pygtk.Alignment causes hard warnings, ignore this in testing. - with ignore_glib_warnings(): + with capture_glib_warnings(allow_warnings=True): a = gtk.Alignment() self.assertEqual(a.props.xalign, 0.0) @@ -119,12 +111,8 @@ class TestGTKCompat(unittest.TestCase): liststore.append((2, 'Two')) liststore.append((3, 'Three')) # might cause a Pango warning, do not break on this - old_mask = GLib.log_set_always_fatal( - GLib.LogLevelFlags.LEVEL_CRITICAL | GLib.LogLevelFlags.LEVEL_ERROR) - try: + with capture_glib_warnings(allow_warnings=True): combo = gtk.ComboBoxEntry(model=liststore) - finally: - GLib.log_set_always_fatal(old_mask) combo.set_text_column(1) combo.set_active(0) self.assertEqual(combo.get_text_column(), 1) @@ -143,7 +131,8 @@ class TestGTKCompat(unittest.TestCase): def test_size_request(self): box = gtk.Box() - self.assertEqual(box.size_request(), [0, 0]) + with capture_gi_deprecation_warnings(): + self.assertEqual(box.size_request(), [0, 0]) def test_pixbuf(self): gtk.gdk.Pixbuf() diff --git a/tests/compathelper.py b/tests/compathelper.py index 668e60a5..e5de5506 100644 --- a/tests/compathelper.py +++ b/tests/compathelper.py @@ -1,4 +1,5 @@ import sys +import collections if sys.version_info >= (3, 0): ''' @@ -62,8 +63,15 @@ if sys.version_info >= (3, 0): ''' _unicode = lambda s: str(s) + + callable = lambda x: isinstance(x, collections.Callable) + from io import StringIO + StringIO else: _long = long _basestring = basestring _bytes = str _unicode = lambda s: unicode(s, 'UTF-8') + callable = callable + from StringIO import StringIO + StringIO diff --git a/tests/helper.py b/tests/helper.py new file mode 100644 index 00000000..c4308fee --- /dev/null +++ b/tests/helper.py @@ -0,0 +1,132 @@ +import contextlib +import unittest +import inspect +import warnings +import functools +import sys +from collections import namedtuple + +import gi +from gi import PyGIDeprecationWarning +from gi.repository import GLib + +from compathelper import callable, StringIO + + +ExceptionInfo = namedtuple("ExceptionInfo", ["type", "value", "traceback"]) +"""The type used for storing exceptions used by capture_exceptions()""" + + +@contextlib.contextmanager +def capture_exceptions(): + """Installs a temporary sys.excepthook which records all exceptions + instead of printing them. + """ + + exceptions = [] + + def custom_excepthook(*args): + exceptions.append(ExceptionInfo(*args)) + + old_hook = sys.excepthook + sys.excepthook = custom_excepthook + try: + yield exceptions + finally: + sys.excepthook = old_hook + + +def ignore_gi_deprecation_warnings(func_or_class): + """A unittest class and function decorator which makes them ignore + PyGIDeprecationWarning. + """ + + if inspect.isclass(func_or_class): + assert issubclass(func_or_class, unittest.TestCase) + cls = func_or_class + for name, value in cls.__dict__.items(): + if callable(value) and name.startswith("test_"): + new_value = ignore_gi_deprecation_warnings(value) + setattr(cls, name, new_value) + return cls + else: + func = func_or_class + + @functools.wraps(func) + def wrapper(*args, **kwargs): + with capture_gi_deprecation_warnings(): + return func(*args, **kwargs) + + return wrapper + + +@contextlib.contextmanager +def capture_gi_deprecation_warnings(): + """Temporarily suppress PyGIDeprecationWarning output and record them""" + + with warnings.catch_warnings(record=True) as warn: + warnings.simplefilter('always', category=PyGIDeprecationWarning) + yield warn + + +@contextlib.contextmanager +def capture_glib_warnings(allow_warnings=False, allow_criticals=False): + """Temporarily suppress glib warning output and record them. + + The test suite is run with G_DEBUG="fatal-warnings fatal-criticals" + by default. Setting allow_warnings and allow_criticals will temporarily + allow warnings or criticals without terminating the test run. + """ + + old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags(0)) + + new_mask = old_mask + if allow_warnings: + new_mask &= ~GLib.LogLevelFlags.LEVEL_WARNING + if allow_criticals: + new_mask &= ~GLib.LogLevelFlags.LEVEL_CRITICAL + + GLib.log_set_always_fatal(GLib.LogLevelFlags(new_mask)) + + GLibWarning = gi._gi._gobject.Warning + try: + with warnings.catch_warnings(record=True) as warn: + warnings.filterwarnings('always', category=GLibWarning) + yield warn + finally: + GLib.log_set_always_fatal(old_mask) + + +@contextlib.contextmanager +def capture_glib_deprecation_warnings(): + """Temporarily suppress glib deprecation warning output and record them""" + + GLibWarning = gi._gi._gobject.Warning + with warnings.catch_warnings(record=True) as warn: + warnings.filterwarnings( + 'always', category=GLibWarning, + message=".+ is deprecated and shouldn't be used anymore\. " + "It will be removed in a future version\.") + yield warn + + +@contextlib.contextmanager +def capture_output(): + """ + with capture_output as (stdout, stderr): + some_action() + print(stdout.getvalue(), stderr.getvalue()) + """ + + err = StringIO() + out = StringIO() + old_err = sys.stderr + old_out = sys.stdout + sys.stderr = err + sys.stdout = out + + try: + yield (out, err) + finally: + sys.stderr = old_err + sys.stdout = old_out diff --git a/tests/test_everything.py b/tests/test_everything.py index 5be9ce4d..4a2df771 100644 --- a/tests/test_everything.py +++ b/tests/test_everything.py @@ -26,6 +26,9 @@ try: except: Gtk = None +from helper import capture_exceptions + + if sys.version_info < (3, 0): UNICHAR = "\xe2\x99\xa5" PY2_UNICODE_UNICHAR = unicode(UNICHAR, 'UTF-8') @@ -624,7 +627,10 @@ class TestCallbacks(unittest.TestCase): # note that we do NOT expect the ZeroDivisionError to be propagated # through from the callback, as it crosses the Python<->C boundary # twice. (See GNOME #616279) - Everything.test_simple_callback(callback) + with capture_exceptions() as exc: + Everything.test_simple_callback(callback) + self.assertTrue(exc) + self.assertEqual(exc[0].type, ZeroDivisionError) def test_double_callback_exception(self): """ @@ -643,7 +649,10 @@ class TestCallbacks(unittest.TestCase): # note that we do NOT expect the ZeroDivisionError to be propagated # through from the callback, as it crosses the Python<->C boundary # twice. (See GNOME #616279) - Everything.test_simple_callback(callback) + with capture_exceptions() as exc: + Everything.test_simple_callback(callback) + self.assertTrue(exc) + self.assertEqual(exc[0].type, ZeroDivisionError) def test_return_value_callback(self): TestCallbacks.called = False @@ -1050,17 +1059,16 @@ class TestClosures(unittest.TestCase): def callback(variant): return 'no_variant' - # reset last error - sys.last_type = None - - # this does not directly raise an exception (see - # https://bugzilla.gnome.org/show_bug.cgi?id=616279) - result = Everything.test_closure_variant(callback, GLib.Variant('i', 42)) + with capture_exceptions() as exc: + # this does not directly raise an exception (see + # https://bugzilla.gnome.org/show_bug.cgi?id=616279) + result = Everything.test_closure_variant(callback, GLib.Variant('i', 42)) # ... but the result shouldn't be a string self.assertEqual(result, None) # and the error should be shown - self.assertEqual(sys.last_type, TypeError) - self.assertTrue('return value' in str(sys.last_value), sys.last_value) + self.assertEqual(len(exc), 1) + self.assertEqual(exc[0].type, TypeError) + self.assertTrue('return value' in str(exc[0].value), exc[0].value) @unittest.skipUnless(has_cairo, 'built without cairo support') diff --git a/tests/test_gi.py b/tests/test_gi.py index f69a61cc..4cdd1a42 100644 --- a/tests/test_gi.py +++ b/tests/test_gi.py @@ -24,6 +24,7 @@ from gi.repository import GObject, GLib, Gio from gi.repository import GIMarshallingTests from compathelper import _bytes, _unicode +from helper import capture_exceptions if sys.version_info < (3, 0): CONSTANT_UTF8 = "const \xe2\x99\xa5 utf8" @@ -2305,7 +2306,10 @@ class TestPythonGObject(unittest.TestCase): def test_exception_in_vfunc_return_value(self): obj = self.ErrorObject() - self.assertEqual(obj.vfunc_return_value_only(), 0) + with capture_exceptions() as exc: + self.assertEqual(obj.vfunc_return_value_only(), 0) + self.assertEqual(len(exc), 1) + self.assertEqual(exc[0].type, ValueError) @unittest.skipUnless(hasattr(GIMarshallingTests, 'callback_owned_boxed'), 'requires newer version of GI') diff --git a/tests/test_gio.py b/tests/test_gio.py index 0c773bc9..05ab008e 100644 --- a/tests/test_gio.py +++ b/tests/test_gio.py @@ -6,6 +6,8 @@ import unittest import gi.overrides from gi.repository import GLib, Gio +from helper import ignore_gi_deprecation_warnings + class TestGio(unittest.TestCase): def test_file_enumerator(self): @@ -120,6 +122,7 @@ class TestGSettings(unittest.TestCase): self.assertEqual(bool(empty), True) self.assertEqual(empty.keys(), []) + @ignore_gi_deprecation_warnings def test_change_event(self): changed_log = [] change_event_log = [] diff --git a/tests/test_iochannel.py b/tests/test_iochannel.py index 02277e1d..aa130ec6 100644 --- a/tests/test_iochannel.py +++ b/tests/test_iochannel.py @@ -49,7 +49,7 @@ second line self.assertEqual(_unicode(ch.readline()), 'À demain!') self.assertEqual(ch.get_buffer_condition(), 0) self.assertEqual(ch.readline(), '') - ch.close() + ch.shutdown(True) def test_file_readline_latin1(self): ch = GLib.IOChannel(filename=self.testlatin1, mode='r') @@ -59,7 +59,7 @@ second line self.assertEqual(ch.readline(), 'second line\n') self.assertEqual(ch.readline(), '\n') self.assertEqual(_unicode(ch.readline()), 'À demain!') - ch.close() + ch.shutdown(True) def test_file_iter(self): items = [] @@ -68,7 +68,7 @@ second line items.append(item) self.assertEqual(len(items), 4) self.assertEqual(_unicode(items[0]), 'hello ♥ world\n') - ch.close() + ch.shutdown(True) def test_file_readlines(self): ch = GLib.IOChannel(filename=self.testutf8) @@ -117,11 +117,11 @@ second line ch = GLib.IOChannel(filename=self.testout, mode='w') ch.set_encoding('latin1') ch.write('hellø world\n') - ch.close() + ch.shutdown(True) ch = GLib.IOChannel(filename=self.testout, mode='a') ch.set_encoding('latin1') ch.write('À demain!') - ch.close() + ch.shutdown(True) with open(self.testout, 'rb') as f: self.assertEqual(f.read().decode('latin1'), 'hellø world\nÀ demain!') @@ -129,7 +129,7 @@ second line def test_file_writelines(self): ch = GLib.IOChannel(filename=self.testout, mode='w') ch.writelines(['foo', 'bar\n', 'baz\n', 'end']) - ch.close() + ch.shutdown(True) with open(self.testout, 'r') as f: self.assertEqual(f.read(), 'foobar\nbaz\nend') @@ -163,9 +163,9 @@ second line # closing flushes writer.set_buffered(True) writer.write('ghi') - writer.close() + writer.shutdown(True) self.assertEqual(reader.read(), b'ghi') - reader.close() + reader.shutdown(True) def test_fd_read(self): (r, w) = os.pipe() @@ -184,7 +184,7 @@ second line os.close(w) self.assertEqual(ch.read(), b'\x03\x04') - ch.close() + ch.shutdown(True) def test_fd_write(self): (r, w) = os.pipe() @@ -199,7 +199,7 @@ second line # now test blocking case, after closing the write end fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) & ~os.O_NONBLOCK) ch.write(b'\x03\x04') - ch.close() + ch.shutdown(True) self.assertEqual(os.read(r, 10), b'\x03\x04') os.close(r) diff --git a/tests/test_overrides_gdk.py b/tests/test_overrides_gdk.py index da968558..eff2c542 100644 --- a/tests/test_overrides_gdk.py +++ b/tests/test_overrides_gdk.py @@ -2,7 +2,6 @@ # vim: tabstop=4 shiftwidth=4 expandtab import unittest -import warnings import gi.overrides from gi import PyGIDeprecationWarning @@ -13,6 +12,8 @@ try: except ImportError: Gdk = None +from helper import capture_glib_deprecation_warnings + @unittest.skipUnless(Gdk, 'Gdk not available') class TestGdk(unittest.TestCase): @@ -29,7 +30,8 @@ class TestGdk(unittest.TestCase): self.assertEqual(color.red, 100) self.assertEqual(color.green, 200) self.assertEqual(color.blue, 300) - self.assertEqual(color, Gdk.Color(100, 200, 300)) + with capture_glib_deprecation_warnings(): + self.assertEqual(color, Gdk.Color(100, 200, 300)) self.assertNotEqual(color, Gdk.Color(1, 2, 3)) def test_color_floats(self): @@ -122,9 +124,11 @@ class TestGdk(unittest.TestCase): def test_cursor(self): self.assertEqual(Gdk.Cursor, gi.overrides.Gdk.Cursor) - c = Gdk.Cursor(Gdk.CursorType.WATCH) + with capture_glib_deprecation_warnings(): + c = Gdk.Cursor(Gdk.CursorType.WATCH) self.assertNotEqual(c, None) - c = Gdk.Cursor(cursor_type=Gdk.CursorType.WATCH) + with capture_glib_deprecation_warnings(): + c = Gdk.Cursor(cursor_type=Gdk.CursorType.WATCH) self.assertNotEqual(c, None) display_manager = Gdk.DisplayManager.get() @@ -136,8 +140,7 @@ class TestGdk(unittest.TestCase): 5, 10) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') + with capture_glib_deprecation_warnings() as warn: c = Gdk.Cursor(display, test_pixbuf, y=0, x=0) @@ -166,7 +169,8 @@ class TestGdk(unittest.TestCase): '<flags GDK_META_MASK | GDK_RELEASE_MASK of type GdkModifierType>') def test_color_parse(self): - c = Gdk.color_parse('#00FF80') + with capture_glib_deprecation_warnings(): + c = Gdk.color_parse('#00FF80') self.assertEqual(c.red, 0) self.assertEqual(c.green, 65535) self.assertEqual(c.blue, 32896) diff --git a/tests/test_overrides_gtk.py b/tests/test_overrides_gtk.py index bd477bf4..44f2f6ec 100644 --- a/tests/test_overrides_gtk.py +++ b/tests/test_overrides_gtk.py @@ -9,6 +9,7 @@ import sys import warnings from compathelper import _unicode, _bytes +from helper import ignore_gi_deprecation_warnings, capture_glib_warnings import gi import gi.overrides @@ -58,16 +59,8 @@ def realized(widget): Gtk.main_iteration() -@contextlib.contextmanager -def ignore_glib_warnings(): - """Temporarily change GLib logging to not bail on warnings.""" - old_mask = GLib.log_set_always_fatal( - GLib.LogLevelFlags.LEVEL_CRITICAL | GLib.LogLevelFlags.LEVEL_ERROR) - yield - GLib.log_set_always_fatal(old_mask) - - @unittest.skipUnless(Gtk, 'Gtk not available') +@ignore_gi_deprecation_warnings class TestGtk(unittest.TestCase): def test_container(self): box = Gtk.Box() @@ -319,7 +312,7 @@ class TestGtk(unittest.TestCase): def test_file_chooser_dialog(self): # might cause a GVFS warning, do not break on this - with ignore_glib_warnings(): + with capture_glib_warnings(allow_warnings=True): dialog = Gtk.FileChooserDialog(title='file chooser dialog test', action=Gtk.FileChooserAction.SAVE) @@ -332,7 +325,7 @@ class TestGtk(unittest.TestCase): def test_file_chooser_dialog_default_action(self): # might cause a GVFS warning, do not break on this - with ignore_glib_warnings(): + with capture_glib_warnings(allow_warnings=True): dialog = Gtk.FileChooserDialog(title='file chooser dialog test') action = dialog.get_property('action') @@ -375,7 +368,7 @@ class TestGtk(unittest.TestCase): self.assertTrue(isinstance(button, Gtk.Widget)) # Using stock items causes hard warning in devel versions of GTK+. - with ignore_glib_warnings(): + with capture_glib_warnings(allow_warnings=True): button = Gtk.Button.new_from_stock(Gtk.STOCK_CLOSE) self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) @@ -594,7 +587,7 @@ class TestGtk(unittest.TestCase): # PyGTK compat # Using stock items causes hard warning in devel versions of GTK+. - with ignore_glib_warnings(): + with capture_glib_warnings(allow_warnings=True): button = Gtk.ToolButton() self.assertEqual(button.props.stock_id, None) @@ -858,6 +851,7 @@ class TestBuilder(unittest.TestCase): self.assertEqual(signal_checker.after_sentinel, 2) +@ignore_gi_deprecation_warnings @unittest.skipUnless(Gtk, 'Gtk not available') class TestTreeModel(unittest.TestCase): def test_tree_model_sort(self): diff --git a/tests/test_properties.py b/tests/test_properties.py index 6010bc28..ce184fed 100644 --- a/tests/test_properties.py +++ b/tests/test_properties.py @@ -41,6 +41,7 @@ else: UNICODE_UTF8 = TEST_UTF8 from compathelper import _long +from helper import capture_glib_warnings, capture_output class PropertyObject(GObject.GObject): @@ -550,14 +551,17 @@ class TestProperty(unittest.TestCase): raise ValueError('something bad happend') o = C() - with self.assertRaisesRegex(ValueError, 'something bad happend'): - o.prop - with self.assertRaisesRegex(ValueError, 'something bad happend'): - o.get_property('prop') + # silence exception printed to stderr + with capture_output(): + with self.assertRaisesRegex(ValueError, 'something bad happend'): + o.prop - with self.assertRaisesRegex(ValueError, 'something bad happend'): - o.props.prop + with self.assertRaisesRegex(ValueError, 'something bad happend'): + o.get_property('prop') + + with self.assertRaisesRegex(ValueError, 'something bad happend'): + o.props.prop def test_custom_setter(self): class C(GObject.GObject): @@ -690,8 +694,7 @@ class TestProperty(unittest.TestCase): # we test known-bad values here which cause Gtk-WARNING logs. # Explicitly allow these for this test. - old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL) - try: + with capture_glib_warnings(allow_warnings=True): o = C() self.assertEqual(o.prop_int, 1) @@ -714,8 +717,6 @@ class TestProperty(unittest.TestCase): o.prop_float = 10.51 self.assertEqual(o.prop_float, 7.75) - finally: - GLib.log_set_always_fatal(old_mask) def test_multiple_instances(self): class C(GObject.GObject): diff --git a/tests/test_repository.py b/tests/test_repository.py index 3d7cf686..8710ce7d 100644 --- a/tests/test_repository.py +++ b/tests/test_repository.py @@ -30,7 +30,6 @@ gi.require_version('GIRepository', '2.0') import gi._gi as GIRepository from gi.module import repository as repo from gi.repository import GObject -from gi.repository import GLib from gi.repository import GIMarshallingTests from gi.repository import GIRepository as IntrospectedRepository @@ -41,6 +40,8 @@ try: except ImportError: has_cairo = False +from helper import capture_glib_warnings + def find_child_info(info, getter_name, name): getter = getattr(info, getter_name) @@ -339,26 +340,20 @@ class Test(unittest.TestCase): # also raise a RuntimeError. GIMarshallingTests.NoTypeFlags # cause flags registration info = repo.find_by_name('GIMarshallingTests', 'NoTypeFlags') - old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_ERROR) - try: + with capture_glib_warnings(allow_warnings=True): self.assertRaises(RuntimeError, GIRepository.flags_register_new_gtype_and_add, info) - finally: - GLib.log_set_always_fatal(old_mask) def test_enum_double_registration_error(self): # a warning is printed for double registration and pygobject will # also raise a RuntimeError. GIMarshallingTests.Enum # cause enum registration info = repo.find_by_name('GIMarshallingTests', 'Enum') - old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_ERROR) - try: + with capture_glib_warnings(allow_warnings=True): self.assertRaises(RuntimeError, GIRepository.enum_register_new_gtype_and_add, info) - finally: - GLib.log_set_always_fatal(old_mask) def test_enums(self): self.assertTrue(hasattr(GIRepository, 'Direction')) diff --git a/tests/test_signal.py b/tests/test_signal.py index 74ec7458..01e4b000 100644 --- a/tests/test_signal.py +++ b/tests/test_signal.py @@ -9,6 +9,7 @@ from gi.repository import GObject, GLib from gi import _signalhelper as signalhelper import testhelper from compathelper import _long +from helper import capture_glib_warnings, capture_gi_deprecation_warnings try: import cairo @@ -83,13 +84,9 @@ class TestGSignalsError(unittest.TestCase): def foo(): class Foo(GObject.GObject): __gsignals__ = {'not-exists': 'override'} - # do not stumble over the warning thrown by GLib - old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL | - GLib.LogLevelFlags.LEVEL_ERROR) - try: + + with capture_glib_warnings(allow_warnings=True): self.assertRaises(TypeError, foo) - finally: - GLib.log_set_always_fatal(old_mask) gc.collect() @@ -373,15 +370,10 @@ class TestClosures(unittest.TestCase): self.count += 1 def _callback_invalid_stop_emission_name(self, obj, prop): - # We expect a GLib warning but there currently is no way to test that - # This can at least make sure we don't crash - old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL | - GLib.LogLevelFlags.LEVEL_ERROR) - try: + with capture_glib_warnings(allow_warnings=True) as warn: obj.stop_emission_by_name('notasignal::baddetail') - finally: - GLib.log_set_always_fatal(old_mask) self.emission_error = True + self.assertTrue(warn) def test_disconnect_by_func(self): e = E() @@ -416,7 +408,8 @@ class TestClosures(unittest.TestCase): e = E() e.connect('notify::prop', self._callback_invalid_stop_emission_name) - e.set_property('prop', 1234) + with capture_glib_warnings(): + e.set_property('prop', 1234) self.assertTrue(self.emission_error) def test_handler_block(self): @@ -1256,7 +1249,8 @@ class _ConnectObjectTestBase(object): else: connect_func = obj.connect_object - connect_func('sig-with-int64-prop', callback, swap_obj, *user_data) + with capture_gi_deprecation_warnings(): + connect_func('sig-with-int64-prop', callback, swap_obj, *user_data) obj.emit('sig-with-int64-prop', *emit_args) self.assertEqual(len(callback_args), 1) return callback_args[0] diff --git a/tests/test_source.py b/tests/test_source.py index 362e5cdf..f13ab6ba 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -7,6 +7,8 @@ import warnings from gi.repository import GLib from gi import PyGIDeprecationWarning +from helper import capture_glib_warnings + class Idle(GLib.Idle): def __init__(self, loop): @@ -132,8 +134,8 @@ class TestSource(unittest.TestCase): self.assertEqual(GLib.source_remove(s), True) # Removing sources not found cause critical - old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_ERROR) - try: + with capture_glib_warnings(allow_criticals=True): + # s is now removed, should fail now self.assertEqual(GLib.source_remove(s), False) @@ -141,8 +143,6 @@ class TestSource(unittest.TestCase): self.assertEqual(GLib.source_remove(GLib.MAXINT32), False) self.assertEqual(GLib.source_remove(GLib.MAXINT32 + 1), False) self.assertEqual(GLib.source_remove(GLib.MAXUINT32), False) - finally: - GLib.log_set_always_fatal(old_mask) def test_recurse_property(self): s = GLib.Idle() |