def assert_that_volume_entity_is_created(self, tenant_id):
     entities = self.almanachHelper.get_entities(tenant_id, "2016-01-01 00:00:00.000")
     assert_that(len(entities), equal_to(2))
     assert_that(entities[0], is_not(has_entry("end", None)))
     assert_that(entities[0], has_entry("size", 10))
     assert_that(entities[1], has_entry("end", None))
     assert_that(entities[1], has_entry("size", 100))
Example #2
0
def GetCompletions_ClangCompleter_UnknownExtraConfException_test():
  app = TestApp( handlers.app )
  filepath = PathToTestFile( 'basic.cpp' )
  completion_data = BuildRequest( filepath = filepath,
                                  filetype = 'cpp',
                                  contents = open( filepath ).read(),
                                  line_num = 11,
                                  column_num = 7,
                                  force_semantic = True )

  response = app.post_json( '/completions',
                            completion_data,
                            expect_errors = True )

  eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR )
  assert_that( response.json,
               has_entry( 'exception',
                          has_entry( 'TYPE', UnknownExtraConf.__name__ ) ) )

  app.post_json( '/ignore_extra_conf_file',
                 { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } )

  response = app.post_json( '/completions',
                            completion_data,
                            expect_errors = True )

  eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR )
  assert_that( response.json,
               has_entry( 'exception',
                          has_entry( 'TYPE', NoExtraConfDetected.__name__ ) ) )
Example #3
0
    def test_it_should_force_reply(self):
        self.register('sendMessage')

        self.telegram.send_message(CHAT_ID, TEXT, force_reply=True)

        assert_that(self.sent_json,
            has_entry('reply_markup', has_entry('force_reply', True)))
Example #4
0
def step_with(name, start, stop, status):
    return has_properties(name=name,
                          title=name,
                          attrib=all_of(
                                        has_entry('start', has_float(greater_than_or_equal_to(start))),
                                        has_entry('stop', has_float(less_than_or_equal_to(stop))),
                                        has_entry('status', status)))
Example #5
0
    def test_dashboard_with_section_slug_returns_module_and_children(self):
        dashboard = DashboardFactory(slug='my-first-slug')
        dashboard.owners.add(self.user)
        module_type = ModuleTypeFactory()
        parent = ModuleFactory(
            type=module_type,
            slug='section-we-want',
            order=1,
            dashboard=dashboard
        )
        ModuleFactory(
            type=module_type,
            slug='module-we-want',
            order=2,
            dashboard=dashboard,
            parent=parent)

        resp = self.client.get(
            '/public/dashboards', {'slug': 'my-first-slug/section-we-want'})
        data = json.loads(resp.content)

        assert_that(data['modules'],
                    contains(has_entry('slug', 'section-we-want')))
        assert_that(len(data['modules']), equal_to(1))
        assert_that(data['modules'][0]['modules'],
                    contains(has_entry('slug', 'module-we-want')))
        assert_that(data, has_entry('page-type', 'module'))
Example #6
0
    def test_list_transforms_for_dataset_and_type_with_no_group(self):
        data_set = DataSetFactory()
        set_transform = TransformFactory(
            input_group=data_set.data_group,
            input_type=data_set.data_type,
        )
        type_transform = TransformFactory(
            input_type=data_set.data_type,
        )

        resp = self.client.get(
            '/data-sets/{}/transform'.format(data_set.name),
            HTTP_AUTHORIZATION='Bearer development-oauth-access-token')

        assert_that(resp.status_code, is_(200))

        resp_json = json.loads(resp.content)

        assert_that(len(resp_json), is_(2))
        assert_that(
            resp_json,
            has_item(has_entry('id', str(set_transform.id))))
        assert_that(
            resp_json,
            has_item(has_entry('id', str(type_transform.id))))
    def test_readonly_override(self):
        class IA(Interface):

            field = Attribute("A field")

        schema = jsonschema.JsonSchemafier(IA, readonly_override=True).make_schema()
        assert_that(schema, has_entry('field', has_entry('readonly', True)))
Example #8
0
def GetCompletions_UnknownExtraConfException_test( app ):
  filepath = PathToTestFile( 'basic.cpp' )
  completion_data = BuildRequest( filepath = filepath,
                                  filetype = 'cpp',
                                  contents = ReadFile( filepath ),
                                  line_num = 11,
                                  column_num = 7,
                                  force_semantic = True )

  response = app.post_json( '/completions',
                            completion_data,
                            expect_errors = True )

  eq_( response.status_code, requests.codes.internal_server_error )
  assert_that( response.json,
               has_entry( 'exception',
                          has_entry( 'TYPE', UnknownExtraConf.__name__ ) ) )

  app.post_json(
    '/ignore_extra_conf_file',
    { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } )

  response = app.post_json( '/completions',
                            completion_data,
                            expect_errors = True )

  eq_( response.status_code, requests.codes.internal_server_error )
  assert_that( response.json,
               has_entry( 'exception',
                          has_entry( 'TYPE',
                                     NoExtraConfDetected.__name__ ) ) )
    def test_update_entity_change_flavor_of_closed(self):
        instance_create_query = "{url}/project/{project}/instance"
        project_id = "my_test_project_id"
        instance_id = str(uuid4())
        data = {'id': instance_id,
                'created_at': '2016-01-01T18:30:00Z',
                'name': 'integration_test_instance_FlavorA',
                'flavor': 'FlavorA',
                'os_type': 'Linux',
                'os_distro': 'Ubuntu',
                'os_version': '14.04'}

        self.almanachHelper.post(url=instance_create_query, data=data, project=project_id)
        instance_delete_query = "{url}/instance/{instance_id}"
        delete_data = {'date': '2016-01-01T18:50:00Z'}
        self.almanachHelper.delete(url=instance_delete_query, data=delete_data, instance_id=instance_id)

        response = self.almanachHelper.put(url="{url}/entity/instance/{instance_id}?start={start}&end={end}",
                                           start="2016-01-01 18:29:59.0",
                                           end="2016-01-01 18:50:00.0",
                                           data={"flavor": "FlavorB",
                                                 "end_date": "2016-01-02 18:50:00.0Z"},
                                           instance_id=instance_id,
                                           )
        assert_that(response.status_code, equal_to(200))
        assert_that(response.json(), has_entry("flavor", "FlavorB"))
        assert_that(response.json(), has_entry("end", "2016-01-02 18:50:00+00:00"))
