Example #1
0
 def test_combobox_entry(self):
     liststore = gtk.ListStore(int, str)
     liststore.append((1, 'One'))
     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:
         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)
     self.assertEqual(combo.get_child().get_text(), 'One')
     combo = gtk.combo_box_entry_new()
     combo.set_model(liststore)
     combo.set_text_column(1)
     combo.set_active(0)
     self.assertEqual(combo.get_text_column(), 1)
     self.assertEqual(combo.get_child().get_text(), 'One')
     combo = gtk.combo_box_entry_new_with_model(liststore)
     combo.set_text_column(1)
     combo.set_active(0)
     self.assertEqual(combo.get_text_column(), 1)
     self.assertEqual(combo.get_child().get_text(), 'One')
Example #2
0
 def testComboBoxEntry(self):
     liststore = gtk.ListStore(int, str)
     liststore.append((1, 'One'))
     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)
     combo = gtk.ComboBoxEntry(model=liststore)
     GLib.log_set_always_fatal(old_mask)
     combo.set_text_column(1)
     combo.set_active(0)
     self.assertEqual(combo.get_text_column(), 1)
     self.assertEqual(combo.get_child().get_text(), 'One')
     combo = gtk.combo_box_entry_new()
     combo.set_model(liststore)
     combo.set_text_column(1)
     combo.set_active(0)
     self.assertEqual(combo.get_text_column(), 1)
     self.assertEqual(combo.get_child().get_text(), 'One')
     combo = gtk.combo_box_entry_new_with_model(liststore)
     combo.set_text_column(1)
     combo.set_active(0)
     self.assertEqual(combo.get_text_column(), 1)
     self.assertEqual(combo.get_child().get_text(), 'One')
Example #3
0
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)
Example #4
0
def unit(run=[],
         filter_func=None,
         main=False,
         subdirs=None,
         strict=False,
         stop_first=False):

    path = os.path.dirname(__file__)
    if subdirs is None:
        subdirs = []

    # make glib warnings fatal
    if strict:
        from gi.repository import GLib
        GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL
                                  | GLib.LogLevelFlags.LEVEL_ERROR
                                  | GLib.LogLevelFlags.LEVEL_WARNING)

    suites = []

    def discover_tests(mod):
        for k in vars(mod):
            value = getattr(mod, k)

            if value is not TestCase and \
                    inspect.isclass(value) and issubclass(value, TestCase):
                suites.append(value)

    if main:
        for name in os.listdir(path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, name[:-3]]), {}, {}, [])
                discover_tests(getattr(mod, name[:-3]))

    if main:
        # include plugin tests by default
        subdirs = (subdirs or []) + ["plugin"]

    for subdir in subdirs:
        sub_path = os.path.join(path, subdir)
        for name in os.listdir(sub_path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, subdir, name[:-3]]), {},
                                 {}, [])
                discover_tests(getattr(getattr(mod, subdir), name[:-3]))

    runner = Runner()
    failures = errors = all_ = 0
    use_suites = filter(filter_func, suites)
    for test in sorted(use_suites, key=repr):
        if (not run or test.__name__ in run or test.__module__[11:] in run):
            df, de, num = runner.run(test, failfast=stop_first)
            failures += df
            errors += de
            all_ += num
            if stop_first and (df or de):
                break

    return failures, errors, all_
