Exemple #1
0
 def raise_keyb_from_match():
     if sys.version_info > (2, 5):
         matcher = Raises(MatchesException(Exception))
     else:
         # On Python 2.4 KeyboardInterrupt is a StandardError subclass
         # but should propogate from less generic exception matchers
         matcher = Raises(MatchesException(EnvironmentError))
     matcher.match(self.raiser)
Exemple #2
0
 def test_not_reentrant(self):
     # A function decorated as not being re-entrant will raise a
     # _spinner.ReentryError if it is called while it is running.
     calls = []
     @_spinner.not_reentrant
     def log_something():
         calls.append(None)
         if len(calls) < 5:
             log_something()
     self.assertThat(
         log_something, Raises(MatchesException(_spinner.ReentryError)))
     self.assertEqual(1, len(calls))
Exemple #3
0
    def test_view_range_factory(self):
        # Test the view range factory is properly configured.
        view = create_initialized_view(self.pillar, name='+sharing')
        range_factory = view.grantees().batch.range_factory

        def test_range_factory():
            row = range_factory.resultset.get_plain_result_set()[0]
            range_factory.getOrderValuesFor(row)

        self.assertThat(
            test_range_factory,
            Not(Raises(MatchesException(StormRangeFactoryError))))
Exemple #4
0
 def test_fast_sigint_raises_no_result_error(self):
     # If we get a SIGINT during a run, we raise _spinner.NoResultError.
     SIGINT = getattr(signal, 'SIGINT', None)
     if not SIGINT:
         self.skipTest("SIGINT not available")
     reactor = self.make_reactor()
     spinner = self.make_spinner(reactor)
     timeout = self.make_timeout()
     reactor.callWhenRunning(os.kill, os.getpid(), SIGINT)
     self.assertThat(lambda:spinner.run(timeout * 5, defer.Deferred),
         Raises(MatchesException(_spinner.NoResultError)))
     self.assertEqual([], spinner._clean())
Exemple #5
0
 def test_notexpr(self):
     for text, node in (
         ('1', _Literal('1')),
         ('a', _Literal('a')),
         ('a1', _Literal('a1')),
         ('$', _Literal('$')),
         ('$1', _Literal('$1')),
     ):
         g = _grammar(text)
         self.expectThat(g.notexpr(), Equals(node))
     for expr in ('$a', ):
         g = _grammar(expr)
         self.expectThat(g.notexpr, Raises())
Exemple #6
0
def _raises_invalid_signature(**kwargs):
    """
    Helper function to create a matcher that matches callables that, when
    executed, raise an ``InvalidSignature`` that is equal to an
    ``InvalidSignature`` created with the passed in keyword arguments.

    :param **kwargs: keyword arguments to pass into an ``InvalidSignature``
        constructor.

    :returns: A matcher to use in tests.
    """
    return Raises(
        MatchesException(InvalidSignature, Equals(InvalidSignature(**kwargs))))
Exemple #7
0
 def test_render_template_raises_PowerActionFail(self):
     # If not enough arguments are supplied to fill in template
     # variables then a PowerActionFail is raised.
     pa = PowerAction(POWER_TYPE.WAKE_ON_LAN)
     template_name = factory.getRandomString()
     template = ShellTemplate("template: {{mac}}", name=template_name)
     self.assertThat(
         lambda: pa.render_template(template),
         Raises(
             MatchesException(
                 PowerActionFail,
                 ".*name 'mac' is not defined at line \d+ column \d+ "
                 "in file %s" % re.escape(template_name))))
Exemple #8
0
 def raise_keyb_from_match():
     if sys.version_info > (2, 5):
         matcher = Raises(MatchesException(Exception))
     else:
         # On Python 2.4 KeyboardInterrupt is a StandardError subclass
         # but should propogate from less generic exception matchers
         matcher = Raises(MatchesException(EnvironmentError))
     matcher.match(self.raiser)
