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 ) )
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 #3
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)
        )
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_enable_dedup(self):
        def method_call():
            l1 = VNXLun(name='l1', cli=t_cli())
            l1.enable_dedup()

        def set_property():
            l1 = VNXLun(name='l1', cli=t_cli())
            l1.is_dedup = True

        assert_that(method_call, raises(VNXDedupError, 'it is migrating'))
        assert_that(set_property, raises(VNXDedupError, 'it is migrating'))
Example #8
0
    def test_disable_dedup(self):
        def method_call():
            l1 = VNXLun(name='l1', cli=t_cli())
            l1.disable_dedup()

        def set_property():
            l1 = VNXLun(name='l1', cli=t_cli())
            l1.is_dedup = False

        assert_that(method_call, raises(VNXDedupError, 'disabled or'))
        assert_that(set_property, raises(VNXDedupError, 'disabled or'))
Example #9
0
    def test_enable_compression(self):
        def method():
            l1 = VNXLun(lun_id=19, cli=t_cli())
            l1.enable_compression(VNXCompressionRate.HIGH)

        def prop():
            l1 = VNXLun(lun_id=19, cli=t_cli())
            l1.is_compressed = True

        assert_that(method, raises(VNXCompressionError, 'already turned on'))
        assert_that(prop, raises(VNXCompressionError, 'not installed'))
Example #10
0
    def test_disable_compression(self):
        def method():
            l1 = VNXLun(lun_id=19, cli=t_cli())
            l1.disable_compression()

        def prop():
            l1 = VNXLun(lun_id=19, cli=t_cli())
            l1.is_compressed = False

        assert_that(method, raises(VNXCompressionError, 'not turned on'))
        assert_that(prop, raises(VNXCompressionError, 'not turned on'))
Example #11
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.' ) )
Example #13
0
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 #15
0
    def test_create_password_criteria(self):
        def f():
            UnityCifsServer.create(t_rest(), 'nas_2', name='c_server1',
                                   workgroup='CEDRIC',
                                   local_password='******')

        assert_that(f, raises(UnityException, 'not meet the password policy'))
Example #16
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 #17
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 #18
0
    def test_create_name_existed(self):
        def f():
            UnityCifsServer.create(t_rest(), 'nas_5', name='NAS1130',
                                   workgroup='CEDRIC',
                                   local_password='******')

        assert_that(f, raises(UnityNetBiosNameExistedError, 'already exists'))
Example #19
0
    def test_raise_if_err_nas_response_input(self):
        def f():
            resp = NasXmlResponse(MockXmlPost.read_file('fs_not_found.xml'))
            raise_if_err(resp, VNXException,
                         expected_error=VNXError.FS_NOT_FOUND)

        assert_that(f, raises(VNXException, 'not found'))
 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 #21
0
    def test_delete_mirror_has_secondary(self):
        def f():
            mv = VNXMirrorView.get(t_cli(), 'mv7')
            mv.delete()

        assert_that(f, raises(VNXDeleteMirrorWithSecondaryError,
                              'at least one secondary'))
    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 #23
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 #24
0
    def test_remove_snap(self):
        def f():
            snap = VNXSnap(cli=t_cli(), name='s3')
            snap.remove()

        assert_that(f, raises(VNXRemoveSnapError,
                              'Cannot destroy the snapshot'))
Example #25
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 #26
0
    def test_mirror_view_feature_not_installed(self):
        def f():
            mv = VNXMirrorView.get(t_cli(), 'mv9')
            mv.delete()

        assert_that(f, raises(VNXMirrorFeatureNotAvailableError,
                              'not installed'))
Example #27
0
    def test_promote_non_local_image(self):
        def f():
            mv = VNXMirrorView.get(t_cli(), 'mv0')
            mv.promote_image()

        assert_that(f, raises(VNXMirrorPromoteNonLocalImageError,
                              'not local'))
Example #28
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 #29
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))
Example #30
0
    def test_remove_image_no_secondary_image(self):
        def f():
            mv = VNXMirrorView.get(t_cli(), 'mv1')
            mv.remove_image()

        assert_that(f,
                    raises(VNXMirrorImageNotFoundError, 'no secondary'))
Example #31
0
    def test_cg_not_found(self):
        def f():
            output = "Cannot find the consistency group."
            raise_if_err(output)

        assert_that(f, raises(exception.VNXConsistencyGroupNotFoundError))
Example #32
0
    def test_snap_not_exists(self):
        def f():
            output = "The specified snapshot does not exist."
            raise_if_err(output)

        assert_that(f, raises(exception.VNXSnapNotExistsError))
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 test_missing_token(self, config_file_path):
     assert_that(path.isfile(config_file_path), is_(True))
     config = Config(profile='missingprofile',
                     config_file_path=config_file_path)
     assert_that(calling(lambda: config.auth_token), raises(RuntimeError))
Example #35
0
 def test_should_raise_api_method_version_err(self):
     service = ServiceBase(api_version=9.0)
     assert_that(
         calling(service._check_method_version).with_args("aMethod", 10.0),
         raises(ApiMethodVersionError)
     )
Example #36
0
    def test_that_loading_without_a_proper_config_raises(self):
        plugin = Plugin()

        assert_that(calling(plugin.load).with_args({}), raises(ValueError))
        assert_that(calling(plugin.load).with_args({'config': {}}), raises(ValueError))