Example #5
0
def unit(run=[], filter_func=None, main=False, subdirs=None,
               strict=False, stop_first=False):

    path = os.path.dirname(__file__)
    if subdirs is None:
        subdirs = []

    # make glib warnings fatal
    if strict:
        from gi.repository import GLib
        GLib.log_set_always_fatal(
            GLib.LogLevelFlags.LEVEL_CRITICAL |
            GLib.LogLevelFlags.LEVEL_ERROR |
            GLib.LogLevelFlags.LEVEL_WARNING)

    suites = []

    def discover_tests(mod):
        for k in vars(mod):
            value = getattr(mod, k)

            if value is not TestCase and \
                    inspect.isclass(value) and issubclass(value, TestCase):
                suites.append(value)

    if main:
        for name in os.listdir(path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, name[:-3]]), {}, {}, [])
                discover_tests(getattr(mod, name[:-3]))

    if main:
        # include plugin tests by default
        subdirs = (subdirs or []) + ["plugin"]

    for subdir in subdirs:
        sub_path = os.path.join(path, subdir)
        for name in os.listdir(sub_path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(
                    ".".join([__name__, subdir, name[:-3]]), {}, {}, [])
                discover_tests(getattr(getattr(mod, subdir), name[:-3]))

    runner = Runner()
    failures = errors = all_ = 0
    use_suites = filter(filter_func, suites)
    for test in sorted(use_suites, key=repr):
        if (not run
                or test.__name__ in run
                or test.__module__[11:] in run):
            df, de, num = runner.run(test, failfast=stop_first)
            failures += df
            errors += de
            all_ += num
            if stop_first and (df or de):
                break

    return failures, errors, all_
Example #6
0
 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:
         obj.stop_emission_by_name('notasignal::baddetail')
     finally:
         GLib.log_set_always_fatal(old_mask)
         self.emission_error = True
Example #7
0
 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:
         obj.stop_emission_by_name('notasignal::baddetail')
     finally:
         GLib.log_set_always_fatal(old_mask)
         self.emission_error = True
Example #8
0
 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:
         self.assertRaises(RuntimeError,
                           GIRepository.enum_register_new_gtype_and_add,
                           info)
     finally:
         GLib.log_set_always_fatal(old_mask)
Example #9
0
 def test_invalid_name(self, *args):
     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:
         self.assertRaises(TypeError, foo)
     finally:
         GLib.log_set_always_fatal(old_mask)
     gc.collect()
Example #10
0
 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:
         self.assertRaises(RuntimeError,
                           GIRepository.enum_register_new_gtype_and_add,
                           info)
     finally:
         GLib.log_set_always_fatal(old_mask)
Example #11
0
    def test_invalid_name(self, *args):
        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:
            self.assertRaises(TypeError, foo)
        finally:
            GLib.log_set_always_fatal(old_mask)
        gc.collect()
Example #12
0
    def test_remove(self):
        s = GLib.idle_add(dir)
        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:
            # s is now removed, should fail now
            self.assertEqual(GLib.source_remove(s), False)

            # accepts large source IDs (they are unsigned)
            self.assertEqual(GLib.source_remove(GObject.G_MAXINT32), False)
            self.assertEqual(GLib.source_remove(GObject.G_MAXINT32 + 1), False)
            self.assertEqual(GLib.source_remove(GObject.G_MAXUINT32), False)
        finally:
            GLib.log_set_always_fatal(old_mask)
Example #13
0
    def test_remove(self):
        s = GLib.idle_add(dir)
        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:
            # s is now removed, should fail now
            self.assertEqual(GLib.source_remove(s), False)

            # accepts large source IDs (they are unsigned)
            self.assertEqual(GLib.source_remove(GObject.G_MAXINT32), False)
            self.assertEqual(GLib.source_remove(GObject.G_MAXINT32 + 1), False)
            self.assertEqual(GLib.source_remove(GObject.G_MAXUINT32), False)
        finally:
            GLib.log_set_always_fatal(old_mask)
Example #14
0
def unit(run=[],
         suite=None,
         strict=False,
         exitfirst=False,
         network=True,
         quality=True):
    """Returns 0 if everything passed"""

    # make glib warnings fatal
    if strict:
        from gi.repository import GLib
        GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL
                                  | GLib.LogLevelFlags.LEVEL_ERROR
                                  | GLib.LogLevelFlags.LEVEL_WARNING)

    args = []

    if is_ci():
        args.extend(["-p", "no:cacheprovider"])
        args.extend(["-p", "no:stepwise"])

    if run:
        args.append("-k")
        args.append(" or ".join(run))

    skip_markers = []

    if not quality:
        skip_markers.append("quality")

    if not network:
        skip_markers.append("network")

    if skip_markers:
        args.append("-m")
        args.append(" and ".join(["not %s" % m for m in skip_markers]))

    if exitfirst:
        args.append("-x")

    if suite is None:
        args.append("tests")
    else:
        args.append(os.path.join("tests", suite))

    return pytest.main(args=args)