Example #10
0
    def test_serialize_with_dataset_but_no_query_parameters(self):
        module = ModuleFactory(
            slug='a-module',
            type=self.module_type,
            data_set=self.data_set,
            order=1,
            dashboard=self.dashboard_a)

        serialization = module.serialize()

        assert_that(serialization['slug'], equal_to('a-module'))
        assert_that(
            serialization['type']['id'],
            equal_to(str(self.module_type.id)))
        assert_that(
            serialization['dashboard']['id'],
            equal_to(str(self.dashboard_a.id)))

        assert_that(serialization['query_parameters'], equal_to(None))
        assert_that(
            serialization,
            has_entry(
                'data_group', equal_to(self.data_set.data_group.name)))

        assert_that(
            serialization,
            has_entry(
                'data_type', equal_to(self.data_set.data_type.name)))
Example #11
0
def test_run_only(report_for, severities):
    """
    Checks that running for given severities runs only selected tests
    """
    report = report_for("""
    import pytest

    @pytest.allure.CRITICAL
    def test_a():
        pass

    @pytest.allure.MINOR
    def test_b():
        pass

    def test_c():
        pass
    """, extra_run_args=['--allure_severities', ','.join(severities)])

    a_status, b_status, c_status = [Status.PASSED if s in severities else Status.CANCELED for s in [Severity.CRITICAL, Severity.MINOR, Severity.NORMAL]]

    assert_that(report.xpath(".//test-case"), contains(
        all_of(has_property('name', 'test_a'), has_property('attrib', has_entry('status', a_status))),
        all_of(has_property('name', 'test_b'), has_property('attrib', has_entry('status', b_status))),
        all_of(has_property('name', 'test_c'), has_property('attrib', has_entry('status', c_status)))
    ))
Example #12
0
    def test_list_returns_all_if_omniscient_nd_collector_view_but_no_ownership(
            self):
        view = TestResourceViewCollector()

        request = HttpRequest()
        request.method = 'GET'
        request.META['HTTP_AUTHORIZATION'] = \
            'Bearer correct-token'

        settings.USE_DEVELOPMENT_USERS = False
        signon = govuk_signon_mock(
            permissions=['omniscient', 'collector-view'])
        with HTTMock(signon):
            response = view.get(request)

            try:
                json_response = json.loads(response.content)
            except ValueError:
                json_response = None

            assert_that(response.status_code, is_(200))
            assert_that(len(json_response), is_(2))
            assert_that(json_response, contains_inanyorder(
                has_entry("name", starts_with(
                    self.__class__.collector_type1.name)),
                has_entry("name", starts_with(
                    self.__class__.collector_type2.name))))
Example #13
0
    def test_application_info(self):

        app_info = {
            'text_key': u'a value',
            'byte_key': b'bytes',
            'int_key': 7,
            'list_key': [42,]
        }

        class IA(Interface):

            field = Attribute("A field")
            field.setTaggedValue(jsonschema.TAG_APPLICATION_INFO, app_info)

        schema = TranslateTestSchema(IA, context=u' TEST').make_schema()

        assert_that(schema, has_key("field"))
        field = schema['field']
        assert_that(field, has_key("application_info"))
        # The dict itself was copied
        assert_that(field['application_info'], is_not(same_instance(app_info)))
        # as were its contents
        assert_that(field['application_info'], has_entry('list_key', is_([42])))
        assert_that(field['application_info'],
                    has_entry('list_key', is_not(same_instance(app_info['list_key']))))

        # Text strings were translated
        assert_that(field['application_info'], has_entry('text_key', u'a value TEST'))

        # Byte strings were not (is that even legel in json?)
        assert_that(field['application_info'], has_entry('byte_key', b'bytes'))
Example #14
0
def Subcommands_StopServer_Timeout_test( app ):
  filepath = PathToTestFile( 'testy', 'GotoTestCase.cs' )
  contents = ReadFile( filepath )
  event_data = BuildRequest( filepath = filepath,
                             filetype = 'cs',
                             contents = contents,
                             event_name = 'FileReadyToParse' )

  app.post_json( '/event_notification', event_data )
  WaitUntilCompleterServerReady( app, 'cs' )

  app.post_json(
    '/run_completer_command',
    BuildRequest(
      filetype = 'cs',
      filepath = filepath,
      command_arguments = [ 'StopServer' ]
    )
  )

  request_data = BuildRequest( filetype = 'cs', filepath = filepath )
  assert_that( app.post_json( '/debug_info', request_data ).json,
               has_entry(
                 'completer',
                 has_entry( 'servers', contains(
                   has_entry( 'is_running', False )
                 ) )
               ) )
def EventNotification_FileReadyToParse_SyntaxKeywords_ClearCacheIfRestart_test(
    ycm, *args ):

  current_buffer = VimBuffer( name = 'current_buffer',
                              filetype = 'some_filetype' )

  with patch( 'ycm.client.event_notification.EventNotification.'
              'PostDataToHandlerAsync' ) as post_data_to_handler_async:
    with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
      ycm.OnFileReadyToParse()
      assert_that(
        # Positional arguments passed to PostDataToHandlerAsync.
        post_data_to_handler_async.call_args[ 0 ],
        contains(
          has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ),
          'event_notification'
        )
      )

      # Send again the syntax keywords after restarting the server.
      ycm.RestartServer()
      WaitUntilReady()
      ycm.OnFileReadyToParse()
      assert_that(
        # Positional arguments passed to PostDataToHandlerAsync.
        post_data_to_handler_async.call_args[ 0 ],
        contains(
          has_entry( 'syntax_keywords', has_items( 'foo', 'bar' ) ),
          'event_notification'
        )
      )