Exemple #9
0
 def test_will_not_run_with_previous_junk(self):
     # If 'run' is called and there's still junk in the spinner's junk
     # list, then the spinner will refuse to run.
     from twisted.internet.protocol import ServerFactory
     reactor = self.make_reactor()
     spinner = self.make_spinner(reactor)
     timeout = self.make_timeout()
     spinner.run(timeout,
                 reactor.listenTCP,
                 0,
                 ServerFactory(),
                 interface='127.0.0.1')
     self.assertThat(lambda: spinner.run(timeout, lambda: None),
                     Raises(MatchesException(_spinner.StaleJunkError)))
Exemple #10
0
 def test_deeper_stack(self):
     calls = []
     @_spinner.not_reentrant
     def g():
         calls.append(None)
         if len(calls) < 5:
             f()
     @_spinner.not_reentrant
     def f():
         calls.append(None)
         if len(calls) < 5:
             g()
     self.assertThat(f, Raises(MatchesException(_spinner.ReentryError)))
     self.assertEqual(2, len(calls))
Exemple #11
0
    def test__run_prepared_result_does_not_mask_keyboard(self):
        class Case(TestCase):
            def test(self):
                raise KeyboardInterrupt("go")

        case = Case('test')
        run = RunTest(case)
        run.result = ExtendedTestResult()
        self.assertThat(lambda: run._run_prepared_result(run.result),
                        Raises(MatchesException(KeyboardInterrupt)))
        self.assertEqual([('startTest', case), ('stopTest', case)],
                         run.result._events)
        # tearDown is still run though!
        self.assertEqual(True, getattr(case, '_TestCase__teardown_called'))
Exemple #12
0
 def test_no_name(self):
     """
     Dicts with no ``name`` raise an error that helps with debugging.
     """
     selfLink = u"BADSELF"
     self.assertThat(
         lambda: _create_poller({u'selfLink': selfLink}),
         Raises(
             MatchesException(
                 MalformedOperation,
                 MatchesStructure(message=MatchesAll(
                     Contains('name'),  # Missing key
                     Contains(selfLink),  # part of the operation
                 )))))
Exemple #13
0
    def test_KeyboardInterrupt_match_Exception_propogates(self):
        # If the raised exception isn't matched, and it is not a subclass of
        # Exception, it is propogated.
        match_keyb = Raises(MatchesException(KeyboardInterrupt))

        def raise_keyb_from_match():
            if sys.version_info > (2, 5):
                matcher = Raises(MatchesException(Exception))
            else:
                # On Python 2.4 KeyboardInterrupt is a StandardError subclass
                # but should propogate from less generic exception matchers
                matcher = Raises(MatchesException(EnvironmentError))
            matcher.match(self.raiser)

        self.assertThat(raise_keyb_from_match, match_keyb)
Exemple #14
0
class TestRaisesInterface(TestCase, TestMatchersInterface):

    matches_matcher = Raises()

    def boom():
        raise Exception('foo')

    matches_matches = [boom]
    matches_mismatches = [lambda: None]

    # Tricky to get function objects to render constantly, and the interfaces
    # helper uses assertEqual rather than (for instance) DocTestMatches.
    str_examples = []

    describe_examples = []
Exemple #15
0
def raises_exception(cls, **attributes):
    def get_exception((type, exception, traceback)):
        return exception

    return Raises(
        AfterPreprocessing(
            get_exception,
            MatchesAll(
                IsInstance(cls),
                MatchesStructure(
                    **{k: Equals(v)
                       for (k, v) in attributes.items()}),
                first_only=True,
            ),
        ), )
Exemple #16
0
    def test_right_click_opens_quicklist_if_already_open(self):
        """A right click to another icon in the launcher must
        close the current open quicklist and open the other
        icons quicklist.
        lp:890991
        """

        icons = self.unity.launcher.model.get_launcher_icons()

        icon1_ql = self.open_quicklist_for_icon(icons[1])
        self.assertThat(icon1_ql.active, Eventually(Equals(True)))

        icon0_ql = self.open_quicklist_for_icon(icons[0])
        self.assertThat(icon0_ql.active, Eventually(Equals(True)))
        self.assertThat(icon1_ql.wait_until_destroyed, Not(Raises()))