Example #15
0
    def test_min_max(self):
        class C(GObject.GObject):
            prop_int = GObject.Property(type=int,
                                        minimum=1,
                                        maximum=100,
                                        default=1)
            prop_float = GObject.Property(type=float,
                                          minimum=0.1,
                                          maximum=10.5,
                                          default=1.1)

            def __init__(self):
                GObject.GObject.__init__(self)

        # 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:
            o = C()
            self.assertEqual(o.prop_int, 1)

            o.prop_int = 5
            self.assertEqual(o.prop_int, 5)

            o.prop_int = 0
            self.assertEqual(o.prop_int, 5)

            o.prop_int = 101
            self.assertEqual(o.prop_int, 5)

            self.assertEqual(o.prop_float, 1.1)

            o.prop_float = 7.75
            self.assertEqual(o.prop_float, 7.75)

            o.prop_float = 0.09
            self.assertEqual(o.prop_float, 7.75)

            o.prop_float = 10.51
            self.assertEqual(o.prop_float, 7.75)
        finally:
            GLib.log_set_always_fatal(old_mask)
Example #16
0
def unit(run=[], suite=None, strict=False, exitfirst=False, network=True,
         quality=True):
    """Returns 0 if everything passed"""

    # make glib warnings fatal
    if strict:
        from gi.repository import GLib
        GLib.log_set_always_fatal(
            GLib.LogLevelFlags.LEVEL_CRITICAL |
            GLib.LogLevelFlags.LEVEL_ERROR |
            GLib.LogLevelFlags.LEVEL_WARNING)

    args = []

    if is_ci():
        args.extend(["-p", "no:cacheprovider"])

    if run:
        args.append("-k")
        args.append(" or ".join(run))

    skip_markers = []

    if not quality:
        skip_markers.append("quality")

    if not network:
        skip_markers.append("network")

    if skip_markers:
        args.append("-m")
        args.append(" and ".join(["not %s" % m for m in skip_markers]))

    if exitfirst:
        args.append("-x")

    if suite is None:
        args.append("tests")
    else:
        args.append(os.path.join("tests", suite))

    return pytest.main(args=args)
Example #17
0
    def testMinMax(self):
        class C(GObject.GObject):
            prop_int = GObject.Property(type=int, minimum=1, maximum=100, default=1)
            prop_float = GObject.Property(type=float, minimum=0.1, maximum=10.5, default=1.1)

            def __init__(self):
                GObject.GObject.__init__(self)

        # 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:
            o = C()
            self.assertEqual(o.prop_int, 1)

            o.prop_int = 5
            self.assertEqual(o.prop_int, 5)

            o.prop_int = 0
            self.assertEqual(o.prop_int, 5)

            o.prop_int = 101
            self.assertEqual(o.prop_int, 5)

            self.assertEqual(o.prop_float, 1.1)

            o.prop_float = 7.75
            self.assertEqual(o.prop_float, 7.75)

            o.prop_float = 0.09
            self.assertEqual(o.prop_float, 7.75)

            o.prop_float = 10.51
            self.assertEqual(o.prop_float, 7.75)
        finally:
            GLib.log_set_always_fatal(old_mask)