def ServerManagement_ServerDies_test( app ):
  StartJavaCompleterServerInDirectory(
    app,
    PathToTestFile( 'simple_eclipse_project' ) )

  request_data = BuildRequest( filetype = 'java' )
  debug_info = app.post_json( '/debug_info', request_data ).json
  print( 'Debug info: {0}'.format( debug_info ) )
  pid = debug_info[ 'completer' ][ 'servers' ][ 0 ][ 'pid' ]
  print( 'pid: {0}'.format( pid ) )
  process = psutil.Process( pid )
  process.terminate()

  for tries in range( 0, 10 ):
    request_data = BuildRequest( filetype = 'java' )
    debug_info = app.post_json( '/debug_info', request_data ).json
    if not debug_info[ 'completer' ][ 'servers' ][ 0 ][ 'is_running' ]:
      break

    time.sleep( 0.5 )

  assert_that( debug_info,
               has_entry(
                 'completer',
                 has_entry( 'servers', contains(
                   has_entry( 'is_running', False )
                 ) )
               ) )
Example #17
0
    def test_add_a_module_to_a_dashboard(self):
        existing_modules_count = len(Module.objects.all())
        resp = self.client.post(
            '/dashboard/{}/module'.format(self.dashboard.slug),
            data=json.dumps({
                'slug': 'a-module',
                'type_id': str(self.module_type.id),
                'title': 'Some module',
                'description': 'Some text about the module',
                'info': ['foo'],
                'options': {
                    'thing': 'a value',
                },
                'objects': "some object",
                'order': 1,
                'modules': [],
            }),
            HTTP_AUTHORIZATION='Bearer development-oauth-access-token',
            content_type='application/json')

        assert_that(resp.status_code, is_(equal_to(200)))
        assert_that(
            len(Module.objects.all()),
            greater_than(existing_modules_count))

        resp_json = json.loads(resp.content)

        assert_that(resp_json, has_key('id'))
        assert_that(resp_json, has_entry('slug', 'a-module'))
        assert_that(resp_json, has_entry('options', {'thing': 'a value'}))

        stored_module = Module.objects.get(id=resp_json['id'])
        assert_that(stored_module, is_not(None))
Example #18
0
    def test_basic_query_with_time_limits(self):
        self._save_all('foo_bar',
                       {'_timestamp': d_tz(2012, 12, 12)},
                       {'_timestamp': d_tz(2012, 12, 14)},
                       {'_timestamp': d_tz(2012, 12, 11)})

        # start at
        results = self.engine.execute_query('foo_bar', Query.create(
            start_at=d_tz(2012, 12, 12, 13)))

        assert_that(results,
                    contains(
                        has_entry('_timestamp', d_tz(2012, 12, 14))))

        # end at
        results = self.engine.execute_query('foo_bar', Query.create(
            end_at=d_tz(2012, 12, 11, 13)))

        assert_that(results,
                    contains(
                        has_entry('_timestamp', d_tz(2012, 12, 11))))

        # both
        results = self.engine.execute_query('foo_bar', Query.create(
            start_at=d_tz(2012, 12, 11, 12),
            end_at=d_tz(2012, 12, 12, 12)))

        assert_that(results,
                    contains(
                        has_entry('_timestamp', d_tz(2012, 12, 12))))
Example #19
0
  def UnknownExtraConfException_test( self ):
    filepath = self._PathToTestFile( 'basic.cpp' )
    completion_data = self._BuildRequest( filepath = filepath,
                                          filetype = 'cpp',
                                          contents = ReadFile( filepath ),
                                          line_num = 11,
                                          column_num = 7,
                                          force_semantic = True )

    response = self._app.post_json( '/completions',
                                    completion_data,
                                    expect_errors = True )

    eq_( response.status_code, http.client.INTERNAL_SERVER_ERROR )
    assert_that( response.json,
                 has_entry( 'exception',
                            has_entry( 'TYPE', UnknownExtraConf.__name__ ) ) )

    self._app.post_json(
      '/ignore_extra_conf_file',
      { 'filepath': self._PathToTestFile( '.ycm_extra_conf.py' ) } )

    response = self._app.post_json( '/completions',
                                    completion_data,
                                    expect_errors = True )

    eq_( response.status_code, http.client.INTERNAL_SERVER_ERROR )
    assert_that( response.json,
                 has_entry( 'exception',
                            has_entry( 'TYPE',
                                       NoExtraConfDetected.__name__ ) ) )
def GetCompletions_Basic_test( app ):
  filepath = PathToTestFile( 'basic.py' )
  completion_data = BuildRequest( filepath = filepath,
                                  filetype = 'python',
                                  contents = ReadFile( filepath ),
                                  line_num = 7,
                                  column_num = 3 )

  results = app.post_json( '/completions',
                           completion_data ).json[ 'completions' ]
  assert_that( results,
               has_items(
                 CompletionEntryMatcher( 'a',
                                         'self.a = 1',
                                         {
                                           'extra_data': has_entry(
                                             'location', has_entries( {
                                               'line_num': 3,
                                               'column_num': 10,
                                               'filepath': filepath
                                             } )
                                           )
                                         } ),
                 CompletionEntryMatcher( 'b',
                                         'self.b = 2',
                                         {
                                           'extra_data': has_entry(
                                             'location', has_entries( {
                                               'line_num': 4,
                                               'column_num': 10,
                                               'filepath': filepath
                                             } )
                                           )
                                         } )
               ) )

  completion_data = BuildRequest( filepath = filepath,
                                  filetype = 'python',
                                  contents = ReadFile( filepath ),
                                  line_num = 7,
                                  column_num = 4 )

  results = app.post_json( '/completions',
                           completion_data ).json[ 'completions' ]
  assert_that( results,
               all_of(
                 has_item(
                   CompletionEntryMatcher( 'a',
                                           'self.a = 1',
                                           {
                                             'extra_data': has_entry(
                                               'location', has_entries( {
                                                 'line_num': 3,
                                                 'column_num': 10,
                                                 'filepath': filepath
                                               } )
                                             )
                                           } ) ),
                 is_not( has_item( CompletionEntryMatcher( 'b' ) ) )
               ) )
