def LanguageServerConnection_AddNotificationToQueue_RingBuffer_test():
  connection = MockConnection()
  notifications = connection._notifications

  # Queue empty

  assert_that( calling( notifications.get_nowait ), raises( queue.Empty ) )

  # Queue partially full, then drained

  connection._AddNotificationToQueue( 'one' )

  assert_that( notifications.get_nowait(), equal_to( 'one' ) )
  assert_that( calling( notifications.get_nowait ), raises( queue.Empty ) )

  # Queue full, then drained

  connection._AddNotificationToQueue( 'one' )
  connection._AddNotificationToQueue( 'two' )

  assert_that( notifications.get_nowait(), equal_to( 'one' ) )
  assert_that( notifications.get_nowait(), equal_to( 'two' ) )
  assert_that( calling( notifications.get_nowait ), raises( queue.Empty ) )

  # Queue full, then new notification, then drained

  connection._AddNotificationToQueue( 'one' )
  connection._AddNotificationToQueue( 'two' )
  connection._AddNotificationToQueue( 'three' )

  assert_that( notifications.get_nowait(), equal_to( 'two' ) )
  assert_that( notifications.get_nowait(), equal_to( 'three' ) )
  assert_that( calling( notifications.get_nowait ), raises( queue.Empty ) )
Example #2
0
    def test_options_validated_against_type(self):
        module_type = ModuleTypeFactory(
            name='some-graph',
            schema={
                "type": "object",
                "properties": {
                    "title": {
                        "type": "string",
                        "maxLength": 3
                    }
                }
            }
        )

        module = Module(
            slug='a-module',
            type=module_type,
            dashboard=self.dashboard_a,
            options={
                'title': 'bar'
            }
        )

        assert_that(
            calling(lambda: module.validate_options()),
            is_not(raises(ValidationError))
        )

        module.options = {'title': 'foobar'}

        assert_that(
            calling(lambda: module.validate_options()),
            raises(ValidationError)
        )
def test_object():
    """
    Can create a class for an object schema.
    """
    registry = Registry()
    registry.load(schema_for("data/name.json"))

    Name = registry.create_class(NAME_ID)

    name = Name(
        first="George",
    )

    assert_that(calling(name.validate), raises(ValidationError))

    name.last = "Washington"

    name.validate()

    assert_that(
        name,
        has_properties(
            first=equal_to("George"),
            last=equal_to("Washington"),
        )
    )
    assert_that(name, is_(equal_to(NAME)))
    assert_that(name, is_(equal_to(Name(**NAME))))
    assert_that(Name.loads(name.dumps()), is_(equal_to(name)))

    del name.first

    assert_that(calling(name.validate), raises(ValidationError))
Example #4
0
def GetCompletions_ServerIsNotRunning_test( app ):
  StopCompleterServer( app, filetype = 'typescript' )

  filepath = PathToTestFile( 'test.ts' )
  contents = ReadFile( filepath )

  # Check that sending a request to TSServer (the response is ignored) raises
  # the proper exception.
  event_data = BuildRequest( filepath = filepath,
                             filetype = 'typescript',
                             contents = contents,
                             event_name = 'BufferVisit' )

  assert_that(
    calling( app.post_json ).with_args( '/event_notification', event_data ),
    raises( AppError, 'TSServer is not running.' ) )

  # Check that sending a command to TSServer (the response is processed) raises
  # the proper exception.
  completion_data = BuildRequest( filepath = filepath,
                                  filetype = 'typescript',
                                  contents = contents,
                                  force_semantic = True,
                                  line_num = 17,
                                  column_num = 6 )

  assert_that(
    calling( app.post_json ).with_args( '/completions', completion_data ),
    raises( AppError, 'TSServer is not running.' ) )