Example #18
0
def _run_tests(run=[],
               filter_func=None,
               main=False,
               subdirs=None,
               strict=False,
               stop_first=False):

    # Ideally nothing should touch the FS on import, but we do atm..
    # Get rid of all modules so QUODLIBET_USERDIR gets used everywhere.
    for key in sys.modules.keys():
        if key.startswith('quodlibet'):
            del (sys.modules[key])

    path = os.path.dirname(__file__)
    if subdirs is None:
        subdirs = []

    import quodlibet
    quodlibet.init()

    # make glib warnings fatal
    if strict:
        from gi.repository import GLib
        GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL
                                  | GLib.LogLevelFlags.LEVEL_ERROR
                                  | GLib.LogLevelFlags.LEVEL_WARNING)

    suites = []
    abstract = []

    def discover_tests(mod):
        for k in vars(mod):
            value = getattr(mod, k)

            if value not in (TestCase, AbstractTestCase) and \
                    inspect.isclass(value) and issubclass(value, TestCase):
                if AbstractTestCase in value.__bases__:
                    abstract.append(value)
                elif value not in skipped:
                    suites.append(value)

    if main:
        for name in os.listdir(path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, name[:-3]]), {}, {}, [])
                discover_tests(getattr(mod, name[:-3]))

    if main:
        # include plugin tests by default
        subdirs = (subdirs or []) + ["plugin"]

    for subdir in subdirs:
        sub_path = os.path.join(path, subdir)
        for name in os.listdir(sub_path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, subdir, name[:-3]]), {},
                                 {}, [])
                discover_tests(getattr(getattr(mod, subdir), name[:-3]))

    # check if each abstract class is actually used (also by skipped ones)
    unused_abstract = set(abstract)
    for case in suites:
        unused_abstract -= set(case.__mro__)
    for case in skipped:
        unused_abstract -= set(case.__mro__)
    if unused_abstract:
        raise Exception("The following abstract test cases have no "
                        "implementation: %r" % list(unused_abstract))

    for case in skipped:
        # don't warn for tests we won't run anyway
        if run and case not in run:
            continue
        name = "%s.%s" % (case.__module__, case.__name__)
        reason = skipped_reason.get(case, "??")
        if case in skipped_warn:
            print_w("Skipped test: %s (%s)" % (name, reason))

    import quodlibet.config

    runner = Runner()
    failures = errors = 0
    use_suites = filter(filter_func, suites)
    for test in sorted(use_suites, key=repr):
        if (not run or test.__name__ in run or test.__module__[11:] in run):
            df, de = runner.run(test, failfast=stop_first)
            if stop_first and (df or de):
                break
            failures += df
            errors += de
            quodlibet.config.quit()

    return failures, errors