Example #21
0
def GetDetailedDiagnostic_JediCompleter_DoesntWork_test():
    app = TestApp(handlers.app)
    diag_data = BuildRequest(contents="foo = 5", line_num=2, filetype="python")
    response = app.post_json("/detailed_diagnostic", diag_data, expect_errors=True)

    eq_(response.status_code, httplib.INTERNAL_SERVER_ERROR)
    assert_that(response.json, has_entry("exception", has_entry("TYPE", NoDiagnosticSupport.__name__)))
Example #22
0
    def test_ui_type(self):
        class IA(Interface):

            field = Attribute("A field")
            field.setTaggedValue(jsonschema.TAG_UI_TYPE, 'MyType')

        schema = jsonschema.JsonSchemafier(IA).make_schema()
        assert_that(schema, has_entry('field', has_entry('type', 'MyType')))
def then_i_see_an_ami_message_on_the_queue(step, event_name, queue):
    events = bus_helper.get_messages_from_bus(queue)

    matcher_dict = dict((event_line['header'], matches_regexp(event_line['value']))
                        for event_line in step.hashes)

    assert_that(events, has_item(all_of(has_entry('name', event_name),
                                        has_entry('data', has_entries(matcher_dict)))))
Example #24
0
def test_index_empty_directory():
    target = 'foo/'
    scanner = [(target, [], [])]

    index = dir2json.create_index(target, scanner)

    assert_that(index, has_entry('type', 'directory'))
    assert_that(index, has_entry('index', empty()))
Example #25
0
        def _assert_type(t, name='field',
                         **kwargs):
            schema = TranslateTestSchema(IA, context=' TEST').make_schema()
            assert_that(schema, has_entry(name, has_entry('type', t)))
            for nested_name, matcher in kwargs.items():
                assert_that(schema, has_entry(name, has_entry(nested_name, matcher)))

            return schema
Example #26
0
def has_parameter(name, value):
    return has_entry('parameters',
                     has_item(
                         all_of(
                             has_entry('name', equal_to(name)),
                             has_entry('value', equal_to(value))
                         )
                     ))
Example #27
0
def has_step(name, *matchers):
    return has_entry('steps',
                     has_item(
                         all_of(
                             has_entry('name', equal_to(name)),
                             *matchers
                         )
                     ))
Example #28
0
def has_link(url, link_type=None, name=None):
    return has_entry('links',
                     has_item(
                         all_of(
                             *[has_entry(key, value) for key, value in
                               zip(('url', 'type', 'name'), (url, link_type, name)) if value is not None]
                         )
                     ))
Example #29
0
def test_creates_default_chain_of_title_from_metadata():
    source_metadata = metadata(lyricist=["Joel Miller"], composer=["John Roney"], publisher=["Effendi Records"])
    track = make_track(metadata_from=source_metadata)

    assert_that(track.chain_of_title.contributors,
                all_of(has_author_composer("John Roney", has_entry("name", "John Roney")),
                       has_author_composer("Joel Miller", has_entry("name", "Joel Miller")),
                       has_publisher("Effendi Records", has_entry("name", "Effendi Records"))),
                "The chain of title")
 def test_period_queries_get_sorted_by__week_start_at(self):
     self.setup__timestamp_data()
     query = Query.create(period=WEEK)
     result = self.data_set.execute_query(query)
     assert_that(result, contains(
         has_entry('_start_at', d_tz(2012, 12, 31)),
         has_entry('_start_at', d_tz(2013, 1, 28)),
         has_entry('_start_at', d_tz(2013, 2, 25))
     ))
Example #31
0
def Diagnostics_Multiline_test(app):
    contents = """
struct Foo {
  Foo(int z) {}
};

int main() {
  Foo foo("goo");
}
"""

    filepath = PathToTestFile('foo.cc')
    request = {'contents': contents, 'filepath': filepath, 'filetype': 'cpp'}

    test = {'request': request, 'route': '/receive_messages'}
    RunAfterInitialized(app, test)
    diag_data = BuildRequest(line_num=7,
                             contents=contents,
                             filepath=filepath,
                             filetype='cpp')

    results = app.post_json('/detailed_diagnostic', diag_data).json
    assert_that(results, has_entry('message', contains_string("\n")))
Example #32
0
def DebugInfo_ServerIsNotRunning_NoSolution_test(app):
    request_data = BuildRequest(filetype='cs')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entries({
                'name':
                'C#',
                'servers':
                contains_exactly(
                    has_entries({
                        'name': 'OmniSharp',
                        'is_running': False,
                        'executable': instance_of(str),
                        'pid': None,
                        'address': None,
                        'port': None,
                        'logfiles': empty()
                    })),
                'items':
                empty()
            })))
