Example #1
0
    def test_base_class(self):
        headers = {
            'X-Error-Title': 'Storage service down',
            'X-Error-Description': ('The configured storage service is not '
                                    'responding to requests. Please contact '
                                    'your service provider.'),
            'X-Error-Status': falcon.HTTP_503
        }

        expected_body = {
            'title': 'Storage service down',
            'description': ('The configured storage service is not '
                            'responding to requests. Please contact '
                            'your service provider.'),
            'code': 10042,
        }

        # Try it with Accept: */*
        headers['Accept'] = '*/*'
        body = self.simulate_request('/fail', headers=headers, decode='utf-8')

        self.assertEqual(self.srmock.status, headers['X-Error-Status'])
        self.assertThat(lambda: json.loads(body), Not(raises(ValueError)))
        self.assertEqual(expected_body, json.loads(body))

        # Now try it with application/json
        headers['Accept'] = 'application/json'
        body = self.simulate_request('/fail', headers=headers, decode='utf-8')

        self.assertEqual(self.srmock.status, headers['X-Error-Status'])
        self.assertThat(lambda: json.loads(body), Not(raises(ValueError)))
        self.assertEqual(json.loads(body), expected_body)
Example #2
0
    def test_base_class(self):
        headers = {
            'X-Error-Title': 'Storage service down',
            'X-Error-Description': ('The configured storage service is not '
                                    'responding to requests. Please contact '
                                    'your service provider'),
            'X-Error-Status': falcon.HTTP_503
        }

        expected_body = [
            b'{\n'
            b'    "title": "Storage service down",\n'
            b'    "description": "The configured storage service is not '
            b'responding to requests. Please contact your service provider",\n'
            b'    "code": 10042\n'
            b'}'
        ]

        # Try it with Accept: */*
        headers['Accept'] = '*/*'
        body = self.simulate_request('/fail', headers=headers)
        self.assertEqual(self.srmock.status, headers['X-Error-Status'])
        self.assertThat(lambda: json.loads(body[0]), Not(raises(ValueError)))
        self.assertEqual(expected_body, body)

        # Now try it with application/json
        headers['Accept'] = 'application/json'
        body = self.simulate_request('/fail', headers=headers)
        self.assertEqual(self.srmock.status, headers['X-Error-Status'])
        self.assertThat(lambda: json.loads(body[0]), Not(raises(ValueError)))
        self.assertEqual(body, expected_body)
Example #3
0
 def test_find_invalid_usage(self):
     """
     Passing fewer or more than one query raises `ValueError`.
     """
     enum = Enum('doc', [])
     self.assertThat(enum.find, raises(ValueError))
     self.assertThat(
         lambda: enum.find(foo=u'a', bar=u'b'),
         raises(ValueError))
Example #4
0
 def test_must_specify_tags_with_tags_options(self):
     fn = lambda: safe_parse_arguments(['--fail', 'foo', '--tag'])
     self.assertThat(
         fn,
         MatchesAny(
             raises(RuntimeError('--tag option requires 1 argument')),
             raises(RuntimeError('--tag option requires an argument')),
         )
     )
 def test_TestCommand_get_run_command_outside_setUp_fails(self):
     self.dirty()
     ui = UI()
     ui.here = self.tempdir
     command = TestCommand(ui, None)
     self.set_config('[DEFAULT]\ntest_command=foo\n')
     self.assertThat(command.get_run_command, raises(TypeError))
     command.setUp()
     command.cleanUp()
     self.assertThat(command.get_run_command, raises(TypeError))
Example #6
0
 def test_provision_at_cap(self):
     source = model.Source(None, None)
     c = cache.Cache("foo", memory.Store({}), source, maximum=2)
     c.provision(2)
     self.assertThat(lambda: c.provision(1), raises(ValueError))
     # The source was not interrogated for more resources.
     self.assertEqual(['2'], source.provision(1))
     with read_locked(c.store):
         self.assertEqual('0,1', c.store['pool/foo'])
         self.assertThat(lambda:c.store['resource/2'], raises(KeyError))
Example #7
0
 def test_delete(self):
     s = self.make_store()
     s2 = self.make_store()
     with write_locked(s):
         s['foo'] = 'bar'
     with write_locked(s):
         del s['foo']
     with read_locked(s):
         self.assertThat(lambda:s['foo'], raises(KeyError))
     # The change is immediately visible to other store instances.
     with read_locked(s2):
         self.assertThat(lambda:s2['foo'], raises(KeyError))