Example #5
0
 def test_get_stasis_start_app_invalid(self):
     assert_that(calling(StartCallEvent).with_args(channel=Mock(),
                                                   event={},
                                                   state_persistor=Mock()),
                 raises(InvalidStartCallEvent))
     assert_that(calling(StartCallEvent).with_args(channel=Mock(),
                                                   event={'args': []},
                                                   state_persistor=Mock()),
                 raises(InvalidStartCallEvent))
Example #6
0
def Subcommands_GoToInclude_Fail_test():
  test = { 'request': [ 4, 1 ], 'response': '' }
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoToInclude', test ),
    raises( AppError, 'Include file not found.' ) )
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoTo', test ),
    raises( AppError, 'Include file not found.' ) )
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoToImprecise', test ),
    raises( AppError, 'Include file not found.' ) )

  test = { 'request': [ 7, 1 ], 'response': '' }
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoToInclude', test ),
    raises( AppError, 'Not an include/import line.' ) )
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoTo', test ),
    raises( AppError, r'Can\\\'t jump to definition or declaration.' ) )
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoToImprecise', test ),
    raises( AppError, r'Can\\\'t jump to definition or declaration.' ) )

  # Unclosed #include statement.
  test = { 'request': [ 10, 13 ], 'response': '' }
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoToInclude', test ),
    raises( AppError, 'Not an include/import line.' ) )
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoTo', test ),
    raises( AppError, r'Can\\\'t jump to definition or declaration.' ) )
  assert_that(
    calling( RunGoToIncludeTest ).with_args( 'GoToImprecise', test ),
    raises( AppError, r'Can\\\'t jump to definition or declaration.' ) )
Example #7
0
 def test_no_intersection(self):
     """Testing of method Line2d.intersection."""
     line_a = Line2d(Point2d(0.0, 2.0), Vector2d(4.0, 0.0))
     line_b = Line2d(Point2d(0.0, 1.0), Vector2d(4.0, 0.0))
     line_c = Line2d(Point2d(2.0, 0.0), Vector2d(0.0, 1.0))
     # raised because lines are parallel
     assert_that(
         calling(line_a.intersection).with_args(line_b),
         raises(NoLineIntersection))
     # factor of line_c is not between 0 and 1
     assert_that(
         calling(line_a.intersection).with_args(line_c),
         raises(NoLineIntersection))
def Subcommands_GoToInclude_Fail_test():
  tests = [ # { 'request': [ 4, 1 ], 'response': '' },
            { 'request': [ 7, 1 ], 'response': '' },
            { 'request': [ 10, 13 ], 'response': '' } ]
  for test in tests:
    assert_that(
      calling( RunGoToIncludeTest ).with_args( 'GoToInclude', test ),
      raises( AppError, 'Cannot jump to location.' ) )
    assert_that(
      calling( RunGoToIncludeTest ).with_args( 'GoTo', test ),
      raises( AppError, 'Cannot jump to location.' ) )
    assert_that(
      calling( RunGoToIncludeTest ).with_args( 'GoToImprecise', test ),
      raises( AppError, 'Cannot jump to location.' ) )
def CheckFilename_test():
  assert_that(
    calling( vimsupport.CheckFilename ).with_args( None ),
    raises( RuntimeError, "'None' is not a valid filename" )
  )

  assert_that(
    calling( vimsupport.CheckFilename ).with_args( 'nonexistent_file' ),
    raises( RuntimeError,
            "filename 'nonexistent_file' cannot be opened. "
            "No such file or directory." )
  )

  assert_that( vimsupport.CheckFilename( __file__ ), none() )
def test_illegal_package_name():
    """
    Illegal package names are detected.
    """
    registry = Registry()
    loader = ModuleLoader(registry.factory, basename="test")

    assert_that(
        calling(loader.package_name_for).with_args("foo/1.0/bar"),
        raises(ValueError),
    )
    assert_that(
        calling(loader.package_name_for).with_args("_foo/bar"),
        raises(ValueError),
    )