Example #33
0
def DebugInfo_FlagsWhenGlobalExtraConfAndCompilationDatabaseLoaded_test( app ):
  with TemporaryTestDir() as tmp_dir:
    compile_commands = [
      {
        'directory': tmp_dir,
        'command': 'clang++ -I. -I/absolute/path -Wall',
        'file': os.path.join( tmp_dir, 'test.cc' ),
      },
    ]
    with TemporaryClangProject( tmp_dir, compile_commands ):
      request_data = BuildRequest(
        filepath = os.path.join( tmp_dir, 'test.cc' ),
        filetype = 'cpp' )

      assert_that(
        app.post_json( '/debug_info', request_data ).json,
        has_entry( 'completer', has_entries( {
          'name': 'C-family',
          'servers': empty(),
          'items': contains(
            has_entries( {
              'key': 'compilation database path',
              'value': instance_of( str )
            } ),
            has_entries( {
              'key': 'flags',
              'value': matches_regexp(
                "\\[u?'clang\\+\\+', u?'-x', u?'c\\+\\+', .*, u?'-Wall', .*\\]"
              )
            } ),
            has_entries( {
              'key': 'translation unit',
              'value': os.path.join( tmp_dir, 'test.cc' ),
            } )
          )
        } ) )
      )
Example #34
0
    def test__shouldReturnListOfTransitionMeta(self):
        initial_state = State.objects.create(label="state-1")
        state_2 = State.objects.create(label="state-2")
        state_3 = State.objects.create(label="state-3")

        content_type = ContentType.objects.first()
        workflow = Workflow.objects.create(initial_state=initial_state,
                                           content_type=content_type,
                                           field_name="test-field")
        transition_meta_1 = TransitionMeta.objects.create(
            workflow=workflow,
            source_state=initial_state,
            destination_state=state_2)
        transition_meta_2 = TransitionMeta.objects.create(
            workflow=workflow,
            source_state=initial_state,
            destination_state=state_3)

        response = self.client.get('/workflow/transition-meta/list/%d/' %
                                   workflow.id)
        assert_that(response.status_code, equal_to(HTTP_200_OK))
        assert_that(response.data, has_length(2))

        assert_that(
            response.data,
            has_item(
                all_of(
                    has_entry("id", equal_to(transition_meta_1.id)),
                    has_entry("source_state",
                              equal_to(transition_meta_1.source_state.id)),
                    has_entry("destination_state",
                              equal_to(
                                  transition_meta_1.destination_state.id)))))

        assert_that(
            response.data,
            has_item(
                all_of(
                    has_entry("id", equal_to(transition_meta_2.id)),
                    has_entry("source_state",
                              equal_to(transition_meta_2.source_state.id)),
                    has_entry("destination_state",
                              equal_to(
                                  transition_meta_2.destination_state.id)))))
Example #35
0
    def test_Diagnostics_Multiline(self, app):
        contents = """
struct Foo {
  Foo(int z) {}
};

int main() {
  Foo foo("goo");
}
"""

        diag_data = BuildRequest(compilation_flags=['-x', 'c++'],
                                 line_num=7,
                                 contents=contents,
                                 filetype='cpp')

        event_data = diag_data.copy()
        event_data.update({
            'event_name': 'FileReadyToParse',
        })

        app.post_json('/event_notification', event_data)
        results = app.post_json('/detailed_diagnostic', diag_data).json
        assert_that(results, has_entry('message', contains_string("\n")))
Example #36
0
def DebugInfo_FlagsWhenGlobalExtraConfAndNoCompilationDatabase_test( app ):
  request_data = BuildRequest( filepath = PathToTestFile( 'basic.cpp' ),
                               filetype = 'cpp' )
  assert_that(
    app.post_json( '/debug_info', request_data ).json,
    has_entry( 'completer', has_entries( {
      'name': 'C-family',
      'servers': empty(),
      'items': contains(
        has_entries( {
          'key': 'compilation database path',
          'value': 'None'
        } ),
        has_entries( {
          'key': 'flags',
          'value': matches_regexp( "\\[u?'-x', u?'c\\+\\+', .*\\]" )
        } ),
        has_entries( {
          'key': 'translation unit',
          'value': PathToTestFile( 'basic.cpp' )
        } )
      )
    } ) )
  )
Example #37
0
    def test_address_field(self):
        params = {'emails': [ONE, SIX]}
        assert_that(
            calling(self.admin_schema.load).with_args(params),
            raises(
                ValidationError,
                has_property(
                    "messages",
                    has_entries(emails=has_entry(1, has_key('address')))),
            ),
        )

        params = {'emails': [ONE, TWO, TWO]}
        assert_that(
            calling(self.admin_schema.load).with_args(params),
            raises(
                ValidationError,
                has_property(
                    "messages",
                    has_entries(_schema=contains_exactly(
                        'The same address can only be used once')),
                ),
            ),
        )
Example #38
0
def GetDetailedDiagnostic_ClangCompleter_Works_test():
    app = TestApp(handlers.app)
    contents = """
struct Foo {
  int x  // semicolon missing here!
  int y;
  int c;
  int d;
};
"""

    diag_data = BuildRequest(compilation_flags=['-x', 'c++'],
                             line_num=3,
                             contents=contents,
                             filetype='cpp')

    event_data = diag_data.copy()
    event_data.update({
        'event_name': 'FileReadyToParse',
    })

    app.post_json('/event_notification', event_data)
    results = app.post_json('/detailed_diagnostic', diag_data).json
    assert_that(results, has_entry('message', contains_string("expected ';'")))
Example #39
0
    def test_Diagnostics_DetailedDiags(self, app):
        filepath = PathToTestFile('common', 'src', 'main.rs')
        contents = ReadFile(filepath)
        with open(filepath, 'w') as f:
            f.write(contents)
        event_data = BuildRequest(event_name='FileSave',
                                  contents=contents,
                                  filepath=filepath,
                                  filetype='rust')
        app.post_json('/event_notification', event_data)

        WaitForDiagnosticsToBeReady(app, filepath, contents, 'rust')
        request_data = BuildRequest(contents=contents,
                                    filepath=filepath,
                                    filetype='rust',
                                    line_num=14,
                                    column_num=13)

        results = app.post_json('/detailed_diagnostic', request_data).json
        assert_that(
            results,
            has_entry(
                'message',
                'no field `build_` on type `test::Builder`\nunknown field'))