Exemple #17
0
    def test__run_prepared_result_calls_stop_test_always(self):
        result = ExtendedTestResult()
        case = self.make_case()

        def inner():
            raise Exception("foo")

        run = RunTest(case, lambda x: x)
        run._run_core = inner
        self.assertThat(lambda: run.run(result),
                        Raises(MatchesException(Exception("foo"))))
        self.assertEqual([
            ('startTest', case),
            ('stopTest', case),
        ], result._events)
Exemple #18
0
    def test_run_with_patches_restores_on_exception(self):
        # run_with_patches restores the original values even when the function
        # raises an exception.
        def _():
            self.assertEquals(self.test_object.foo, 'haha')
            self.assertEquals(self.test_object.bar, 'blahblah')
            raise RuntimeError("Something went wrong!")

        self.monkey_patcher.add_patch(self.test_object, 'foo', 'haha')
        self.monkey_patcher.add_patch(self.test_object, 'bar', 'blahblah')

        self.assertThat(
            lambda: self.monkey_patcher.run_with_patches(_),
            Raises(MatchesException(RuntimeError("Something went wrong!"))))
        self.assertEquals(self.test_object.foo, self.original_object.foo)
        self.assertEquals(self.test_object.bar, self.original_object.bar)
Exemple #19
0
 def test_stringio(self):
     """A StringIO object should maybe get an ascii native str type"""
     try:
         from cStringIO import StringIO
         newio = False
     except ImportError:
         from io import StringIO
         newio = True
     sout = StringIO()
     soutwrapper = unicode_output_stream(sout)
     if newio:
         self.expectFailure("Python 3 StringIO expects text not bytes",
             self.assertThat, lambda: soutwrapper.write(self.uni),
             Not(Raises(MatchesException(TypeError))))
     soutwrapper.write(self.uni)
     self.assertEqual("pa???n", sout.getvalue())
Exemple #20
0
 def test_fast_keyboard_interrupt_stops_test_run(self):
     # If we get a SIGINT during a test run, the test stops and no more
     # tests run.
     SIGINT = getattr(signal, 'SIGINT', None)
     if not SIGINT:
         raise self.skipTest("SIGINT unavailable")
     class SomeCase(TestCase):
         def test_pause(self):
             return defer.Deferred()
     test = SomeCase('test_pause')
     reactor = self.make_reactor()
     timeout = self.make_timeout()
     runner = self.make_runner(test, timeout * 5)
     result = self.make_result()
     reactor.callWhenRunning(os.kill, os.getpid(), SIGINT)
     self.assertThat(lambda:runner.run(result),
         Raises(MatchesException(KeyboardInterrupt)))
Exemple #21
0
 def test_global_no_selfLink(self):
     """
     Dicts with ``name`` but no ``selfLink`` and no ``zone`` raise an error
     that will help in debugging.
     """
     name = u"RARENAME"
     self.assertThat(
         lambda: _create_poller({
             u'name': name,
         }),
         Raises(
             MatchesException(
                 MalformedOperation,
                 MatchesStructure(message=MatchesAll(
                     Contains('selfLink'),  # The missing key.
                     Contains(name),  # The name of the operation.
                 )))))
Exemple #22
0
 def test_zone_nolength_zone(self):
     """
     Dicts with ``name` and empty ``zone` raise an error that can assist in
     debugging.
     """
     name = u'CATACTAC'
     self.assertThat(
         lambda: _create_poller({
             u'name': name,
             u'zone': u''
         }),
         Raises(
             MatchesException(
                 MalformedOperation,
                 MatchesStructure(message=MatchesAll(
                     Contains('/zones/'),  # Expected format.
                     Contains(name),  # The name of the operation.
                 )))))