Example #11
0
def CompilationDatabase_InvalidDatabase_test():
  with TemporaryClangTestDir() as tmp_dir:
    with TemporaryClangProject( tmp_dir, 'this is junk' ):
      assert_that(
        calling( flags.Flags().FlagsForFile ).with_args(
          os.path.join( tmp_dir, 'test.cc' ) ),
        raises( NoExtraConfDetected ) )
Example #12
0
def WaitUntilProcessIsTerminated_TimedOut_test( *args ):
  assert_that(
    calling( utils.WaitUntilProcessIsTerminated ).with_args( None,
                                                             timeout = 0 ),
    raises( RuntimeError,
            'Waited process to terminate for 0 seconds, aborting.' )
  )
    def test_api_raises_exception_with_if_data_status_is_false(self, request_mock):
        data = a_response_data(status=False, error_code=1, error_message="invalid method specified: client.miss",
                               data=None)
        ubersmith_api = api.init(self.url, self.username, self.password)

        self.expect_a_ubersmith_call(request_mock, method="client.miss", data=data)
        assert_that(calling(ubersmith_api.client.miss), raises(UbersmithException))
Example #14
0
    def testTraverseFailsIntoSiblingSiteExceptHostPolicyFolders(self):
        new_comps = BaseComponents(BASE, 'sub_site', ())
        new_site = MockSite(new_comps)
        new_site.__name__ = new_comps.__name__

        with currentSite(None):
            threadSiteSubscriber(new_site, None)
            # If we walk into a site...

            # ...and then try to walk into a sibling site with no apparent relationship...
            new_comps2 = BaseComponents(BASE, 'sub_site', (new_comps,))
            new_site2 = MockSite(new_comps2)
            new_site2.__name__ = new_comps2.__name__

            # ... we fail...
            assert_that(calling(threadSiteSubscriber).with_args(new_site2, None),
                        raises(LocationError))

            # ...unless they are both HostPolicyFolders...
            interface.alsoProvides(new_site, IHostPolicyFolder)
            interface.alsoProvides(new_site2, IHostPolicyFolder)
            repr(new_site) # coverage
            str(new_site)
            threadSiteSubscriber(new_site2, None)

            # ... which does not change the site
            assert_that(getSite(), is_(same_instance(new_site)))
Example #15
0
def ComputeCandidatesInner_GoCodePanic_test( completer, *args ):
  assert_that(
    calling( completer.ComputeCandidatesInner ).with_args(
      BuildRequest( 1, 1 ) ),
    raises( RuntimeError,
            'Gocode panicked trying to find completions, '
            'you likely have a syntax error.' ) )
Example #16
0
    def test_when_template_has_two_func_keys_with_same_destination_then_raises_error(self):
        destination = CustomDestination(exten='1234')
        template = FuncKeyTemplate(keys={1: FuncKey(destination=destination),
                                         2: FuncKey(destination=destination)})

        assert_that(calling(self.validator.validate).with_args(template),
                    raises(ResourceError))
Example #17
0
    def test_given_transfer_does_not_exist_when_validating_then_raises_error(self):
        self.dao.find_all_transfer_extensions.return_value = []

        destination = TransferDestination(transfer='blind')

        assert_that(calling(self.validator.validate).with_args(destination),
                    raises(InputError))
 def test_download_datapackage_existing_dest_dir(
         self, config, api_client, dataset_key):
     os.mkdir(config.cache_dir)
     assert_that(
         calling(api_client.download_datapackage).with_args(
             dataset_key, config.cache_dir),
         raises(ValueError))
Example #19
0
    def test_given_agent_action_does_not_exist_when_validating_then_raises_error(self):
        self.dao.find_all_agent_action_extensions.return_value = []

        destination = AgentDestination(action='login')

        assert_that(calling(self.validator.validate).with_args(destination),
                    raises(InputError))
Example #20
0
    def test_given_service_does_not_exist_when_validating_then_raises_error(self):
        self.dao.find_all_service_extensions.return_value = []

        destination = ServiceDestination(service='enablevm')

        assert_that(calling(self.validator.validate).with_args(destination),
                    raises(InputError))