Example #8
0
 def test_discard_force_ignores_reserve(self):
     source = model.Source(None, None)
     c = cache.Cache("foo", memory.Store({}), source, reserve=1)
     c.discard(c.provision(2), force=True)
     self.assertThat(source._calls, MatchesAny(
         Equals([('provision', 2), ('discard', ['0', '1'])]),
         Equals([('provision', 2), ('discard', ['1', '0'])])))
     # The instance should have been unmapped in both directions from the
     # store.
     with read_locked(c.store):
         self.assertEqual('', c.store['pool/foo'])
         self.assertThat(lambda:c.store['resource/0'], raises(KeyError))
         self.assertThat(lambda:c.store['resource/1'], raises(KeyError))
Example #9
0
 def test_header_types(self):
     """
     Header keys and values must be bytes, not unicode.
     """
     self.assertThat(
         lambda: Request(method='get', url='http://google.com/',
                         headers={u'foo': b'bar'}),
         raises(TypeError("headers key {0!r} is not bytes".format(u'foo')))
         )
     self.assertThat(
         lambda: Request(method='get', url='http://google.com/',
                         headers={b'foo': u'bar'}),
         raises(TypeError("headers value {0!r} is not bytes".format(u'bar')))
         )
Example #10
0
    def test_not_set_delta_property_correctly(self):
        self.assertThat(
            lambda: deltas.BaseDeltasGenerator(
                source_path=self.source_file, target_path=self.target_file,
                delta_format=None, delta_tool_path=self.delta_tool_path),
            m.raises(deltas.errors.DeltaFormatError)
        )
        exception = self.assertRaises(deltas.errors.DeltaFormatError,
                                      deltas.BaseDeltasGenerator,
                                      source_path=self.source_file,
                                      target_path=self.target_file,
                                      delta_format=None,
                                      delta_tool_path='/usr/bin/xdelta3')
        expected = 'delta_format must be set in subclass!'
        self.assertEqual(str(exception), expected)

        self.assertThat(
            lambda: deltas.BaseDeltasGenerator(
                source_path=self.source_file, target_path=self.target_file,
                delta_format='xdelta3',
                delta_tool_path=None),
            m.raises(deltas.errors.DeltaToolError)
        )
        exception = self.assertRaises(deltas.errors.DeltaToolError,
                                      deltas.BaseDeltasGenerator,
                                      source_path=self.source_file,
                                      target_path=self.target_file,
                                      delta_format='xdelta3',
                                      delta_tool_path=None)
        expected = 'delta_tool_path must be set in subclass!'
        self.assertEqual(str(exception), expected)

        self.assertThat(
            lambda: deltas.BaseDeltasGenerator(
                source_path=self.source_file,
                target_path=self.target_file,
                delta_format='not-defined',
                delta_tool_path='/usr/bin/xdelta3'),
            m.raises(deltas.errors.DeltaFormatOptionError)
        )
        exception = self.assertRaises(deltas.errors.DeltaFormatOptionError,
                                      deltas.BaseDeltasGenerator,
                                      source_path=self.source_file,
                                      target_path=self.target_file,
                                      delta_format='invalid-delta-format',
                                      delta_tool_path=self.delta_tool_path)
        expected = """delta_format must be a option in ['xdelta3'].
for now delta_format='invalid-delta-format'"""
        self.assertEqual(str(exception), expected)
Example #11
0
    def test_duplicateHandlers(self):
        """
        Only one handler for an accept type may be specified.
        """
        @implementer(INegotiableResource)
        class _BarJSON(object):
            contentType = b'application/json'
            acceptTypes = [b'application/json']

        self.assertThat(
            partial(ContentTypeNegotiator, [_FooJSON(), _FooJSON()]),
            raises(ValueError))
        self.assertThat(
            partial(ContentTypeNegotiator, [_FooJSON(), _BarJSON()]),
            raises(ValueError))
Example #12
0
 def test_discard_multiple(self):
     source = model.Source(None, None)
     c = cache.Cache("foo", memory.Store({}), source)
     c.provision(4)
     c.discard(['foo-0', 'foo-2'])
     self.assertEqual(2, c.in_use())
     self.assertEqual(0, c.cached())
     self.assertEqual(
         [('provision', 4), ('discard', ['0', '2'])], source._calls)
     # The instances should have been unmapped in both directions from the
     # store.
     with read_locked(c.store):
         self.assertEqual('1,3', c.store['pool/foo'])
         self.assertThat(lambda:c.store['resource/0'], raises(KeyError))
         self.assertThat(lambda:c.store['resource/2'], raises(KeyError))