Exemple #23
0
    def test__run_prepared_result_does_not_mask_keyboard(self):
        tearDownRuns = []

        class Case(TestCase):
            def test(self):
                raise KeyboardInterrupt("go")

            def _run_teardown(self, result):
                tearDownRuns.append(self)
                return super()._run_teardown(result)

        case = Case('test')
        run = RunTest(case)
        run.result = ExtendedTestResult()
        self.assertThat(lambda: run._run_prepared_result(run.result),
                        Raises(MatchesException(KeyboardInterrupt)))
        self.assertEqual([('startTest', case), ('stopTest', case)],
                         run.result._events)
        # tearDown is still run though!
        self.assertThat(tearDownRuns, HasLength(1))
Exemple #24
0
 def test_zone_malformed_zone(self):
     """
     Dicts with ``name`` and malformed ``zone`` without enough slashes raise
     an error that can assist in debugging.
     """
     name = u'CATACTAC'
     zone = u'BADZONEBAD'
     self.assertThat(
         lambda: _create_poller({
             u'name': name,
             u'zone': zone
         }),
         Raises(
             MatchesException(
                 MalformedOperation,
                 MatchesStructure(message=MatchesAll(
                     Contains(zone),  # Actual zone.
                     Contains('/zones/'),  # Expected format.
                     Contains(name),  # The name of the operation.
                 )))))
Exemple #25
0
    def test__run_prepared_result_uncaught_Exception_raised(self):
        e = KeyError('Yo')

        class Case(TestCase):
            def test(self):
                raise e

        case = Case('test')
        log = []

        def log_exc(self, result, err):
            log.append((result, err))

        run = RunTest(case, [(ValueError, log_exc)])
        run.result = ExtendedTestResult()
        self.assertThat(lambda: run._run_prepared_result(run.result),
                        Raises(MatchesException(KeyError)))
        self.assertEqual([('startTest', case), ('stopTest', case)],
                         run.result._events)
        self.assertEqual([], log)
Exemple #26
0
    def test_DistributionBuildRecordsView__range_factory(self):
        # DistributionBuildRecordsView works with StormRangeFactory:
        # StormRangeFactory requires result sets where the sort order
        # is specified by Storm Column objects or by Desc(storm_column).
        # DistributionBuildRecordsView gets its resultset from
        # IDistribution.getBuildRecords(); the sort order of the
        # result set depends on the parameter build_state.
        # The order expressions for all possible values of build_state
        # are usable by StormRangeFactory.
        distroseries = self.factory.makeDistroSeries()
        distribution = distroseries.distribution
        das = self.factory.makeDistroArchSeries(distroseries=distroseries)
        for status in BuildStatus.items:
            build = self.factory.makeBinaryPackageBuild(
                distroarchseries=das,
                archive=distroseries.main_archive,
                status=status)
            # BPBs in certain states need a bit tweaking to appear in
            # the result of getBuildRecords().
            if status == BuildStatus.FULLYBUILT:
                build.updateStatus(BuildStatus.BUILDING,
                                   force_invalid_transition=True)
                build.updateStatus(BuildStatus.FULLYBUILT)
            elif status in (BuildStatus.NEEDSBUILD, BuildStatus.BUILDING):
                build.queueBuild()
        for status in ('built', 'failed', 'depwait', 'chrootwait',
                       'superseded', 'uploadfail', 'all', 'building',
                       'pending'):
            view = create_initialized_view(distribution,
                                           name="+builds",
                                           form={'build_state': status})
            view.setupBuildList()
            range_factory = view.batchnav.batch.range_factory

            def test_range_factory():
                row = range_factory.resultset.get_plain_result_set()[0]
                range_factory.getOrderValuesFor(row)

            self.assertThat(
                test_range_factory,
                Not(Raises(MatchesException(StormRangeFactoryError))))