Example #21
0
    def test_given_forward_does_not_exist_when_validating_then_raises_error(self):
        self.dao.find_all_forward_extensions.return_value = []

        destination = ForwardDestination(forward='noanswer')

        assert_that(calling(self.validator.validate).with_args(destination),
                    raises(InputError))
Example #22
0
    def test_given_resource_does_not_exist_then_raises_error(self):
        model = Mock(field=sentinel.field)

        self.dao_exist.return_value = False

        assert_that(calling(self.validator.validate).with_args(model),
                    raises(InputError))
Example #23
0
    def test_given_user_has_a_voicemail_then_validation_passes(self):
        model = UserVoicemail(user_id=1, voicemail_id=2)
        self.dao.find_by_user_id.return_value = model

        assert_that(
            calling(self.validator.validate).with_args(model),
            raises(ResourceError))
Example #24
0
    def test_given_no_validator_for_destination_when_validating_then_raises_error(self):
        destination = Mock(type='spam')

        model = FuncKey(destination=destination)

        assert_that(calling(self.validator.validate).with_args(model),
                    raises(InputError))
Example #25
0
 def test_connect_event_originator_missing_event_args(self):
     assert_that(calling(ConnectCallEvent).with_args(channel=Mock(),
                                                     event={'application': 'myapp',
                                                            'args': ['red']},
                                                     ari=Mock(),
                                                     state_persistor=Mock()),
                 raises(InvalidConnectCallEvent))
Example #26
0
 def test_app_app_instance_unknown_channel(self):
     state_persistor = Mock()
     state_persistor.get.side_effect = KeyError
     assert_that(calling(CallEvent).with_args(channel=Mock(),
                                              event={},
                                              state_persistor=state_persistor),
                 raises(InvalidCallEvent))
    def test_(self):
        class IBaz(Interface):
            pass

        class IFoo(Interface):
            ob = Object(IBaz)

        @implementer(IBaz)
        class Baz(object):
            pass

        class CantConform(object):
            pass

        class Conforms(object):
            def __conform__(self, iface):
                return Baz()

        for fp in AdaptingFieldProperty, AdaptingFieldPropertyStoredThroughField:

            assert_that(calling(fp).with_args(None), raises(WrongType))

            @implementer(IFoo)
            class O(object):
                ob = fp(IFoo['ob'])

            obj = O()

            # First, can't set it
            with self.assertRaises(SchemaNotProvided):
                obj.ob = CantConform()

            # But this can be adapted
            obj.ob = Conforms()
            assert_that(obj.ob, is_(Baz))
def test_object_graph_partial_use():
    """
    Partial initialization succeeds partially and is recoverable.

    """
    registry = Registry()

    create_first = Mock()
    create_first.return_value = "first"
    create_second = Mock()
    create_second.side_effect = [Exception, "second"]
    create_third = Mock()
    create_third.side_effect = "third"

    registry.bind("first", create_first)
    registry.bind("second", create_second)
    registry.bind("third", create_third)

    graph = create_object_graph("test", registry=registry)
    # exception raised from initial call to create_second
    assert_that(calling(graph.use).with_args("first", "second", "third"), raises(Exception))
    # first and second were called, but not third
    assert_that(create_first.call_count, is_(equal_to(1)))
    assert_that(create_second.call_count, is_(equal_to(1)))
    assert_that(create_third.call_count, is_(equal_to(0)))

    # second call succeeds
    [first, second, third] = graph.use("first", "second", "third")
    # first was not called, second was called again, and third called for the first time
    assert_that(create_first.call_count, is_(equal_to(1)))
    assert_that(create_second.call_count, is_(equal_to(2)))
    assert_that(create_third.call_count, is_(equal_to(1)))
def test_build_document_set_handles_big_numbers():
    results = [0] * 3142
    special_fields = [0] * 3142

    assert_that(
        calling(build_document_set).with_args(results, '', {}, special_fields),
        is_not(raises(ValueError)))