Example #19
0
def unit(run=[], filter_func=None, main=False, subdirs=None,
               strict=False, stop_first=False):

    path = os.path.dirname(__file__)
    if subdirs is None:
        subdirs = []

    # make glib warnings fatal
    if strict:
        from gi.repository import GLib
        GLib.log_set_always_fatal(
            GLib.LogLevelFlags.LEVEL_CRITICAL |
            GLib.LogLevelFlags.LEVEL_ERROR |
            GLib.LogLevelFlags.LEVEL_WARNING)

    suites = []
    abstract = []

    def discover_tests(mod):
        for k in vars(mod):
            value = getattr(mod, k)

            if value not in (TestCase, AbstractTestCase) and \
                    inspect.isclass(value) and issubclass(value, TestCase):
                if AbstractTestCase in value.__bases__:
                    abstract.append(value)
                elif value not in skipped:
                    suites.append(value)

    if main:
        for name in os.listdir(path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, name[:-3]]), {}, {}, [])
                discover_tests(getattr(mod, name[:-3]))

    if main:
        # include plugin tests by default
        subdirs = (subdirs or []) + ["plugin"]

    for subdir in subdirs:
        sub_path = os.path.join(path, subdir)
        for name in os.listdir(sub_path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(
                    ".".join([__name__, subdir, name[:-3]]), {}, {}, [])
                discover_tests(getattr(getattr(mod, subdir), name[:-3]))

    # check if each abstract class is actually used (also by skipped ones)
    unused_abstract = set(abstract)
    for case in suites:
        unused_abstract -= set(case.__mro__)
    for case in skipped:
        unused_abstract -= set(case.__mro__)
    if unused_abstract:
        raise Exception("The following abstract test cases have no "
                        "implementation: %r" % list(unused_abstract))

    for case in skipped:
        # don't warn for tests we won't run anyway
        if run and case not in run:
            continue
        name = "%s.%s" % (case.__module__, case.__name__)
        reason = skipped_reason.get(case, "??")
        if case in skipped_warn:
            print_w("Skipped test: %s (%s)" % (name, reason))

    import quodlibet.config

    runner = Runner()
    failures = errors = all_ = 0
    use_suites = filter(filter_func, suites)
    for test in sorted(use_suites, key=repr):
        if (not run
                or test.__name__ in run
                or test.__module__[11:] in run):
            df, de, num = runner.run(test, failfast=stop_first)
            failures += df
            errors += de
            all_ += num
            if stop_first and (df or de):
                break
            quodlibet.config.quit()

    return failures, errors, all_
Example #20
0
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)
Example #21
0
def test(load_gi, backend=None, strict=False, filter_=None, failfast=False):
    """Run the test suite.

    load_gi -- run all tests in the pygobject suite with PyGObject
    backend -- "ctypes" or "cffi"
    strict  -- fail on glib warnings
    filter_ -- filter for test names (class names)
    """

    global _is_gi, _is_pypy, _has_cairo, _gi_version, GIOverflowError

    _is_gi = load_gi
    _is_pypy = platform.python_implementation() == "PyPy"
    _has_cairo = True

    if not load_gi:
        try:
            import cairocffi
            cairocffi.install_as_pycairo()
        except (ImportError, OSError):
            _has_cairo = False
        import pgi
        pgi.install_as_gi()
        try:
            pgi.set_backend(backend)
        except LookupError:
            print("Couldn't load backend: %r" % backend)
            return

    def headline(text):
        return (("### %s " % text) + "#" * 80)[:80]

    import gi

    TYPELIBS = {
        "Gtk": "3.0",
        "Gdk": "3.0",
        "Clutter": "1.0",
        "Regress": "1.0",
        "GIMarshallingTests": "1.0",
        "PangoCairo": "1.0"
    }

    for name, version in TYPELIBS.items():
        try:
            gi.require_version(name, version)
        except ValueError:
            pass

    if load_gi:
        assert gi.__name__ == "gi"
        try:
            _gi_version = gi.version_info
        except AttributeError:
            _gi_version = gi._gobject.pygobject_version

        if _gi_version < (3, 10):
            GIOverflowError = ValueError
        else:
            GIOverflowError = OverflowError

        hl = headline("GI")
    else:
        assert gi.__name__ == "pgi"
        if backend:
            hl = headline("PGI (%s)" % backend)
        else:
            hl = headline("PGI")

        GIOverflowError = OverflowError
    print(hl[:80])

    # gi uses logging
    logging.disable(logging.ERROR)

    if strict:
        # make glib warnings fatal
        from gi.repository import GLib
        GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL
                                  | GLib.LogLevelFlags.LEVEL_ERROR
                                  | GLib.LogLevelFlags.LEVEL_WARNING)

    current_dir = os.path.join(os.path.dirname(__file__))
    tests = []
    tests = discover(current_dir, "tests_pygobject")
    tests += discover(current_dir, "tests_mixed")
    if not load_gi:
        tests.extend(discover(current_dir, "tests_pgi"))

    if filter_ is not None:
        tests = filter(lambda t: filter_(t.__name__), tests)

    tests = [unittest.makeSuite(t) for t in tests]

    # only in case all get run, so filtered results don't get spammed
    if filter_ is None:
        # collected by the FIXME decorator
        print(headline("FIXME"))
        for item, desc in sorted(_fixme.items(), key=lambda x: repr(x)):
            print(" -> %s.%s" % (item.__module__, item.__name__), end="")
            if desc:
                print("(%s)" % desc)
            else:
                print()

    run = unittest.TextTestRunner(verbosity=2, failfast=failfast).run(
        unittest.TestSuite(tests))

    return len(run.failures) + len(run.errors)