Exemple #27
0
 def test_expr(self):
     for text, node in (
         ('$a', _SimpleExpression('a', '$a')),
         ('$a1', _SimpleExpression('a1', '$a1')),
         ('${ab}', _SimpleExpression('ab', '${ab}')),
         ('${ab:-}', _Expression('ab', ':', '-', [], '${ab:-}')),
         ('${ab:-${foo}}',
          _Expression('ab', ':', '-', [_SimpleExpression('foo', '${foo}')],
                      '${ab:-${foo}}')),
         ('${ab:-${cd:-${foo}}}',
          _Expression('ab', ':', '-', [
              _Expression('cd', ':', '-',
                          [_SimpleExpression('foo', '${foo}')],
                          '${cd:-${foo}}'),
          ], '${ab:-${cd:-${foo}}}')),
     ):
         g = _grammar(text)
         self.expectThat(g.expr(), Equals(node))
     for notname in ('1', ' ', '{'):
         g = _grammar(notname)
         self.expectThat(g.expr, Raises())
Exemple #28
0
 def test_global_numerical_selfLink(self):
     """
     Dicts with ``name`` and a numerical ``selfLink`` and no ``zone`` raise
     an error that will help in debugging.
     """
     name = u"RARENAME"
     selfLink = 123
     self.assertThat(
         lambda: _create_poller({
             u'name': name,
             u'selfLink': selfLink
         }),
         Raises(
             MatchesException(
                 MalformedOperation,
                 MatchesStructure(message=MatchesAll(
                     Contains(unicode(selfLink)),  # The actual value.
                     Contains('/global/operations/'),  # Expected url.
                     Contains('selfLink'),  # The malformed key.
                     Contains(name),  # The name of the operation.
                 )))))
Exemple #29
0
    def test_can_handle_non_unicode_stdout_and_stderr(self):
        path = self.write_script(
            dedent("""\
            #!%s
            # -*- coding: utf-8 -*-
            from PyQt4.QtGui import QMainWindow, QApplication
            from sys import argv, stdout, stderr

            app = QApplication(argv)
            win = QMainWindow()
            win.show()
            stdout.write('Hello\x88stdout')
            stdout.flush()
            stderr.write('Hello\x88stderr')
            stderr.flush()
            app.exec_()
            """ % sys.executable))
        self.launch_test_application(path, app_type='qt')
        details_dict = self.getDetails()
        for name, content_obj in details_dict.items():
            self.assertThat(lambda: content_obj.as_text(), Not(Raises()))
Exemple #30
0
 def assertRaises(self, excClass, callableObj, *args, **kwargs):
     """Fail unless an exception of class excClass is thrown
        by callableObj when invoked with arguments args and keyword
        arguments kwargs. If a different type of exception is
        thrown, it will not be caught, and the test case will be
        deemed to have suffered an error, exactly as for an
        unexpected exception.
     """
     class ReRaiseOtherTypes(object):
         def match(self, matchee):
             if not issubclass(matchee[0], excClass):
                 reraise(*matchee)
     class CaptureMatchee(object):
         def match(self, matchee):
             self.matchee = matchee[1]
     capture = CaptureMatchee()
     matcher = Raises(MatchesAll(ReRaiseOtherTypes(),
             MatchesException(excClass), capture))
     our_callable = Nullary(callableObj, *args, **kwargs)
     self.assertThat(our_callable, matcher)
     return capture.matchee
Exemple #31
0
    def test__run_prepared_result_uncaught_Exception_triggers_error(self):
        # https://bugs.launchpad.net/testtools/+bug/1364188
        # When something isn't handled, the test that was
        # executing has errored, one way or another.
        e = SystemExit(0)

        class Case(TestCase):
            def test(self):
                raise e

        case = Case('test')
        log = []

        def log_exc(self, result, err):
            log.append((result, err))

        run = RunTest(case, [], log_exc)
        run.result = ExtendedTestResult()
        self.assertThat(lambda: run._run_prepared_result(run.result),
                        Raises(MatchesException(SystemExit)))
        self.assertEqual([('startTest', case), ('stopTest', case)],
                         run.result._events)
        self.assertEqual([(run.result, e)], log)
Exemple #32
0
 def raise_keyb_from_match():
     matcher = Raises()
     matcher.match(self.raiser)