Example #30
0
    def test_given_resource_does_not_exist_then_raises_error(self):
        model = Mock(field=sentinel.field)

        self.dao_get.side_effect = NotFoundError

        assert_that(calling(self.validator.validate).with_args(model),
                    raises(InputError))
Example #31
0
def Calculated_SetMethod_test():
    assert_that(
        calling(RequestWrap(PrepareJson()).__setitem__).with_args(
            'line_value', ''),
        raises(ValueError, 'Key "line_value" is read-only'))
Example #32
0
def AddNearestThirdPartyFoldersToSysPath_Failure_test():
    assert_that(
        calling(AddNearestThirdPartyFoldersToSysPath).with_args(
            os.path.expanduser('~')),
        raises(RuntimeError, '.*third_party folder.*'))
Example #33
0
def GetCompletions_RejectInvalid_test():
    if utils.OnWindows():
        filepath = 'C:\\test.test'
    else:
        filepath = '/test.test'

    contents = 'line1.\nline2.\nline3.'

    request_data = RequestWrap(
        BuildRequest(filetype='ycmtest',
                     filepath=filepath,
                     contents=contents,
                     line_num=1,
                     column_num=7))

    text_edit = {
        'newText': 'blah',
        'range': {
            'start': {
                'line': 0,
                'character': 6
            },
            'end': {
                'line': 0,
                'character': 6
            },
        }
    }

    assert_that(
        lsc._GetCompletionItemStartCodepointOrReject(text_edit, request_data),
        equal_to(7))

    text_edit = {
        'newText': 'blah',
        'range': {
            'start': {
                'line': 0,
                'character': 6
            },
            'end': {
                'line': 1,
                'character': 6
            },
        }
    }

    assert_that(
        calling(lsc._GetCompletionItemStartCodepointOrReject).with_args(
            text_edit, request_data),
        raises(lsc.IncompatibleCompletionException))

    text_edit = {
        'newText': 'blah',
        'range': {
            'start': {
                'line': 0,
                'character': 20
            },
            'end': {
                'line': 0,
                'character': 20
            },
        }
    }

    assert_that(
        lsc._GetCompletionItemStartCodepointOrReject(text_edit, request_data),
        equal_to(7))

    text_edit = {
        'newText': 'blah',
        'range': {
            'start': {
                'line': 0,
                'character': 6
            },
            'end': {
                'line': 0,
                'character': 5
            },
        }
    }

    assert_that(
        lsc._GetCompletionItemStartCodepointOrReject(text_edit, request_data),
        equal_to(7))
Example #34
0
def ComputeCandidatesInner_NoResultsFailure_test( completer, *args ):
  assert_that(
    calling( completer.ComputeCandidatesInner ).with_args(
      BuildRequest( 1, 1 ) ),
    raises( RuntimeError, 'No completions found.' ) )
Example #35
0
 def test_missing_token(self, config_file_path):
     assert_that(path.isfile(config_file_path), is_(True))
     config = FileConfig(profile='missingprofile',
                         config_file_path=config_file_path)
     assert_that(calling(lambda: config.auth_token), raises(RuntimeError))
    def test_given_no_tenant_when_from_token_then_return_tenant(self):
        token = Mock(tenant_uuid=None)

        assert_that(calling(Tenant.from_token).with_args(token), raises(InvalidTenant))
Example #37
0
def test_series_fails_on_zero_series():
    assert_that(calling(consecutive_series).with_args('49142', 0), raises(ValueError))
Example #38
0
def test_series_fails_on_empty_digits():
    assert_that(calling(consecutive_series).with_args('', 3), raises(ValueError))
Example #39
0
    def test_ps_cmd_phpfpm_off(self):
        self.stop_fpm()

        assert_that(
            calling(subp.call).with_args(PS_CMD),
            raises(AmplifySubprocessError))