Example #22
0
def test(load_gi, backend=None, strict=False, filter_=None, failfast=False):
    """Run the test suite.

    load_gi -- run all tests in the pygobject suite with PyGObject
    backend -- "ctypes" or "cffi"
    strict  -- fail on glib warnings
    filter_ -- filter for test names (class names)
    """

    global _is_gi, _is_pypy, _has_cairo, _gi_version, GIOverflowError

    _is_gi = load_gi
    _is_pypy = platform.python_implementation() == "PyPy"
    _has_cairo = True

    if not load_gi:
        try:
            import cairocffi
            cairocffi.install_as_pycairo()
        except (ImportError, OSError):
            _has_cairo = False
        import pgi
        pgi.install_as_gi()
        try:
            pgi.set_backend(backend)
        except LookupError:
            print("Couldn't load backend: %r" % backend)
            return

    def headline(text):
        return (("### %s " % text) + "#" * 80)[:80]

    import gi

    TYPELIBS = {
        "Gtk": "3.0",
        "Gdk": "3.0",
        "Clutter": "1.0",
        "Regress": "1.0",
        "GIMarshallingTests": "1.0",
        "PangoCairo": "1.0"
    }

    for name, version in TYPELIBS.items():
        try:
            gi.require_version(name, version)
        except ValueError:
            pass

    if load_gi:
        assert gi.__name__ == "gi"
        try:
            _gi_version = gi.version_info
        except AttributeError:
            _gi_version = gi._gobject.pygobject_version

        if _gi_version < (3, 10):
            GIOverflowError = ValueError
        else:
            GIOverflowError = OverflowError

        hl = headline("GI")
    else:
        assert gi.__name__ == "pgi"
        if backend:
            hl = headline("PGI (%s)" % backend)
        else:
            hl = headline("PGI")

        GIOverflowError = OverflowError
    print(hl[:80])

    # gi uses logging
    logging.disable(logging.ERROR)

    if strict:
        # make glib warnings fatal
        from gi.repository import GLib
        GLib.log_set_always_fatal(
            GLib.LogLevelFlags.LEVEL_CRITICAL |
            GLib.LogLevelFlags.LEVEL_ERROR |
            GLib.LogLevelFlags.LEVEL_WARNING)

    current_dir = os.path.join(os.path.dirname(__file__))
    tests = []
    tests = discover(current_dir, "tests_pygobject")
    tests += discover(current_dir, "tests_mixed")
    if not load_gi:
        tests.extend(discover(current_dir, "tests_pgi"))

    if filter_ is not None:
        tests = filter(lambda t: filter_(t.__name__), tests)

    tests = [unittest.makeSuite(t) for t in tests]

    # only in case all get run, so filtered results don't get spammed
    if filter_ is None:
        # collected by the FIXME decorator
        print(headline("FIXME"))
        for item, desc in sorted(_fixme.items(), key=lambda x: repr(x)):
            print(" -> %s.%s" % (item.__module__, item.__name__), end="")
            if desc:
                print("(%s)" % desc)
            else:
                print()

    run = unittest.TextTestRunner(
        verbosity=2, failfast=failfast).run(unittest.TestSuite(tests))

    return len(run.failures) + len(run.errors)
Example #23
0
import unittest
import tempfile
import sys
import os
import imp
import apport
import shutil
import subprocess
from gi.repository import GLib, Gtk
from apport import unicode_gettext as _
from mock import patch

import apport.crashdb_impl.memory

GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_CRITICAL)

if os.environ.get('APPORT_TEST_LOCAL'):
    apport_gtk_path = 'gtk/apport-gtk'
    kernel_oops_path = 'data/kernel_oops'
else:
    apport_gtk_path = os.path.join(os.environ.get('APPORT_DATA_DIR', '/usr/share/apport'), 'apport-gtk')
    kernel_oops_path = os.path.join(os.environ.get('APPORT_DATA_DIR', '/usr/share/apport'), 'kernel_oops')