Example #40
0
def Diagnostics_Basic_test(app):
    filepath = PathToTestFile('testy', 'Program.cs')
    with WrapOmniSharpServer(app, filepath):
        contents = ReadFile(filepath)

        event_data = BuildRequest(filepath=filepath,
                                  event_name='FileReadyToParse',
                                  filetype='cs',
                                  contents=contents)
        app.post_json('/event_notification', event_data)

        diag_data = BuildRequest(filepath=filepath,
                                 filetype='cs',
                                 contents=contents,
                                 line_num=11,
                                 column_num=2)

        results = app.post_json('/detailed_diagnostic', diag_data).json
        assert_that(
            results,
            has_entry(
                'message',
                contains_string(
                    "Unexpected symbol `}'', expecting identifier")))
Example #41
0
 def test_DebugInfo_ExtraConf_Global( self, app ):
   request_data = BuildRequest( filepath = PathToTestFile( 'foo.cpp' ),
                                contents = '',
                                filetype = 'cpp' )
   test = { 'request': request_data }
   request_data[ 'contents' ] = ''
   RunAfterInitialized( app, test )
   assert_that(
     app.post_json( '/debug_info', request_data ).json,
     has_entry( 'completer', has_entries( {
       'name': 'C-family',
       'servers': contains_exactly( has_entries( {
         'name': 'Clangd',
         'is_running': True,
         'extras': contains_exactly(
           has_entries( {
             'key': 'Server State',
             'value': 'Initialized',
           } ),
           has_entries( {
             'key': 'Project Directory',
             'value': PathToTestFile(),
           } ),
           has_entries( {
             'key': 'Settings',
             'value': '{}',
           } ),
           has_entries( {
             'key': 'Compilation Command',
             'value': has_items( '-I', 'test' ),
           } ),
         ),
       } ) ),
       'items': empty()
     } ) )
   )
Example #42
0
    def test_that_importing_a_contact_with_an_existing_uuid(self):
        csv = textwrap.dedent(
            '''\
        firstname
        alice
        '''
        )
        result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT)
        for user in result['created']:
            uuid = user['id']
            break

        csv = textwrap.dedent(
            '''\
        id,firstname
        {},not alice
        29d4aec1-db4c-4c67-80a0-b83136c58a47,bob
        '''.format(
                uuid
            )
        )
        result = self.import_personal(csv, VALID_TOKEN_MAIN_TENANT)

        assert_that(result['failed'], contains(has_entry('line', 2)))
Example #43
0
 def test_dashboard_with_nonexistent_tab_slug_returns_nothing(self):
     dashboard = DashboardFactory(slug='my-first-slug')
     module_type = ModuleTypeFactory()
     ModuleFactory(type=module_type,
                   dashboard=dashboard,
                   slug='module',
                   info=['module-info'],
                   title='module-title',
                   options={
                       'tabs': [{
                           'slug': 'tab-we-want',
                           'title': 'tab-title'
                       }, {
                           'slug': 'tab-we-dont-want',
                       }]
                   })
     ModuleFactory(type=module_type,
                   dashboard=dashboard,
                   slug='module-we-dont-want')
     resp = self.client.get(
         '/public/dashboards',
         {'slug': 'my-first-slug/module/module-non-existent-tab'})
     data = json.loads(resp.content)
     assert_that(data, has_entry('status', 'error'))
Example #44
0
    def test__shouldCreateTransitionMetaWithGivenPriority(self):
        initial_state = State.objects.create(label="state-1")
        state_2 = State.objects.create(label="state-2")

        content_type = ContentType.objects.first()
        workflow = Workflow.objects.create(initial_state=initial_state,
                                           content_type=content_type,
                                           field_name="test-field")

        response = self.client.post('/transition-meta/create/',
                                    data={
                                        "workflow": workflow.id,
                                        "source_state": initial_state.id,
                                        "destination_state": state_2.id
                                    })
        assert_that(response.status_code, equal_to(HTTP_200_OK))

        created_transition_meta = TransitionMeta.objects.first()
        assert_that(response.data,
                    has_entry("id", equal_to(created_transition_meta.pk)))
        assert_that(created_transition_meta,
                    has_property("source_state", equal_to(initial_state)))
        assert_that(created_transition_meta,
                    has_property("destination_state", equal_to(state_2)))
Example #45
0
 def test_DebugInfo_TypeScriptCompleter(self, app):
     request_data = BuildRequest(filetype='javascript')
     assert_that(
         app.post_json('/debug_info', request_data).json,
         has_entry(
             'completer',
             has_entries({
                 'name':
                 'TypeScript',
                 'servers':
                 contains_exactly(
                     has_entries({
                         'name':
                         'TSServer',
                         'is_running':
                         True,
                         'executable':
                         instance_of(str),
                         'pid':
                         instance_of(int),
                         'address':
                         None,
                         'port':
                         None,
                         'logfiles':
                         contains_exactly(instance_of(str)),
                         'extras':
                         contains_exactly(
                             has_entries({
                                 'key':
                                 'version',
                                 'value':
                                 any_of(None, instance_of(str))
                             }))
                     }))
             })))
Example #46
0
def DebugInfo_test(app):
    request_data = BuildRequest(filetype='javascript')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entries({
                'name':
                'JavaScript',
                'servers':
                contains(
                    has_entries({
                        'name':
                        'Tern',
                        'is_running':
                        instance_of(bool),
                        'executable':
                        instance_of(str),
                        'pid':
                        instance_of(int),
                        'address':
                        instance_of(str),
                        'port':
                        instance_of(int),
                        'logfiles':
                        contains(instance_of(str), instance_of(str)),
                        'extras':
                        contains(
                            has_entries({
                                'key': 'configuration file',
                                'value': instance_of(str)
                            }))
                    })),
                'items':
                empty()
            })))