Example #40
0
def ComputeOffset_OutOfBoundsOffset_test():
  assert_that(
    calling( _ComputeOffset ).with_args( 'test', 2, 1 ),
    raises( RuntimeError, 'Go completer could not compute byte offset '
                          'corresponding to line 2 and column 1.' ) )
    def test_given_no_token_when_autodetect_then_raise(self, request):
        tokens = Mock()
        tokens.from_headers.side_effect = InvalidToken
        request.headers = {}

        assert_that(calling(Tenant.autodetect).with_args(tokens), raises(InvalidToken))
Example #42
0
def ComputeCandidatesInner_ParseFailure_test( completer, *args ):
  assert_that(
    calling( completer.ComputeCandidatesInner ).with_args(
      BuildRequest( 1, 1 ) ),
    raises( RuntimeError, 'Gocode returned invalid JSON response.' ) )
    def test_given_no_header_when_get_then_raise(self, extract):
        extract.return_value = ''
        auth = Mock()
        tokens = Tokens(auth)

        assert_that(calling(tokens.from_headers), raises(InvalidToken))
Example #44
0
def EnsureRequestValid_MissingFileDataContents_test():
    data = BasicData()
    del data['file_data']['/foo']['contents']
    assert_that(
        calling(EnsureRequestValid).with_args(data),
        raises(ServerError, ".*contents.*"))
Example #45
0
def EnsureRequestValid_MissingColumnNum_test():
    data = BasicData()
    del data['column_num']
    assert_that(
        calling(EnsureRequestValid).with_args(data),
        raises(ServerError, ".*column_num.*"))
Example #46
0
def EnsureRequestValid_EmptyFileDataFiletypes_test():
    data = BasicData()
    del data['file_data']['/foo']['filetypes'][0]
    assert_that(
        calling(EnsureRequestValid).with_args(data),
        raises(ServerError, ".*filetypes.*"))
Example #47
0
def CompilationDatabase_NoDatabase_test():
    with TemporaryTestDir() as tmp_dir:
        assert_that(
            calling(flags.Flags().FlagsForFile).with_args(
                os.path.join(tmp_dir, 'test.cc')), raises(NoExtraConfDetected))
Example #48
0
def EnsureRequestValid_MissingFileData_test():
    data = BasicData()
    del data['file_data']
    assert_that(
        calling(EnsureRequestValid).with_args(data),
        raises(ServerError, ".*file_data.*"))
    def test_given_unknown_token_when_get_then_raise(self):
        auth = Mock()
        auth.token.get.side_effect = requests.HTTPError
        tokens = Tokens(auth)

        assert_that(calling(tokens.get).with_args('token'), raises(InvalidToken))
Example #50
0
def EnsureRequestValid_MissingEntryForFileInFileData_test():
    data = BasicData()
    data['filepath'] = '/bar'
    assert_that(
        calling(EnsureRequestValid).with_args(data),
        raises(ServerError, ".*/bar.*"))
Example #51
0
def JoinLinesAsUnicode_BadInput_test():
    assert_that(
        calling(utils.JoinLinesAsUnicode).with_args([42]),
        raises(ValueError, 'lines must contain either strings or bytes'))
Example #52
0
def WaitUntilProcessIsTerminated_TimedOut_test(*args):
    assert_that(
        calling(utils.WaitUntilProcessIsTerminated).with_args(None, timeout=0),
        raises(RuntimeError,
               'Waited process to terminate for 0 seconds, aborting.'))
Example #53
0
 def test_missing_file_unsuitable_legacy_file(self, config_file_path):
     assert_that(path.isfile(config_file_path), is_(False))
     config = FileConfig(config_file_path=config_file_path)
     assert_that(calling(lambda: config.auth_token), raises(RuntimeError))
Example #54
0
def AddNearestThirdPartyFoldersToSysPath_ErrorIfNoStandardLibrary_test(*args):
    assert_that(
        calling(AddNearestThirdPartyFoldersToSysPath).with_args(__file__),
        raises(RuntimeError,
               'Could not find standard library path in Python path.'))