Example #37
0
 def test_delete_attached_snap(self):
     snap = UnitySnap(_id='38654705845', cli=t_rest())
     assert_that(lambda: snap.delete(),
                 raises(UnityDeleteAttachedSnapError))
Example #38
0
def test_rendering_invalid_template():
    fixture = """{{ a"""

    assert_that(
        calling(render).with_args(fixture), raises(TemplateSyntaxError))
Example #39
0
def test_rendering_invalid_expression_raises():
    context = Context()
    fixture = BooleanExpression("""{{ False }}""")

    assert_that(
        calling(fixture.evaluate).with_args(context), raises(RuntimeError))
Example #40
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_execute_cmd_ip_error(self):
        def f():
            hb = self.get_test_hb()
            hb.execute_cmd('abc', ['naviseccli', '-h', 'abc', 'getagent'])

        assert_that(f, raises(VNXCredentialError, 'not connect to'))
Example #42
0
def AddNearestThirdPartyFoldersToSysPath_Failure_test():
    assert_that(
        calling(AddNearestThirdPartyFoldersToSysPath).with_args(
            os.path.expanduser('~')),
        raises(RuntimeError, '.*third_party folder.*'))
Example #43
0
 def test_delete_not_exist_snap(self):
     snap = UnitySnap(_id='38654705844', cli=t_rest())
     assert_that(lambda: snap.delete(), raises(UnityResourceNotFoundError))
Example #44
0
    def test_create_nfs_share_type_error(self):
        def f():
            snap = UnitySnap(cli=t_rest(), _id='171798691852')
            snap.create_nfs_share('sns1')

        assert_that(f, raises(UnityShareOnCkptSnapError, 'is a checkpoint'))
Example #45
0
 def test_delete_host_and_ip_port(self):
     host = UnityHost(cli=t_rest(), _id='Host_1')
     ip_port = host.host_ip_ports[0]
     resp = host.delete()
     assert_that(resp.is_ok(), equal_to(True))
     assert_that(ip_port.delete, raises(UnityResourceNotFoundError))
Example #46
0
def ComputeCandidatesInner_NoResultsFailure_test(completer, *args):
    assert_that(
        calling(completer.ComputeCandidatesInner).with_args(BuildRequest(1,
                                                                         1)),
        raises(RuntimeError, 'No completions found.'))
    def test_create_existed(self):
        def f():
            VNXFsSnap.create(t_nas(), 'Tan_Manual_CheckPoint', 228, 61)

        assert_that(f, raises(VNXFsSnapNameInUseError, 'already in use'))
Example #48
0
    def test_create_ip_in_use(self):
        def f():
            UnityHostIpPort.create(t_rest(), 'Host_1', '1.1.1.1')

        assert_that(f, raises(UnityHostIpInUseError, 'already exists'))
Example #49
0
def test_unsupported_source_startup_error():
    mock_options = MagicMock(koji=True, source="build_nvr.src.foo")
    assert_that(
        calling(BaseProcessor).with_args(mock_options), raises(StartupError))
Example #50
0
    def test_given_position_over_maximum_then_raises_error(self):
        destination = FuncKeyDestParkPosition(position=800)

        assert_that(
            calling(self.validator.validate).with_args(destination),
            raises(InputError))
Example #51
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 #52
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.'))
Example #53
0
def test_append_file_names_handles_folder_not_found(_mock_print):
    file_names = []
    assert_that(calling(append_file_names).with_args(file_names, "test/folder_not_exists"),
                is_not(raises(FileNotFoundError)),
                "Errors should be handled when the folder is not found")
Example #54
0
def GetClangResourceDir_NotFound_test(*args):
    assert_that(calling(utils.GetClangResourceDir),
                raises(RuntimeError, 'Cannot find Clang resource directory'))
Example #55
0
def test_rendering_invalid_template_variable():
    fixture = """{{ nofunc(1) }}"""

    assert_that(calling(render).with_args(fixture), raises(UndefinedError))
Example #56
0
def JoinLinesAsUnicode_BadInput_test():
    assert_that(
        calling(utils.JoinLinesAsUnicode).with_args([42]),
        raises(ValueError, 'lines must contain either strings or bytes'))
Example #57
0
def CompilationDatabase_NoDatabase_test():
    with TemporaryClangTestDir() as tmp_dir:
        assert_that(
            calling(flags.Flags().FlagsForFile).with_args(
                os.path.join(tmp_dir, 'test.cc')), raises(NoExtraConfDetected))
Example #58
0
 def test_should_not_raise_api_parameter_version_err_with_no_since(self):
     service = ServiceBase(api_version=9.0)
     assert_that(
         calling(service._check_method_version).with_args("aMethod", None),
         not_(raises(ApiParameterVersionError))
     )
Example #59
0
    def test_get_rx_count_error(self):
        self.driver.read.return_value = [0x00, 0x1E, 0x00]

        assert_that(calling(self.serial.get_rx_count),
                    raises(UsbIssError,
                           "NACK received - transmit buffer overflow"))
Example #60
0
    def test_when_validating_private_template_then_raises_error(self):
        template = FuncKeyTemplate(private=True)

        assert_that(
            calling(self.validator.validate).with_args(template),
            raises(ResourceError))