GTKUserInterface = imp.load_source('', apport_gtk_path).GTKUserInterface


class T(unittest.TestCase):
    @classmethod
    def setUpClass(klass):
        r = apport.Report()
        r.add_os_info()
def unit(run=[],
         filter_func=None,
         main=False,
         subdirs=None,
         strict=False,
         stop_first=False):

    global _TEMP_DIR

    # Ideally nothing should touch the FS on import, but we do atm..
    # Get rid of all modules so QUODLIBET_USERDIR gets used everywhere.
    for key in sys.modules.keys():
        if key.startswith('quodlibet'):
            del (sys.modules[key])

    # create a user dir in /tmp
    _TEMP_DIR = tempfile.mkdtemp(prefix="QL-TEST-")
    user_dir = tempfile.mkdtemp(prefix="QL-USER-", dir=_TEMP_DIR)
    os.environ['QUODLIBET_USERDIR'] = user_dir

    path = os.path.dirname(__file__)
    if subdirs is None:
        subdirs = []

    import quodlibet
    quodlibet._dbus_init()
    quodlibet._gtk_init()
    quodlibet._python_init()

    # make glib warnings fatal
    if strict:
        from gi.repository import GLib
        GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL
                                  | GLib.LogLevelFlags.LEVEL_ERROR
                                  | GLib.LogLevelFlags.LEVEL_WARNING)

    suites = []
    abstract = []

    def discover_tests(mod):
        for k in vars(mod):
            value = getattr(mod, k)

            if value not in (TestCase, AbstractTestCase) and \
                    inspect.isclass(value) and issubclass(value, TestCase):
                if AbstractTestCase in value.__bases__:
                    abstract.append(value)
                elif value not in skipped:
                    suites.append(value)

    if main:
        for name in os.listdir(path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, name[:-3]]), {}, {}, [])
                discover_tests(getattr(mod, name[:-3]))

    for subdir in subdirs:
        sub_path = os.path.join(path, subdir)
        for name in os.listdir(sub_path):
            if fnmatch.fnmatch(name, "test_*.py"):
                mod = __import__(".".join([__name__, subdir, name[:-3]]), {},
                                 {}, [])
                discover_tests(getattr(getattr(mod, subdir), name[:-3]))

    # check if each abstract class is actually used (also by skipped ones)
    unused_abstract = set(abstract)
    for case in suites:
        unused_abstract -= set(case.__mro__)
    for case in skipped:
        unused_abstract -= set(case.__mro__)
    if unused_abstract:
        raise Exception("The following abstract test cases have no "
                        "implementation: %r" % list(unused_abstract))

    for case in skipped:
        # don't warn for tests we won't run anyway
        if run and case not in run:
            continue
        name = "%s.%s" % (case.__module__, case.__name__)
        reason = skipped_reason.get(case, "??")
        print_w("Skipped test: %s (%s)" % (name, reason))

    import quodlibet.config

    # emulate python2.7 behavior
    def setup_test(test):
        if hasattr(TestCase, "setUpClass"):
            return
        if hasattr(test, "setUpClass"):
            test.setUpClass()

    def teardown_test(test):
        if hasattr(TestCase, "setUpClass"):
            return
        if hasattr(test, "tearDownClass"):
            test.tearDownClass()

    runner = Runner()
    failures = errors = 0
    use_suites = filter(filter_func, suites)
    for test in sorted(use_suites, key=repr):
        if (not run or test.__name__ in run or test.__module__[11:] in run):
            setup_test(test)
            df, de = runner.run(test)
            if stop_first and (df or de):
                break
            failures += df
            errors += de
            teardown_test(test)
            quodlibet.config.quit()

    try:
        shutil.rmtree(_TEMP_DIR)
    except EnvironmentError:
        pass

    return failures, errors
Example #25
0
 def main(self): # pylint: disable=no-self-use
     # Some ATK relative warnings are called during launching GtkWindow.
     flags = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL)
     Gtk.main()
     GLib.log_set_always_fatal(flags)
Example #26
0
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)