Example #13
0
 def test_rejects_doubledash(self):
     base = self.useFixture(TempDir()).path
     arg = path.ExistingPathArgument('path')
     self.addCleanup(os.chdir, os.getcwd())
     os.chdir(base)
     with open('--', 'wt') as f:pass
     self.assertThat(lambda: arg.parse(['--']), raises(ValueError))
Example #14
0
 def test_duplicate_values(self):
     """
     Constructing an enumeration with duplicate values results in
     `ValueError` being raised.
     """
     values = [
         EnumItem(u'foo', u'Foo'),
         EnumItem(u'bar', u'Bar'),
         EnumItem(u'foo', u'Not Foo', quux=u'frob')]
     self.assertThat(
         lambda: Enum('doc', values),
         raises(ValueError))
     pairs = [(e.value, e.desc) for e in values]
     self.assertThat(
         lambda: Enum.from_pairs('doc', pairs),
         raises(ValueError))
Example #15
0
 def test_maximum_exceeded(self):
     if not self.test_maximum:
         self.skip("Cannot test maximum.")
     source = self.make_source()
     self.assertThat(lambda: source.provision(self.test_maximum + 1),
         raises(TooManyInstances))
     source.discard(source.provision(self.test_maximum))
 def test_format_version_1(self):
     """Initial format without version marker is rejected"""
     self.make_bug_summary("1", format_version=1)
     tracker = self.get_tracker()
     self.assertThat(lambda: tracker.getRemoteStatus("1"),
         raises(SummaryParseError))
     tracker.getRemoteImportance("1")
 def test_format_version_4(self):
     """A hypothetical summary format version 4 is rejected"""
     self.make_bug_summary("1", format_version=4)
     tracker = self.get_tracker()
     self.assertThat(lambda: tracker.getRemoteStatus("1"),
         raises(SummaryVersionError))
     tracker.getRemoteImportance("1")
Example #18
0
    def test_exc_value(self):
        e = RuntimeError("You lose!")

        def raiser():
            raise e

        self.assertThat(raiser, raises(e))
Example #19
0
    def test_epic_fail_xml(self):
        headers = {
            'Accept': 'text/xml'
        }

        expected_body = ('<?xml version="1.0" encoding="UTF-8"?>' +
                         '<error>' +
                         '<title>Internet crashed</title>' +
                         '<description>' +
                         'Catastrophic weather event due to climate change.' +
                         '</description>' +
                         '<code>8733224</code>' +
                         '<link>' +
                         '<text>Drill baby drill!</text>' +
                         '<href>http://example.com/api/climate</href>' +
                         '<rel>help</rel>' +
                         '</link>' +
                         '</error>')

        body = self.simulate_request('/fail', headers=headers, method='PUT',
                                     decode='utf-8')

        self.assertEqual(self.srmock.status, falcon.HTTP_792)
        self.assertThat(lambda: et.fromstring(body), Not(raises(ValueError)))
        self.assertEqual(body, expected_body)
Example #20
0
 def test_none(self):
     """
     Passing ``None`` as the task value raises ``ValueError``
     """
     self.assertThat(
         lambda: _TaskNode(task=None),
         raises(ValueError))
Example #21
0
 def test_none(self):
     """
     Cannot create a task name for ``None``.
     """
     self.assertThat(
         lambda: task_name(None),
         raises(ValueError))
Example #22
0
    def test_greeting_mouse(self):
        """Greeting with mouse navigation"""

        entry_name = self.app.select_single(BuilderName='entry_name')
        entry_color = self.app.select_single(BuilderName='entry_color')

        # FIXME: This isn't necessary for real X, but under Xvfb there is no
        # default focus sometimes
        if not entry_name.has_focus:
            self.mouse.click_object(entry_name)

        # type in name and color
        self.keyboard.type('Joe')
        self.mouse.click_object(entry_color)
        self.keyboard.type('blue')

        # entries should now have the typed text
        self.assertThat(entry_name.text, Eventually(Equals('Joe')))
        self.assertThat(entry_color.text, Eventually(Equals('blue')))

        # should not have any dialogs
        self.assertThat(
            lambda: self.app.select_single('GtkMessageDialog'),
            raises(StateNotFoundError)
        )

        # focus and activate the "Greet" button
        btn = self.app.select_single('GtkButton', label='Greet')
        self.assertNotEqual(btn, None)
        self.mouse.click_object(btn)

        # should get the greeting dialog
        md = self.app.wait_select_single('GtkMessageDialog', visible=True)

        # we expect the message dialog to show the corresponding greeting
        self.assertNotEqual(md.select_single('GtkLabel',
                                             label=u'Hello Joe, you like blue.'),
                            None)

        # close the dialog
        btn = md.select_single('GtkButton')
        self.mouse.click_object(btn)
        self.assertThat(
            lambda: self.app.select_single('GtkMessageDialog', visible=True),
            raises(StateNotFoundError)
        )
 def test_list_tests_nonzero_exit(self):
     ui, command = self.get_test_ui_and_cmd()
     ui.proc_results = [1]
     self.set_config(
         '[DEFAULT]\ntest_command=foo $LISTOPT $IDLIST\ntest_id_list_default=whoo yea\n'
         'test_list_option=--list\n')
     fixture = self.useFixture(command.get_run_command())
     self.assertThat(lambda:fixture.list_tests(), raises(ValueError))