def DebugInfo_test(app):
    request_data = BuildRequest(filetype='python')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entries({
                'name':
                'Python',
                'items':
                contains_exactly(
                    has_entries({
                        'key': 'Python interpreter',
                        'value': instance_of(str)
                    }),
                    has_entries({
                        'key': 'Python root',
                        'value': instance_of(str)
                    }),
                    has_entries({
                        'key': 'Python path',
                        'value': instance_of(str)
                    }),
                    has_entries({
                        'key': 'Python version',
                        'value': instance_of(str)
                    }),
                    has_entries({
                        'key': 'Jedi version',
                        'value': instance_of(str)
                    }),
                    has_entries({
                        'key': 'Parso version',
                        'value': instance_of(str)
                    }))
            })))
    def test_EventNotification_FileReadyToParse_SyntaxKeywords_SeedWithCache(
            self, ycm, *args):

        current_buffer = VimBuffer(name='current_buffer',
                                   filetype='some_filetype')

        with patch('ycm.client.event_notification.EventNotification.'
                   'PostDataToHandlerAsync') as post_data_to_handler_async:
            with MockVimBuffers([current_buffer], [current_buffer]):
                ycm.OnFileReadyToParse()
                assert_that(
                    # Positional arguments passed to PostDataToHandlerAsync.
                    post_data_to_handler_async.call_args[0],
                    contains_exactly(
                        has_entry('syntax_keywords', has_items('foo', 'bar')),
                        'event_notification'))

                # Do not send again syntax keywords in subsequent requests.
                ycm.OnFileReadyToParse()
                assert_that(
                    # Positional arguments passed to PostDataToHandlerAsync.
                    post_data_to_handler_async.call_args[0],
                    contains_exactly(is_not(has_key('syntax_keywords')),
                                     'event_notification'))
    def test_decrypt_data_file(self, mock_getpass):

        ciphertext = (
            b'Salted__\xbe\x82\x11\xc4\x01\xe6\x94\xfc\x93\xb5\x8aF\xeb\x8chEy"'
            b'\xd0\xb4\x04\xf3g\xb3.UX\x18\x17\x95\xe7 x7\x16\xa4{\x805~z\xe5\xad\xdc\xc4\xdc'
            b'\xd43\x8e\xfd\xda\x108\xbfv\xf8yW\x1f\xd2\xd73j\x0f\xce\x0f(4\x95\xe3{&~{\xdf'
            b'\x8ekm\xbb\x01\x17\xf28\x97\xd4\xfaSL\x99\xb5I\xfb\xc4\t\xb8\xeeH\x97\x02\\\xc8\xd6dw'
        )

        fd, cast_file_path = tempfile.mkstemp(suffix=".cast5",
                                              prefix="passwords_test")
        self.addCleanup(os.remove, cast_file_path)
        os.write(fd, ciphertext)
        os.close(fd)

        mock_getpass.is_callable().returns('temp001')

        buildout = NoDefaultBuildout()
        options = {'file': cast_file_path, 'output-file': 'decrypted'}

        section = DecryptFile(buildout, 'passwords', options)

        assert_that(options, has_entry('_input_mod_time', not_none()))

        section.install()

        assert_that(
            os.path.isfile(os.path.join('parts', 'passwords', 'plaintext')))
        assert_that(
            os.path.isfile(os.path.join('parts', 'passwords', 'checksum')))
        assert_that(os.path.isfile('decrypted'))

        with open('decrypted', 'rb') as f:
            data = f.read()

        self.assertIn(b'[passwords]', data)
Example #50
0
def LanguageServerCompleter_GetCompletions_UnsupportedKinds_test( app ):
  completer = MockCompleter()
  request_data = RequestWrap( BuildRequest() )

  completion_response = { 'result': [ { 'label': 'test',
                                        'kind': len( lsp.ITEM_KIND ) + 1 } ] }

  resolve_responses = [
    { 'result': { 'label': 'test' } },
  ]

  with patch.object( completer, '_is_completion_provider', True ):
    with patch.object( completer.GetConnection(),
                       'GetResponse',
                       side_effect = [ completion_response ] +
                                     resolve_responses ):
      assert_that(
        completer.ComputeCandidatesInner( request_data, 1 ),
        contains_exactly(
          has_items( all_of( has_entry( 'insertion_text', 'test' ),
                             is_not( has_key( 'kind' ) ) ) ),
          False
        )
      )
Example #51
0
    def test_given_call_logs_when_list_cdr_with_number_then_list_matching_cdr(
            self):
        result = self.call_logd.cdr.list(number='_45')
        assert_that(
            result,
            has_entries(filtered=2,
                        total=4,
                        items=contains_inanyorder(
                            has_entry('source_extension', '12345'),
                            has_entry('destination_extension', '45'),
                        )))

        result = self.call_logd.cdr.list(number='45')
        assert_that(
            result,
            has_entries(filtered=1,
                        total=4,
                        items=contains_inanyorder(
                            has_entry('destination_extension', '45'), )))

        result = self.call_logd.cdr.list(number='_23_')
        assert_that(
            result,
            has_entries(filtered=2,
                        total=4,
                        items=contains_inanyorder(
                            has_entry('source_extension', '12345'),
                            has_entry('source_extension', '123'),
                        )))

        result = self.call_logd.cdr.list(number='4_')
        assert_that(
            result,
            has_entries(filtered=1,
                        total=4,
                        items=contains_inanyorder(
                            has_entry('destination_extension', '45'), )))

        result = self.call_logd.cdr.list(number='0123456789')
        assert_that(result, has_entries(filtered=0, total=4, items=empty()))
