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)
def test_quicklist_action_uses_startup_notification(self): """Tests that quicklist uses startup notification protocol.""" self.register_nautilus() self.addCleanup(self.close_all_windows, "Nautilus") self.process_manager.start_app_window("Calculator") self.process_manager.start_app(self.app_name) nautilus_icon = self.unity.launcher.model.get_icon( desktop_id="org.gnome.Nautilus.desktop") ql = self.open_quicklist_for_icon(nautilus_icon) de = self.get_desktop_entry("Nautilus") new_window_action_name = de.get("Name", group="Desktop Action Window", locale=True) self.assertThat(new_window_action_name, NotEquals(None)) new_win_ql_item_fn = lambda: ql.get_quicklist_item_by_text( new_window_action_name) self.assertThat(new_win_ql_item_fn, Eventually(NotEquals(None))) new_win_ql_item = new_win_ql_item_fn() ql.click_item(new_win_ql_item) nautilus_windows_fn = lambda: self.process_manager.get_open_windows_by_application( "Nautilus") self.assertThat(lambda: len(nautilus_windows_fn()), Eventually(Equals(1))) [nautilus_window] = nautilus_windows_fn() self.assertThat(new_win_ql_item.wait_until_destroyed, Not(Raises()))
def test_keyboard_interrupt_not_caught(self): # If a cleanup raises KeyboardInterrupt, it gets reraised. def raiseKeyboardInterrupt(): raise KeyboardInterrupt() self.test.addCleanup(raiseKeyboardInterrupt) self.assertThat(lambda:self.test.run(self.logging_result), Raises(MatchesException(KeyboardInterrupt)))
def test_execute_raises_PowerActionFail_when_script_fails(self): path = self._create_template_file("this_is_not_valid_shell") self.assertThat( lambda: self.run_action(path), Raises( MatchesException(PowerActionFail, "ether_wake failed.* return.* 127")))
def test_timeout(self): # If the function takes too long to run, we raise a # _spinner.TimeoutError. timeout = self.make_timeout() self.assertThat( lambda: self.make_spinner().run(timeout, lambda: defer.Deferred()), Raises(MatchesException(_spinner.TimeoutError)))
def test_not_reentrant(self): # run_in_reactor raises an error if it is called inside another call # to run_in_reactor. spinner = self.make_spinner() self.assertThat(lambda: spinner.run( self.make_timeout(), spinner.run, self.make_timeout(), lambda: None), Raises(MatchesException(_spinner.ReentryError)))
def test_exception_reraised(self): # If the given function raises an error, run_in_reactor re-raises that # error. self.assertThat( lambda: self.make_spinner().run(self.make_timeout(), lambda: 1 / 0 ), Raises(MatchesException(ZeroDivisionError)))
def test_next_stream_corruption_error(self): repo = self.useFixture(FileRepositoryFixture(self)).repo open(os.path.join(repo.base, 'next-stream'), 'wb').close() self.assertThat( repo.count, Raises(MatchesException( ValueError("Corrupt next-stream file: ''"))))
def test_fires_after_timeout(self): # If we timeout, but the Deferred actually ends up firing after the # time out (perhaps because Spinner's clean-up code is buggy, or # perhaps because the code responsible for the callback is in a # thread), then the next run of a spinner works as intended, # completely isolated from the previous run. # Ensure we've timed out, and that we have a handle on the Deferred # that didn't fire. reactor = self.make_reactor() spinner1 = self.make_spinner(reactor) timeout = self.make_timeout() deferred1 = defer.Deferred() self.expectThat(lambda: spinner1.run(timeout, lambda: deferred1), Raises(MatchesException(_spinner.TimeoutError))) # Make a Deferred that will fire *after* deferred1 as long as the # reactor keeps spinning. We don't care that it's a callback of # deferred1 per se, only that it strictly fires afterwards. marker = object() deferred2 = defer.Deferred() deferred1.addCallback( lambda ignored: reactor.callLater(0, deferred2.callback, marker)) def fire_other(): """Fire Deferred from the last spin while waiting for this one.""" deferred1.callback(object()) return deferred2 spinner2 = self.make_spinner(reactor) self.assertThat(spinner2.run(timeout, fire_other), Is(marker))
def test_launch_application_doesnt_raise(self): test_desktop_file = self.getUniqueString() process = Mock() process.launch_uris_as_manager.side_effect = TypeError( "Argument 2 does not allow None as a value") with patch.object(_b.Gio.DesktopAppInfo, 'new', return_value=process): self.assertThat(lambda: _launch_application(test_desktop_file, []), Not(Raises()))
def test_get_package_location_can_import_package(self): self.create_empty_package_file('__init__.py') with working_dir(self.sandbox_dir): self.assertThat( lambda: get_package_location(self.test_module_name), Not(Raises()), verbose=True)
def test_name(self): for name in ('a', '_', 'A', 'ba', 'b_', 'b1', 'bA', '_a', '_1', '_A', 'Aa', 'A_', 'A0', 'adsd2343aweawe_'): g = _grammar(name) self.expectThat(g.name(), Equals(name)) for notname in ('1', ' ', '{'): g = _grammar(notname) self.expectThat(g.name, Raises())
def test_KeyboardInterrupt_propogates(self): # The default 'it raised' propogates KeyboardInterrupt. match_keyb = Raises(MatchesException(KeyboardInterrupt)) def raise_keyb_from_match(): matcher = Raises() matcher.match(self.raiser) self.assertThat(raise_keyb_from_match, match_keyb)
def test_assertRaises_function_repr_in_exception(self): # When assertRaises fails, it includes the repr of the invoked # function in the error message, so it's easy to locate the problem. def foo(): """An arbitrary function.""" pass self.assertThat( lambda: self.assertRaises(Exception, foo), Raises( MatchesException(self.failureException, '.*%r.*' % (foo,))))
def test_follow_file_does_not_raise_on_IOError(self): fake_test = Mock() content_name = self.getUniqueString() with NamedTemporaryFile() as f: os.chmod(f.name, 0) self.assertThat( lambda: follow_file(f.name, fake_test, content_name), Not(Raises()) )
def test_failure(self): # _spinner.extract_result raises the failure's exception if it's given # a Deferred that is failing. try: 1 / 0 except ZeroDivisionError: f = Failure() d = defer.fail(f) self.assertThat(lambda: _spinner.extract_result(d), Raises(MatchesException(ZeroDivisionError)))
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()) self.assertThat(lambda: spinner.run(timeout, lambda: None), Raises(MatchesException(_spinner.StaleJunkError)))
def test_can_follow_file_with_binary_content(self): open_args = dict(buffering=0) with NamedTemporaryFile(**open_args) as temp_file: log_debug_object = d.LogFileDebugObject(self.fake_caseAddDetail, temp_file.name) log_debug_object.setUp() temp_file.write("Hello\x88World".encode()) log_debug_object.cleanUp() args, _ = self.fake_caseAddDetail.call_args self.assertThat(args[1].as_text, Not(Raises()))
def test_oops_directory_without_reporter(self): # It is an error to omit the OOPS reporter if directory is specified. config = ( 'oops:\n' ' directory: /tmp/oops\n' ) expected = MatchesException( formencode.Invalid, "oops: You must give a value for reporter") self.assertThat( partial(Config.parse, config), Raises(expected))
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())
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))))
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))
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))))
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))))
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())
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'))
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))
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 )))))
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)
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()))