Example #55
0
 def test_given_error_when_list_cdr_as_csv_then_return_error_in_csv(self):
     assert_that(
         calling(self.call_logd.cdr.list_csv).with_args(from_='wrong'),
         raises(CallLogdError).matching(
             has_properties(status_code=400, details=has_key('from'))),
     )
Example #56
0
 def test_tables_broken_schema(self, simpsons_broken_dataset):
     assert_that(
         calling(simpsons_broken_dataset.tables.get).with_args(
             'simpsons_episodes'), not_(raises(Exception)))
     assert_that(simpsons_broken_dataset.tables.get('simpsons_episodes'),
                 not_none())
Example #57
0
def JavaCompleter_GetType_test(app):
    completer = handlers._server_state.GetFiletypeCompleter(['java'])

    # The LSP defines the hover response as either:
    # - a string
    # - a list of strings
    # - an object with keys language, value
    # - a list of objects with keys language, value
    # = an object with keys kind, value

    with patch.object(completer, 'GetHoverResponse', return_value=''):
        assert_that(
            calling(completer.GetType).with_args(BuildRequest()),
            raises(RuntimeError, 'Unknown type'))

    with patch.object(completer, 'GetHoverResponse', return_value='string'):
        assert_that(
            calling(completer.GetType).with_args(BuildRequest()),
            raises(RuntimeError, 'Unknown type'))

    with patch.object(completer, 'GetHoverResponse', return_value='value'):
        assert_that(
            calling(completer.GetType).with_args(BuildRequest()),
            raises(RuntimeError, 'Unknown type'))

    with patch.object(completer, 'GetHoverResponse', return_value=[]):
        assert_that(
            calling(completer.GetType).with_args(BuildRequest()),
            raises(RuntimeError, 'Unknown type'))

    with patch.object(completer, 'GetHoverResponse', return_value=['a', 'b']):
        assert_that(
            calling(completer.GetType).with_args(BuildRequest()),
            raises(RuntimeError, 'Unknown type'))

    with patch.object(completer,
                      'GetHoverResponse',
                      return_value={
                          'language': 'java',
                          'value': 'test'
                      }):
        assert_that(completer.GetType(BuildRequest()),
                    has_entries({'message': 'test'}))

    with patch.object(completer,
                      'GetHoverResponse',
                      return_value=[{
                          'language': 'java',
                          'value': 'test'
                      }]):
        assert_that(completer.GetType(BuildRequest()),
                    has_entries({'message': 'test'}))

    with patch.object(completer,
                      'GetHoverResponse',
                      return_value=[{
                          'language': 'java',
                          'value': 'test'
                      }, {
                          'language': 'java',
                          'value': 'not test'
                      }]):
        assert_that(completer.GetType(BuildRequest()),
                    has_entries({'message': 'test'}))

    with patch.object(completer,
                      'GetHoverResponse',
                      return_value=[{
                          'language': 'java',
                          'value': 'test'
                      }, 'line 1', 'line 2']):
        assert_that(completer.GetType(BuildRequest()),
                    has_entries({'message': 'test'}))

    with patch.object(completer,
                      'GetHoverResponse',
                      return_value={
                          'kind': 'plaintext',
                          'value': 'test'
                      }):
        assert_that(
            calling(completer.GetType).with_args(BuildRequest()),
            raises(RuntimeError, 'Unknown type'))
 def test_delete_pool_lun_value_error(self):
     assert_that(calling(self.client.delete_pool_lun),
                 raises(ValueError, 'lun_id, lun_name'))
Example #59
0
def test_series_fails_series_higher_than_digit_length():
	assert_that(calling(consecutive_series).with_args('4', 2), raises(ValueError))
Example #60
0
    def test_receive_error(self):
        self.driver.read.return_value = [0x00, 0x1E, 0x00]

        assert_that(
            calling(self.serial.receive),
            raises(UsbIssError, "NACK received - transmit buffer overflow"))