Example #52
0
    def test__shouldReturnListOfStates(self):
        function_1 = Function.objects.create(name="test-function-1",
                                             body="function-body")
        function_2 = Function.objects.create(name="test-function-2",
                                             body="function-body")

        response = self.client.get('/function/list/')
        assert_that(response.status_code, equal_to(HTTP_200_OK))
        assert_that(response.data, has_length(2))
        assert_that(
            response.data,
            has_item(
                all_of(has_entry("id", equal_to(function_1.id)),
                       has_entry("name", equal_to(function_1.name)),
                       has_entry("body", equal_to(function_1.body)))))

        assert_that(
            response.data,
            has_item(
                all_of(has_entry("id", equal_to(function_2.id)),
                       has_entry("name", equal_to(function_2.name)),
                       has_entry("body", equal_to(function_2.body)))))
def ServerManagement_StopServerTwice_test( app ):
  StartJavaCompleterServerInDirectory(
    app, PathToTestFile( 'simple_eclipse_project' ) )

  app.post_json(
    '/run_completer_command',
    BuildRequest(
      filetype = 'java',
      command_arguments = [ 'StopServer' ],
    ),
  )

  request_data = BuildRequest( filetype = 'java' )
  assert_that( app.post_json( '/debug_info', request_data ).json,
               has_entry(
                 'completer',
                 has_entry( 'servers', contains(
                   has_entry( 'is_running', False )
                 ) )
               ) )


  # Stopping a stopped server is a no-op
  app.post_json(
    '/run_completer_command',
    BuildRequest(
      filetype = 'java',
      command_arguments = [ 'StopServer' ],
    ),
  )

  request_data = BuildRequest( filetype = 'java' )
  assert_that( app.post_json( '/debug_info', request_data ).json,
               has_entry(
                 'completer',
                 has_entry( 'servers', contains(
                   has_entry( 'is_running', False )
                 ) )
               ) )
Example #54
0
    def test_swagger(self):
        response = self.client.get("/api/swagger")
        assert_that(response.status_code, is_(equal_to(200)))
        data = loads(response.data)["paths"]["/foo"]["post"]

        assert_that(
            data["parameters"],
            has_items(
                has_entry(
                    "in",
                    "body",
                ),
                has_entry(
                    "schema",
                    has_entry(
                        "$ref",
                        "#/definitions/FooRequest",
                    ),
                ),
            ),
        )
        assert_that(
            data["responses"],
            all_of(
                has_key("200"),
                is_not(has_key("204")),
                has_entry(
                    "200",
                    has_entry(
                        "schema",
                        has_entry(
                            "$ref",
                            "#/definitions/FooList",
                        ),
                    ),
                ),
            ),
        )
    def test_removed_unserializable(self):
        import warnings
        marker = object()
        ext = {
            'x': 1,
            'y': [1, 2, marker],
            'z': marker,
            'a': {3, 4},
            'b': {
                'c': (marker, 1)
            }
        }
        with warnings.catch_warnings(
                record=True):  # removed_unserializable is deprecated
            assert_that(removed_unserializable((1, 2, 3)), is_([1, 2, 3]))

            assert_that(removed_unserializable([[(1, 2, 3)]]),
                        is_([[[1, 2, 3]]]))
            removed_unserializable(ext)
        assert_that(ext, has_entry('x', is_(1)))
        assert_that(ext, has_entry('y', is_([1, 2, None])))
        assert_that(ext, has_entry('a', is_([3, 4])))
        assert_that(ext, has_entry('z', is_(none())))
        assert_that(ext, has_entry('b', has_entry('c', is_([None, 1]))))
Example #56
0
def test_list_multi_tenant(main, sub):
    response = confd.agents.skills.get(wazo_tenant=MAIN_TENANT)
    assert_that(
        response.items,
        all_of(
            has_item(has_entry('id', main['id'])),
            not_(has_item(has_entry('id', sub['id']))),
        ),
    )

    response = confd.agents.skills.get(wazo_tenant=SUB_TENANT)
    assert_that(
        response.items,
        all_of(
            has_item(has_entry('id', sub['id'])),
            not_(has_item(has_entry('id', main['id']))),
        ),
    )

    response = confd.agents.skills.get(wazo_tenant=MAIN_TENANT, recurse=True)
    assert_that(
        response.items,
        has_items(has_entry('id', main['id']), has_entry('id', sub['id'])),
    )
Example #57
0
def test_build_document():
    gapy_response = {
        "metrics": {
            "visits": "12345"
        },
        "dimensions": {
            "date": "2013-04-02"
        }
    }

    data = build_document(gapy_response, "weeklyvisits", date(2013, 4, 1))

    assert_that(
        data,
        has_entry(
            "_id",
            "d2Vla2x5dmlzaXRzXzIwMTMwMzMxMjMwMDAwX3dlZWtfMjAxMy0wNC0wMg=="))
    assert_that(data, has_entry("dataType", "weeklyvisits"))
    assert_that(
        data, has_entry("_timestamp", dt(2013, 4, 1, 0, 0, 0,
                                         "Europe/London")))
    assert_that(data, has_entry("timeSpan", "week"))
    assert_that(data, has_entry("date", "2013-04-02"))
    assert_that(data, has_entry("visits", 12345))
Example #58
0
    def test_given_mobile_destination_when_load_then_location_empty(self):
        relocate = dict(VALID_RELOCATE)
        relocate['destination'] = 'mobile'

        assert_that(user_relocate_request_schema.load(relocate),
                    has_entry('location', {}))
Example #59
0
 def calld_is_ready():
     status = integration_test.calld.status()
     assert_that(status, has_entries({
         'ari': has_entry('status', 'ok'),
         'bus_consumer': has_entry('status', 'ok')
     }))
Example #60
0
def MessageMatcher( msg ):
  return has_entry( 'message', contains_string( msg ) )