Example #24
0
 def test_error_bubbles_up(self):
     """
     When perform_effect raises an exception, it is raised up through
     sync_perform.
     """
     self.assertThat(
         lambda: sync_perform(Effect(ErrorIntent())),
         raises(ValueError('oh dear')))
 def test_get_test_run_missing_keyerror(self):
     repo = self.repo_impl.initialise(self.sample_url)
     result = repo.get_inserter()
     result.startTestRun()
     result.stopTestRun()
     inserted = result.get_id()
     self.assertThat(lambda:repo.get_test_run(inserted - 1),
         raises(KeyError))
Example #26
0
 def test_timeout(self):
     transport = self.useFixture(
         utils.RPCTransportFixture(self.conf, self.url)
     )
     target = oslo_messaging.Target(topic="no_such_topic")
     c = utils.ClientStub(transport.transport, target, timeout=1)
     self.assertThat(c.ping,
                     matchers.raises(oslo_messaging.MessagingTimeout))
Example #27
0
 def test_no_effect_handler(self):
     """
     When no perform_effect method is on the intent object, the default
     dispatcher raises :class:`NoEffectHandlerError`.
     """
     intent = object()
     self.assertThat(
         lambda: sync_perform(Effect(intent)),
         raises(NoEffectHandlerError(intent)))
Example #28
0
 def test_getattr_error(self):
     """
     Trying to access nonexistent additional enum values by attribute
     results in `AttributeError`.
     """
     item = EnumItem(u'foo', u'Foo', a=1)
     self.assertThat(
         lambda: item.b,
         raises(AttributeError))
Example #29
0
 def test_merge_startless_tasks(self):
     """
     Merging a task that will never have a start parent raises
     ``RuntimeError``.
     """
     tree = Tree()
     self.assertThat(
         lambda: tree.merge_tasks([action_task_end]),
         raises(RuntimeError))
    def test_set_ValueError(self):
        class Test(resource.Resource):
            attr = resource.prop("attr", type=int)

        t = Test()

        def should_raise():
            t.attr = "this is not an int"

        self.assertThat(should_raise, matchers.raises(ValueError))
Example #31
0
 def test_sa_warning(self):
     self.assertThat(
         lambda: warnings.warn('test sa warning error', exc.SAWarning),
         matchers.raises(exc.SAWarning))
Example #32
0
 def test_deprecation_warnings_are_raised_as_exceptions_in_tests(self):
     self.assertThat(
         lambda: warnings.warn('this is deprecated', DeprecationWarning),
         matchers.raises(DeprecationWarning))
 def test_timeout(self):
     transport = self.useFixture(utils.TransportFixture(self.url))
     target = oslo_messaging.Target(topic="no_such_topic")
     c = utils.ClientStub(transport.transport, target, timeout=1)
     self.assertThat(c.ping,
                     matchers.raises(oslo_messaging.MessagingTimeout))
 def test_exception(self):
     group = self.useFixture(utils.RpcServerGroupFixture(self.url))
     client = group.client(1)
     client.add(increment=2)
     f = lambda: client.subtract(increment=3)
     self.assertThat(f, matchers.raises(ValueError))
Example #35
0
 def test_no_command(self):
     arg = command.CommandArgument('name')
     self.assertThat(lambda: arg.parse(['one']),
         raises(ValueError("Could not find command 'one'.")))
    def test_from_id_with_bad_value(self):
        def should_raise():
            FakeResource.from_id(3.14)

        self.assertThat(should_raise, matchers.raises(ValueError))
Example #37
0
 def test_unexpected_exit(self):
     # if a test calls sys.exit it raises rather than exiting.
     self.assertThat(lambda: sys.exit(),
                     matchers.raises(unit.UnexpectedExit))
Example #38
0
 def test_bad_log(self):
     # If the arguments are invalid for the string in a log it raises an
     # exception during testing.
     self.assertThat(
         lambda: LOG.warn('String %(p1)s %(p2)s', {'p1': 'something'}),
         matchers.raises(KeyError))