コード例 #1
0
def test_build_document_set():
    def build_gapy_response(visits):
        return {
            "metrics": visits,
            "dimensions": {"date": "2013-04-02"},
            "start_date":  date(2013, 4, 1)
        }

    results = [
        build_gapy_response({"visits": "12345", "avgSessionDuration": 400.0}),
        build_gapy_response(
            {"visits": "2313.13", "avgSessionDuration": "400.0"}),
        build_gapy_response({"visits": "4323", "avgSessionDuration": 1234}),
    ]
    docs = list(build_document_set(results))

    assert_that(docs, has_item(has_entries({
        "visits": 12345,
        "avgSessionDuration": 400000.0
    })))
    assert_that(docs, has_item(has_entries({
        "visits": 2313.13,
        "avgSessionDuration": 400000.0
    })))
    assert_that(docs, has_item(has_entries({
        "visits": 4323,
        "avgSessionDuration": 1234000
    })))
コード例 #2
0
ファイル: test_data_set.py プロジェクト: NRCan/backdrop
    def test_period_group_query_adds_missing_periods_in_correct_order(self):
        self.mock_storage.execute_query.return_value = [
            {'some_group': 'val1', '_week_start_at': d(2013, 1, 14), '_count': 23},
            {'some_group': 'val1', '_week_start_at': d(2013, 1, 21), '_count': 41},
            {'some_group': 'val2', '_week_start_at': d(2013, 1, 14), '_count': 31},
            {'some_group': 'val2', '_week_start_at': d(2013, 1, 28), '_count': 12},
        ]

        data = self.data_set.execute_query(
            Query.create(period=WEEK, group_by=['some_group'],
                         start_at=d_tz(2013, 1, 7, 0, 0, 0),
                         end_at=d_tz(2013, 2, 4, 0, 0, 0)))

        assert_that(data, has_item(has_entries({
            "some_group": "val1",
            "values": contains(
                has_entries({"_start_at": d_tz(2013, 1, 7), "_count": 0}),
                has_entries({"_start_at": d_tz(2013, 1, 14), "_count": 23}),
                has_entries({"_start_at": d_tz(2013, 1, 21), "_count": 41}),
                has_entries({"_start_at": d_tz(2013, 1, 28), "_count": 0}),
            ),
        })))

        assert_that(data, has_item(has_entries({
            "some_group": "val2",
            "values": contains(
                has_entries({"_start_at": d_tz(2013, 1, 7), "_count": 0}),
                has_entries({"_start_at": d_tz(2013, 1, 14), "_count": 31}),
                has_entries({"_start_at": d_tz(2013, 1, 21), "_count": 0}),
                has_entries({"_start_at": d_tz(2013, 1, 28), "_count": 12}),
            ),
        })))
コード例 #3
0
ファイル: test_port.py プロジェクト: crook/storops
    def test_connection_port_not_in_hba_port_set(self):
        ports = self.hba_port_set()
        c_port = VNXConnectionPort(sp='a', port_id=4, cli=t_cli())
        assert_that(ports, is_not(has_item(c_port)))

        c_port = VNXConnectionPort(sp='a', port_id=9, cli=t_cli())
        assert_that(ports, is_not(has_item(c_port)))
コード例 #4
0
ファイル: flags_test.py プロジェクト: OrangeCrush/dotfiles
def FlagsForFile_DoNotAddMacIncludePathsWithSysroot_test():
  flags_object = flags.Flags()

  def FlagsForFile( filename ):
    return {
      'flags': [ '-isysroot', 'test1', '--test2=test' ]
    }

  with MockExtraConfModule( FlagsForFile ):
    flags_list = flags_object.FlagsForFile( '/foo' )
    assert_that( flags_list, not_( has_item( 'sentinel_value_for_testing' ) ) )

  def FlagsForFile( filename ):
    return {
      'flags': [ '-test', '--sysroot', 'test1' ]
    }

  with MockExtraConfModule( FlagsForFile ):
    flags_list = flags_object.FlagsForFile( '/foo' )
    assert_that( flags_list, not_( has_item( 'sentinel_value_for_testing' ) ) )

  def FlagsForFile( filename ):
    return {
      'flags': [ '-test', 'test1', '--sysroot=test' ]
    }

  with MockExtraConfModule( FlagsForFile ):
    flags_list = flags_object.FlagsForFile( '/foo' )
    assert_that( flags_list, not_( has_item( 'sentinel_value_for_testing' ) ) )
コード例 #5
0
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' ) ) )
               ) )
コード例 #6
0
 def Fallback_Suggestions_test(self):
     # TESTCASE1 (general_fallback/lang_c.c)
     self._RunTest({
         'description':
         '. after macro with some query text (.a_)',
         'request': {
             'filetype': 'c',
             'filepath': self._PathToTestFile('general_fallback',
                                              'lang_c.c'),
             'line_num': 29,
             'column_num': 23,
             'extra_conf_data': {
                 '&filetype': 'c'
             },
             'force_semantic': False,
         },
         'expect': {
             'response':
             http.client.OK,
             'data':
             has_entries({
                 'completions':
                 has_item(
                     self._CompletionEntryMatcher('a_parameter', '[ID]')),
                 'errors':
                 has_item(self._no_completions_error),
             })
         },
     })
コード例 #7
0
ファイル: get_completions_test.py プロジェクト: CoderPad/ycmd
def GetCompletions_MaxDetailedCompletion_test( app ):
  RunTest( app, {
    'expect': {
      'data': has_entries( {
        'completions': all_of(
          contains_inanyorder(
            CompletionEntryMatcher( 'methodA' ),
            CompletionEntryMatcher( 'methodB' ),
            CompletionEntryMatcher( 'methodC' ),
          ),
          is_not( any_of(
            has_item(
              CompletionEntryMatcher( 'methodA', extra_params = {
                'menu_text': 'methodA (method) Foo.methodA(): void' } ) ),
            has_item(
              CompletionEntryMatcher( 'methodB', extra_params = {
                'menu_text': 'methodB (method) Foo.methodB(): void' } ) ),
            has_item(
              CompletionEntryMatcher( 'methodC', extra_params = {
                'menu_text': ( 'methodC (method) Foo.methodC(a: '
                               '{ foo: string; bar: number; }): void' ) } ) )
          ) )
        )
      } )
    }
  } )
コード例 #8
0
ファイル: test_data_set.py プロジェクト: NRCan/stagecraft
    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))))
コード例 #9
0
def test_good_gotoassignment_do_not_follow_imports():
  app = TestApp( handlers.app )
  filepath = fixture_filepath( 'follow_imports', 'importer.py' )
  request_data = {
      'source': open( filepath ).read(),
      'line': 3,
      'col': 9,
      'source_path': filepath
  }
  expected_definition = {
      'module_path': filepath,
      'name': 'imported_function',
      'in_builtin_module': False,
      'line': 1,
      'column': 21,
      'docstring': '',
      'description': 'from imported '
      'import imported_function',
      'is_keyword': False
  }

  definitions = app.post_json( '/gotoassignment',
                               request_data ).json[ 'definitions' ]

  assert_that( definitions, has_length( 1 ) )
  assert_that( definitions, has_item( expected_definition ) )

  request_data[ 'follow_imports' ] = False

  definitions = app.post_json( '/gotoassignment',
                               request_data ).json[ 'definitions' ]

  assert_that( definitions, has_length( 1 ) )
  assert_that( definitions, has_item( expected_definition ) )
コード例 #10
0
def test_build_document_set():
    def build_gapy_response(visits, name, start_date):
        return {
            "metrics": {"visits": visits},
            "dimensions": {"customVarValue1": name},
            "start_date": start_date,
        }

    mappings = {
        "customVarValue1": "name"
    }
    results = [
        build_gapy_response("12345", "Jane", date(2013, 4, 1)),
        build_gapy_response("2313", "John", date(2013, 4, 1)),
        build_gapy_response("4323", "Joanne", date(2013, 4, 8)),
    ]
    docs = build_document_set(results, "people", mappings)

    assert_that(docs, has_item(has_entries({
        "name": "Jane",
        "_timestamp": dt(2013, 4, 1, 0, 0, 0, "UTC"),
        "dataType": "people",
        "visits": 12345,
    })))
    assert_that(docs, has_item(has_entries({
        "name": "John",
        "_timestamp": dt(2013, 4, 1, 0, 0, 0, "UTC"),
        "visits": 2313,
    })))
    assert_that(docs, has_item(has_entries({
        "name": "Joanne",
        "_timestamp": dt(2013, 4, 8, 0, 0, 0, "UTC"),
        "visits": 4323,
    })))
コード例 #11
0
 def test_drinking_potion_empty_discards_it(self):
     """
     Test that empty potion is discarded from character inventory
     """
     assert_that(self.character.inventory, has_item(self.potion))
     drink(self.character,
           self.potion)
     assert_that(self.character.inventory, is_not(has_item(self.potion)))
コード例 #12
0
ファイル: handlers_test.py プロジェクト: micbou/JediHTTP
def test_py3():
    app = TestApp(handlers.app)
    filepath = fixture_filepath("py3.py")
    request_data = {"source": open(filepath).read(), "line": 19, "col": 11, "source_path": filepath}

    completions = app.post_json("/completions", request_data).json["completions"]

    assert_that(completions, has_item(CompletionEntry("values")))
    assert_that(completions, is_not(has_item(CompletionEntry("itervalues"))))
コード例 #13
0
    def test_concurrent_copy_image(self):
        concurrency = 3
        atomic_lock = threading.Lock()
        results = {"ok": 0, "existed": 0}

        datastore = self._find_configured_datastore_in_host_config()
        new_image_id = "concurrent-copy-%s" % str(uuid.uuid4())

        src_image = Image("ttylinux", datastore)
        dst_image = Image(new_image_id, datastore)

        # verify destination_id is not in datastore
        request = Host.GetImagesRequest(datastore.id)
        response = self.host_client.get_images(request)
        assert_that(response.result, is_(GetImagesResultCode.OK))
        assert_that(response.image_ids, has_item("ttylinux"))
        assert_that(response.image_ids, not(has_item(new_image_id)))
        image_number = len(response.image_ids)

        def _thread():
            client = self.create_client()
            request = Host.CopyImageRequest(src_image, dst_image)
            response = client.copy_image(request)
            ok = response.result == CopyImageResultCode.OK
            existed = response.result == CopyImageResultCode.\
                DESTINATION_ALREADY_EXIST

            # Verify destination_id is in datastore
            request = Host.GetImagesRequest(datastore.id)
            response = client.get_images(request)
            assert_that(response.result, is_(GetImagesResultCode.OK))
            assert_that(response.image_ids, has_item("ttylinux"))
            assert_that(response.image_ids, has_item(new_image_id))
            assert_that(response.image_ids, has_length(image_number + 1))
            with atomic_lock:
                if ok:
                    results["ok"] += 1
                if existed:
                    results["existed"] += 1

        threads = []
        for i in range(concurrency):
            thread = threading.Thread(target=_thread)
            threads.append(thread)
            thread.start()

        for thread in threads:
            thread.join()

        # Clean destination image
        self._delete_image(dst_image)

        # Only one copy is successful, all others return
        # DESTINATION_ALREADY_EXIST
        assert_that(results["ok"], is_(1))
        assert_that(results["existed"], is_(concurrency - 1))
コード例 #14
0
ファイル: test_core.py プロジェクト: perfa/py-x
    def test_should_aggregate_all_suite_names(self):
        suite = XunitSuite("name")
        suite2 = XunitSuite("other name")
        results = Xunit()

        results.append(suite)
        results.append(suite2)
        names = [x.name for x in results.suites]
        assert_that(names, has_item("name"))
        assert_that(names, has_item("other name"))
コード例 #15
0
    def test_build_query_with_boolean_value(self):
        request_args = MultiDict([
            ("filter_by", "planet:true"),
            ("filter_by", "star:false"),
        ])

        args = parse_request_args(request_args)

        assert_that(args['filter_by'], has_item([ "planet", True ]))
        assert_that(args['filter_by'], has_item([ "star", False ]))
コード例 #16
0
    def test_many_filter_by_are_parsed(self):
        request_args = MultiDict([
            ("filter_by_prefix", "foo:bar"),
            ("filter_by_prefix", "bar:foo")
        ])

        args = parse_request_args(request_args)

        assert_that(args['filter_by_prefix'], has_item(["foo", 'bar']))
        assert_that(args['filter_by_prefix'], has_item(["bar", 'foo']))
コード例 #17
0
ファイル: matchers.py プロジェクト: manojpkr/allure-python
def has_label(test_name, label_name=anything(), label_value=anything()):
    return has_property('{}test-cases',
                        has_property('test-case',
                                     has_item(
                                         has_properties({'name': equal_to(test_name),
                                                         'labels': has_property('label',
                                                                                has_item(
                                                                                    has_property('attrib', equal_to(
                                                                                        {'name': label_name,
                                                                                         'value': label_value}))))}))))
コード例 #18
0
ファイル: test_cg.py プロジェクト: optionalg/storops
 def test_parse(self):
     output = """
             Name:  test cg name
             Name:  another cg
             """
     cgs = VNXConsistencyGroup.parse_all(output)
     self.assertEqual(2, len(cgs))
     names = [cg.name for cg in cgs]
     assert_that(names, has_item('test cg name'))
     assert_that(names, has_item('another cg'))
コード例 #19
0
 def test_line_is_too_long(self):
     # max is 72 total including the identation
     too_long = "".join(list(repeat("M", 70)))
     errors = check_message("search: hello\r\n\r\n"
                            "* {0}\r\n\r\n"
                            "* M{0}\r\n\r\n"
                            "Signed-off-by: a a <*****@*****.**>"
                            .format(too_long),
                            **self.kwargs)
     assert_that(errors, is_not(has_item("Line 3 is too long (72 > 72)")))
     assert_that(errors, has_item("Line 5 is too long (73 > 72)"))
コード例 #20
0
ファイル: test_parser.py プロジェクト: owtf/ptp
 def test_parser_wapiti_xml_parse_report(self, mock_lxml_etree_parse):
     from .wapiti_reports_2_3_0 import report_high
     with mock.patch('ptp.libptp.parser.AbstractParser._recursive_find', return_value=[report_high]):
         WapitiXMLParser.__format__ = ''
         my_wapiti = WapitiXMLParser()
         report = my_wapiti.parse_report()
         assert_that(report, has_items(*[{'ranking': HIGH, 'name': 'Cross Site Scripting', 'description': '\nCross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts.            '}] * 1))
         assert_that(report, is_not(has_item([{'ranking': LOW}])))
         assert_that(report, is_not(has_item([{'ranking': UNKNOWN}])))
         assert_that(report, is_not(has_item([{'ranking': INFO}])))
         assert_that(report, is_not(has_item([{'ranking': MEDIUM}])))
コード例 #21
0
def test_writes_one_record_per_track_in_album(formatter, out):
    project = make_album(tracks=[build.track(track_title="Song 1"),
                                 build.track(track_title="Song 2"),
                                 build.track(track_title="Song 3")])

    formatter.write(project, out)

    rows = read_csv(out)
    _ = next(rows)
    assert_that(next(rows), has_item("Song 1"), "first row")
    assert_that(next(rows), has_item("Song 2"), "second row")
    assert_that(next(rows), has_item("Song 3"), "third row")
コード例 #22
0
ファイル: test_ptp.py プロジェクト: owtf/ptp
 def test_ptp_no_cumulative_parsing(self):
     my_ptp = PTP(cumulative=False)
     my_ptp.parser = MockParserInfo()  # Tool 1, first run
     report = my_ptp.parse()
     assert_that(1, equal_to(len(report)))
     assert_that(report, has_item({'ranking': constants.INFO}))
     assert_that(report, is_not(has_item({'ranking': constants.HIGH})))
     my_ptp.parser = MockParserHigh()  # Tool 2, second run
     report = my_ptp.parse()
     assert_that(1, equal_to(len(report)))
     assert_that(report, has_item({'ranking': constants.HIGH}))
     assert_that(report, is_not(has_item({'ranking': constants.INFO})))
コード例 #23
0
ファイル: test_parser.py プロジェクト: owtf/ptp
 def test_parser_arachni_json_parse_report(self, mock_handle):
     # Arachni version 1.2.1
     from .arachni_json_reports_1_2_1 import report_high
     my_arachni = ArachniJSONParser(None)
     my_arachni.stream = json.loads(report_high)
     report = my_arachni.parse_report()
     assert_that(report, has_items(*[{'ranking': INFO}] * 6))
     assert_that(report, has_item(*[{'ranking': MEDIUM}]))
     assert_that(report, has_item(*[{'ranking': LOW}]))
     assert_that(report, has_item(*[{'ranking': HIGH}]))
     assert_that(report, is_not(has_item([{'ranking': UNKNOWN}])))
     assert_that(10, equal_to(len(report)))
     assert_that(10, equal_to(len(report[-1]['transactions'])))
コード例 #24
0
    def test_many_filter_by_are_parsed(self):
        request_args = MultiDict([
            ("filter_by_prefix", "foo:bar"),
            ("filter_by_prefix", "bar:foo")
        ])

        args = parse_request_args(request_args)

        parsed_regex1 = re.compile('^bar.*')
        parsed_regex2 = re.compile('^foo.*')

        assert_that(args['filter_by_prefix'], has_item(["foo", parsed_regex1]))
        assert_that(args['filter_by_prefix'], has_item(["bar", parsed_regex2]))
コード例 #25
0
ファイル: test_nfs_share.py プロジェクト: crook/storops
 def verify_share_eee(share):
     assert_that(share.path, equal_to('/EEE'))
     assert_that(share.read_only, equal_to(False))
     assert_that(share.fs_id, equal_to(213))
     assert_that(share.mover_id, equal_to(1))
     assert_that(len(share.root_hosts), equal_to(41))
     assert_that(share.access_hosts, has_item('10.110.43.94'))
     assert_that(len(share.access_hosts), equal_to(41))
     assert_that(share.access_hosts, has_item('10.110.43.94'))
     assert_that(len(share.rw_hosts), equal_to(41))
     assert_that(share.rw_hosts, has_item('10.110.43.94'))
     assert_that(len(share.ro_hosts), equal_to(41))
     assert_that(share.ro_hosts, has_item('10.110.43.94'))
コード例 #26
0
    def test_that_make_links_creates_links_to__multiple_targets_if_specified(self):
        source_url = self.dut.update_entry("network", "compatibleone", {"label": "ethernet", "vlan": "100M"})
        target_url = self.dut.update_entry(
            "port", "http", {"protocol": "tcp", "from": "80", "to": "80", "direction": "inout", "state": "0"}
        )
        target_url2 = self.dut.update_entry(
            "port", "something_else", {"protocol": "tcp", "from": "80", "to": "80", "direction": "inout", "state": "0"}
        )

        self.dut.make_links(source_url, [target_url, target_url2])

        link_targets = self.dut.read_link_targets(source_url)
        assert_that(link_targets, has_item(target_url))
        assert_that(link_targets, has_item(target_url2))
コード例 #27
0
ファイル: test_parser.py プロジェクト: owtf/ptp
 def test_parser_owasp_cm008_parse_report(self, mock_handle):
     from .owasp_cm008_reports import report_low
     my_cm008 = OWASPCM008Parser(report_low)
     report = my_cm008.parse_report()
     assert_that(report, has_items(*[{'ranking': UNKNOWN}] * 2))
     assert_that(report, has_items(*[{'ranking': LOW}] * 2))
     assert_that(report, is_not(has_item([{'ranking': INFO}])))
     assert_that(report, is_not(has_item([{'ranking': MEDIUM}])))
     assert_that(report, is_not(has_item([{'ranking': HIGH}])))
     from .owasp_cm008_reports import report_medium
     my_cm008 = OWASPCM008Parser(report_medium)
     report = my_cm008.parse_report()
     assert_that(report, has_items(*[{'ranking': UNKNOWN}] * 1))
     assert_that(report, has_items(*[{'ranking': MEDIUM}] * 1))
     assert_that(report, is_not(has_item([{'ranking': INFO}])))
     assert_that(report, is_not(has_item([{'ranking': LOW}])))
     assert_that(report, is_not(has_item([{'ranking': HIGH}])))
     from .owasp_cm008_reports import report_high
     my_cm008 = OWASPCM008Parser(report_high)
     report = my_cm008.parse_report()
     assert_that(report, has_items(*[{'ranking': UNKNOWN}] * 2))
     assert_that(report, has_items(*[{'ranking': LOW}] * 2))
     assert_that(report, has_items(*[{'ranking': HIGH}] * 1))
     assert_that(report, is_not(has_item([{'ranking': INFO}])))
     assert_that(report, is_not(has_item([{'ranking': MEDIUM}])))
コード例 #28
0
    def test_swagger(self):
        response = self.client.get("/api/swagger")
        assert_that(response.status_code, is_(equal_to(200)))
        data = loads(response.data)

        upload = data["paths"]["/file"]["post"]
        upload_for = data["paths"]["/person/{person_id}/file"]["post"]

        # both endpoints return form data
        assert_that(
            upload["consumes"],
            contains("multipart/form-data"),
        )
        assert_that(
            upload_for["consumes"],
            contains("multipart/form-data"),
        )

        # one endpoint gets an extra query string parameter (and the other doesn't)
        assert_that(
            upload["parameters"],
            has_item(
                has_entries(name="extra"),
            ),
        )
        assert_that(
            upload_for["parameters"],
            has_item(
                is_not(has_entries(name="extra")),
            ),
        )

        # one endpoint gets a custom response type (and the other doesn't)
        assert_that(
            upload["responses"],
            all_of(
                has_key("204"),
                is_not(has_key("200")),
                has_entry("204", is_not(has_key("schema"))),
            ),
        )
        assert_that(
            upload_for["responses"],
            all_of(
                has_key("200"),
                is_not(has_key("204")),
                has_entry("200", has_entry("schema", has_entry("$ref", "#/definitions/FileResponse"))),
            ),
        )
コード例 #29
0
ファイル: test_data_set.py プロジェクト: NRCan/backdrop
    def test_month_and_groups_query(self):
        self.mock_storage.execute_query.return_value = [
            {'some_group': 'val1', 'another_group': 'val3', '_month_start_at': d(2013, 1, 1), '_count': 1},
            {'some_group': 'val1', 'another_group': 'val3', '_month_start_at': d(2013, 2, 1), '_count': 5},
            {'some_group': 'val2', 'another_group': 'val3', '_month_start_at': d(2013, 3, 1), '_count': 2},
            {'some_group': 'val2', 'another_group': 'val3', '_month_start_at': d(2013, 4, 1), '_count': 6},
            {'some_group': 'val2', 'another_group': 'val3', '_month_start_at': d(2013, 7, 1), '_count': 6},
        ]

        data = self.data_set.execute_query(Query.create(period=MONTH,
                                                        group_by=['some_group', 'another_group']))
        assert_that(data,
                    has_item(has_entries({"values": has_length(2)})))
        assert_that(data,
                    has_item(has_entries({"values": has_length(3)})))
コード例 #30
0
    def test_one_filter_by_is_parsed(self):
        request_args = MultiDict([
            ("filter_by", "foo:bar")])

        args = parse_request_args(request_args)

        assert_that(args['filter_by'], has_item(["foo", "bar"]))
コード例 #31
0
    def test_subscriptions_manipulate_with_user1(self, subscription_):
        webhookd = self.make_webhookd(USER_1_TOKEN)
        response = webhookd.subscriptions.list()
        assert_that(
            response,
            has_entry('items', has_item(has_entry('uuid', subscription_['uuid']))),
        )

        response = webhookd.subscriptions.get(subscription_['uuid'])
        assert_that(response, has_entry('uuid', subscription_['uuid']))

        subscription_["name"] = "update 1"
        response = webhookd.subscriptions.update(subscription_['uuid'], subscription_)
        assert_that(response, has_entry('uuid', subscription_['uuid']))
        assert_that(response, has_entry('name', subscription_['name']))

        webhookd.subscriptions.delete(subscription_['uuid'])
        self.ensure_webhookd_not_consume_uuid(subscription_['uuid'])
        response = webhookd.subscriptions.list()
        assert_that(response, has_entry('items', equal_to([])))

        response = webhookd.subscriptions.create_as_user(subscription_)
        assert_that(response, has_entry('name', subscription_['name']))

        subscription_["uuid"] = response["uuid"]

        response = webhookd.subscriptions.get_as_user(subscription_['uuid'])
        assert_that(response, has_entry('uuid', subscription_['uuid']))

        subscription_["name"] = "update 2"
        response = webhookd.subscriptions.update_as_user(
            subscription_['uuid'], subscription_
        )
        assert_that(response, has_entry('uuid', subscription_['uuid']))
        assert_that(response, has_entry('name', subscription_['name']))

        webhookd.subscriptions.delete_as_user(subscription_['uuid'])
        self.ensure_webhookd_not_consume_uuid(subscription_['uuid'])
コード例 #32
0
def EventNotification_FileReadyToParse_TagFiles_UnicodeWorkingDirectory_test(
        ycm, *args):
    unicode_dir = PathToTestFile('uni¢𐍈d€')
    current_buffer_file = PathToTestFile('uni¢𐍈d€', 'current_buffer')
    current_buffer = VimBuffer(name=current_buffer_file,
                               contents=['current_buffer_contents'],
                               filetype='some_filetype')

    with patch('ycm.client.event_notification.EventNotification.'
               'PostDataToHandlerAsync') as post_data_to_handler_async:
        with CurrentWorkingDirectory(unicode_dir):
            with MockVimBuffers([current_buffer], current_buffer, (1, 5)):
                ycm.OnFileReadyToParse()

        assert_that(
            # Positional arguments passed to PostDataToHandlerAsync.
            post_data_to_handler_async.call_args[0],
            contains(
                has_entries({
                    'filepath':
                    current_buffer_file,
                    'line_num':
                    1,
                    'column_num':
                    6,
                    'file_data':
                    has_entries({
                        current_buffer_file:
                        has_entries({
                            'contents': 'current_buffer_contents\n',
                            'filetypes': ['some_filetype']
                        })
                    }),
                    'event_name':
                    'FileReadyToParse',
                    'tag_files':
                    has_item(PathToTestFile('uni¢𐍈d€', 'tags'))
                }), 'event_notification'))
コード例 #33
0
def GetCompletions_ClientDataGivenToExtraConf_Include_test( app ):
  app.post_json(
    '/load_extra_conf_file',
    { 'filepath': PathToTestFile( 'client_data',
                                  '.ycm_extra_conf.py' ) } )

  filepath = PathToTestFile( 'client_data', 'include.cpp' )
  completion_data = BuildRequest( filepath = filepath,
                                  filetype = 'cpp',
                                  contents = ReadFile( filepath ),
                                  line_num = 1,
                                  column_num = 11,
                                  extra_conf_data = {
                                    'flags': [ '-x', 'c++' ]
                                  } )

  results = app.post_json( '/completions',
                           completion_data ).json[ 'completions' ]
  assert_that(
    results,
    has_item( CompletionEntryMatcher( 'include.hpp',
              extra_menu_info = '[File]' ) )
  )
コード例 #34
0
 def assert_function():
     assert_that(
         events.accumulate(with_headers=True),
         has_item(
             has_entries(message=has_entries({
                 'name':
                 'call_ended',
                 'origin_uuid':
                 XIVO_UUID,
                 'data':
                 has_entries({
                     'creation_time': '2016-02-01T15:00:00.000-0500',
                     'sip_call_id': 'foobar',
                     'line_id': 2,
                     'reason_code': 0,
                     'is_caller': False,
                     'hangup_time': is_(a_timestamp()),
                 })
             }),
                         headers=has_entries(
                             name='call_ended',
                             tenant_uuid=VALID_TENANT,
                         ))))
コード例 #35
0
def GetCompletions_Keyword_test(app):
    RunTest(
        app, {
            'description':
            'No extra and detailed info when completion is a keyword',
            'request': {
                'line_num': 2,
                'column_num': 5,
                'filepath': PathToTestFile('test.ts'),
            },
            'expect': {
                'response':
                requests.codes.ok,
                'data':
                has_entries({
                    'completions':
                    has_item({
                        'insertion_text': 'class',
                        'kind': 'keyword',
                    })
                })
            }
        })
コード例 #36
0
def call_ansible_step(step_name, playbook="test-system.yml", extra_vars=None):
    """call_ansible_step - run a step by running a matching ansible tag"""

    proc_res = subprocess.run(args=["ansible-playbook", "--list-tags", playbook],
                              capture_output=True)
    if proc_res.returncode > 0:
        eprint("Ansible STDOUT:\n", proc_res.stdout, "Ansible STDERR:\n", proc_res.stderr)
        raise Exception("ansible failed while listing tags")

    lines = [x.lstrip() for x in proc_res.stdout.split(b"\n")]
    steps_lists = [x[10:].rstrip(b"]").lstrip(b"[ ").split(b",") for x in lines if x.startswith(b"TASK TAGS:")]
    steps = [x.lstrip() for y in steps_lists for x in y]
    eprint(b"\n".join([bytes(x) for x in steps]))
    assert_that(steps, has_item(bytes(step_name, 'latin-1')))

    eprint("calling ansible with: ", step_name)
    ansible_args = ["ansible-playbook", "-vvv", "--tags", step_name, playbook]
    if extra_vars is not None:
        ansible_args.extend(["--extra-vars", extra_vars])
    proc_res = subprocess.run(args=ansible_args, capture_output=True)
    eprint("Ansible STDOUT:\n", proc_res.stdout, "Ansible STDERR:\n", proc_res.stderr)
    if proc_res.returncode > 0:
        raise Exception("ansible failed")
コード例 #37
0
 def assert_function():
     assert_that(
         events.accumulate(with_headers=True),
         has_item(
             has_entries(
                 message=has_entries({
                     'name':
                     'call_answered',
                     'origin_uuid':
                     XIVO_UUID,
                     'data':
                     has_entries({
                         'call_id': call_id,
                         'status': 'Up',
                         'hangup_time': None,
                         'answer_time': is_(a_timestamp()),
                     })
                 }),
                 headers=has_entries(
                     name='call_answered',
                     tenant_uuid=VALID_TENANT,
                 ),
             )))
コード例 #38
0
def GetCompletions_ProcMacro_test(app):
    StartRustCompleterServerInDirectory(app, PathToTestFile('macro'))

    filepath = PathToTestFile('macro', 'src', 'main.rs')
    contents = ReadFile(filepath)

    completion_data = BuildRequest(filepath=filepath,
                                   filetype='rust',
                                   contents=contents,
                                   line_num=33,
                                   column_num=14)

    results = []
    expiration = time.time() + 60
    while time.time() < expiration:
        results = app.post_json('/completions',
                                completion_data).json['completions']
        if len(results) > 0:
            break
        time.sleep(0.25)

    assert_that(results, has_item(CompletionEntryMatcher('checkpoint')))

    # This completer does not require or support resolve
    assert_that(results[0], is_not(has_key('resolve')))
    assert_that(results[0], is_not(has_key('item')))

    # So (erroneously) resolving an item returns the item
    completion_data['resolve'] = 0
    response = app.post_json('/resolve_completion', completion_data).json
    print(f"Resolve resolve: { pformat( response ) }")

    # We can't actually check the result because we don't know what completion
    # resolve ID 0 actually is (could be anything), so we just check that we get 1
    # result, and that there are no errors.
    assert_that(response['completion'], is_not(None))
    assert_that(response['errors'], empty())
コード例 #39
0
def GetCompletions_AutoImport_test( app ):
  filepath = PathToTestFile( 'test.ts' )
  RunTest( app, {
    'description': 'Symbol from external module can be completed and '
                   'its completion contains fixits to automatically import it',
    'request': {
      'line_num': 39,
      'column_num': 5,
      'filepath': filepath,
    },
    'expect': {
      'response': requests.codes.ok,
      'data': has_entries( {
        'completions': has_item( has_entries( {
          'insertion_text':  'Bår',
          'extra_menu_info': 'class Bår',
          'detailed_info':   'class Bår',
          'kind':            'class',
          'extra_data': has_entries( {
            'fixits': contains_inanyorder(
              has_entries( {
                'text': 'Import \'Bår\' from module "./unicode"',
                'chunks': contains_exactly(
                  ChunkMatcher(
                    matches_regexp( '^import { Bår } from "./unicode";\r?\n' ),
                    LocationMatcher( filepath, 1, 1 ),
                    LocationMatcher( filepath, 1, 1 )
                  )
                ),
                'location': LocationMatcher( filepath, 39, 5 )
              } )
            )
          } )
        } ) )
      } )
    }
  } )
コード例 #40
0
def test_search(_, meeting, hidden):
    url = confd.meetings
    searches = {'name': 'search'}

    for field, term in searches.items():
        yield check_search, url, meeting, hidden, field, term

    response = url.get(persistent=True)
    assert_that(response.items, has_item(meeting))
    assert_that(response.items, is_not(has_item(hidden)))

    response = url.get(persistent=False)
    assert_that(response.items, has_item(hidden))
    assert_that(response.items, is_not(has_item(meeting)))

    response = url.get(require_authorization=False)
    assert_that(response.items, has_item(hidden))
    assert_that(response.items, is_not(has_item(meeting)))
コード例 #41
0
 def bus_events_received():
     assert_that(
         events.accumulate(with_headers=True),
         has_item(
             has_entries(
                 message=has_entries(
                     name='call_push_notification',
                     data=has_entries(
                         peer_caller_id_number='8001',
                         peer_caller_id_name='my name is 8001',
                         call_id='1560784195.313',
                         video=True,
                         sip_call_id='de9eb39fb7585796',
                     ),
                     required_acl='events.calls.fb27eb93-d21c-483f-8068-e685c90b07e1',
                 ),
                 headers=has_entries({
                     'name': 'call_push_notification',
                     'tenant_uuid': 'some-tenant-uuid',
                     'user_uuid:fb27eb93-d21c-483f-8068-e685c90b07e1': True,
                 })
             )
         )
     )
コード例 #42
0
def test_given_user_with_no_associations_when_exporting_then_csv_has_all_user_fields(
        user):
    expected = has_entries(uuid=user['uuid'],
                           firstname="Ûrsule",
                           lastname="Wèrber",
                           email="*****@*****.**",
                           mobile_phone_number="5551234567",
                           language="fr_FR",
                           outgoing_caller_id="Hûrsule <4441234567>",
                           userfield="userfield",
                           ring_seconds="15",
                           simultaneous_calls="10",
                           supervision_enabled="1",
                           call_transfer_enabled="1",
                           call_record_enabled="0",
                           online_call_record_enabled="0",
                           call_permission_password="******",
                           enabled="1",
                           username="******",
                           password="******",
                           entity_id="1")

    response = confd_csv.users.export.get()
    assert_that(response.csv(), has_item(expected))
コード例 #43
0
def GetCompletions_Fallback_Exception_test( app ):
  # TESTCASE4 (general_fallback/lang_c.c)
  # extra conf throws exception
  RunTest( app, {
    'description': '. on struct returns identifier because of error',
    'request': {
      'filetype'  : 'c',
      'filepath'  : PathToTestFile( 'general_fallback', 'lang_c.c' ),
      'line_num'  : 62,
      'column_num': 20,
      'extra_conf_data': { '&filetype': 'c', 'throw': 'testy' },
      'force_semantic': False,
    },
    'expect': {
      'response': requests.codes.ok,
      'data': has_entries( {
        'completions': contains(
          CompletionEntryMatcher( 'a_parameter', '[ID]' ),
          CompletionEntryMatcher( 'another_parameter', '[ID]' ),
        ),
        'errors': has_item( ErrorMatcher( ValueError, 'testy' ) )
      } )
    },
  } )
コード例 #44
0
def GetCompletions_Fallback_Suggestions_test(app):
    # TESTCASE1 (general_fallback/lang_c.c)
    RunTest(
        app, {
            'description': '. after macro with some query text (.a_)',
            'request': {
                'filetype': 'c',
                'filepath': PathToTestFile('general_fallback', 'lang_c.c'),
                'line_num': 29,
                'column_num': 23,
                'force_semantic': False,
            },
            'expect': {
                'response':
                requests.codes.ok,
                'data':
                has_entries({
                    'completions':
                    has_item(CompletionEntryMatcher('a_parameter', '[ID]')),
                    'errors':
                    empty(),
                })
            },
        })
コード例 #45
0
ファイル: get_completions_test.py プロジェクト: tungpd/ycmd
def GetCompletions_MoreThan100FilteredResolve_test( app ):
  RunTest( app, {
    'description': 'More that 100 match, but filtered set is fewer as this '
                   'depends on max_num_candidates',
    'request': {
      'filetype'  : 'java',
      'filepath'  : ProjectPath( 'TestLauncher.java' ),
      'line_num'  : 4,
      'column_num': 15,
    },
    'expect': {
      'response': requests.codes.ok,
      'data': has_entries( {
        'completions': has_item(
          CompletionEntryMatcher( 'com.youcompleteme.*;', None, {
            'kind': 'Module',
            'detailed_info': 'com.youcompleteme\n\n',
          } ),
        ),
        'completion_start_column': 8,
        'errors': empty(),
      } )
    },
  } )
コード例 #46
0
    def test_update_contact_fields_no_phone(self):
        self.source.load(self.DEPENDENCIES)

        mario = {
            'name': 'Mario Bros',
            'mobilePhone': None,
            'businessPhones': [],
            'homePhones': [],
        }

        assert_that(
            self.source._update_contact_fields([mario]),
            has_item(
                has_entries({
                    'numbers':
                    empty(),
                    'numbers_except_label':
                    has_entries({
                        'mobilePhone': empty(),
                        'businessPhones': empty(),
                        'homePhones': empty(),
                    }),
                })),
        )
コード例 #47
0
def GetCompletions_ClangCompleter_Fallback_NoSuggestions_test():
    # TESTCASE1 (general_fallback/lang_c.c)
    GetCompletions_RunTest({
        'description': 'Triggered, fallback but no query so no completions',
        'request': {
            'filetype': 'c',
            'filepath': PathToTestFile('general_fallback', 'lang_c.c'),
            'line_num': 29,
            'column_num': 21,
            'extra_conf_data': {
                '&filetype': 'c'
            },
            'force_semantic': False,
        },
        'expect': {
            'response':
            httplib.OK,
            'data':
            has_entries({
                'completions': empty(),
                'errors': has_item(NO_COMPLETIONS_ERROR),
            })
        },
    })
コード例 #48
0
def test_good_gotoassignment():
  app = TestApp( handlers.app )
  filepath = fixture_filepath( 'goto.py' )
  request_data = {
      'source': open( filepath ).read(),
      'line': 20,
      'col': 1,
      'source_path': filepath
  }

  definitions = app.post_json( '/gotoassignment',
                               request_data ).json[ 'definitions' ]

  assert_that( definitions, has_length( 1 ) )
  assert_that( definitions, has_item( {
                                'module_path': filepath,
                                'name': 'inception',
                                'in_builtin_module': False,
                                'line': 18,
                                'column': 0,
                                'docstring': '',
                                'description': 'inception = _list[ 2 ]',
                                'is_keyword': False
                            } ) )
コード例 #49
0
    def test_shouldReturnAnApprovalWhenUserIsAuthorizedWithAPermission(self):
        authorized_permission = PermissionObjectFactory()
        authorized_user = UserObjectFactory(
            user_permissions=[authorized_permission])

        state1 = StateObjectFactory(label="state1")
        state2 = StateObjectFactory(label="state2")

        workflow = WorkflowFactory(initial_state=state1,
                                   content_type=self.content_type,
                                   field_name="my_field")

        transition_meta = TransitionMetaFactory.create(
            workflow=workflow,
            source_state=state1,
            destination_state=state2,
        )
        TransitionApprovalMetaFactory.create(
            workflow=workflow,
            transition_meta=transition_meta,
            priority=0,
            permissions=[authorized_permission])

        workflow_object = BasicTestModelObjectFactory(workflow=workflow)

        available_approvals = BasicTestModel.river.my_field.get_available_approvals(
            as_user=authorized_user)
        assert_that(available_approvals, has_length(1))
        assert_that(
            list(available_approvals),
            has_item(
                all_of(
                    has_property("workflow_object", workflow_object.model),
                    has_property("workflow", workflow),
                    has_property("transition",
                                 transition_meta.transitions.first()))))
コード例 #50
0
    def test_removes_bond_from_get_bonds(self):
        self.client.remove_bond(42)

        assert_that(self.client.get_bonds(), not_(has_item(42)))
コード例 #51
0
def GetCompletions_ClientDataGivenToExtraConf_Cache_test( app ):
  app.post_json(
    '/load_extra_conf_file',
    { 'filepath': PathToTestFile( 'client_data', '.ycm_extra_conf.py' ) } )

  filepath = PathToTestFile( 'client_data', 'macro.cpp' )
  contents = ReadFile( filepath )
  request = {
    'filetype'  : 'cpp',
    'filepath'  : filepath,
    'contents'  : contents,
    'line_num'  : 11,
    'column_num': 8
  }

  # Complete with flags from the client.
  completion_request = CombineRequest( request, {
    'extra_conf_data': {
      'flags': [ '-DSOME_MACRO' ]
    }
  } )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': has_item(
        CompletionEntryMatcher( 'macro_defined' )
      ),
      'errors': empty()
    } )
  )

  # Complete at the same position but for a different set of flags from the
  # client.
  completion_request = CombineRequest( request, {
    'extra_conf_data': {
      'flags': [ '-Wall' ]
    }
  } )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': has_item(
        CompletionEntryMatcher( 'macro_not_defined' )
      ),
      'errors': empty()
    } )
  )

  # Finally, complete once again at the same position but no flags are given by
  # the client. An empty list of flags is returned by the extra conf file in
  # that case.
  completion_request = CombineRequest( request, {} )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': empty(),
      'errors': contains(
        ErrorMatcher( RuntimeError, NO_COMPILE_FLAGS_MESSAGE )
      )
    } )
  )
コード例 #52
0
 def assert_function():
     expected_message = 'PUTVAL [^/]+/calls-{app}.{app_instance}/counter-abandoned .* N:1'
     expected_message = expected_message.format(app=STASIS_APP,
                                                app_instance=STASIS_APP_INSTANCE)
     assert_that(self.bus.events(), not_(has_item(matches_regexp(expected_message))))
コード例 #53
0
 def test_lun_properties_perf_not_enabled(self):
     lun = self.unity.get_lun(_id='sv_2')
     assert_that(lun.property_names, is_not(has_item('read_iops')))
     disk = self.unity.get_disk(_id='dae_0_1_disk_0')
     assert_that(disk.property_names(), has_item('read_iops'))
コード例 #54
0
def run_completion(test_dir, rc_command, expected):
    """Run a completion test, and compare with EXPECTED output."""
    outputs = run_rc([c.format(test_dir) for c in rc_command]).split("\n")
    assert_that(len(outputs), equal_to(len(expected)))
    for output in outputs:
        assert_that(expected, has_item(output))
コード例 #55
0
def run_parse(test_dir, rc_command, expected):
    """Run a parse test, and compare with EXPECTED output."""
    output = run_rc(rc_command)
    assert_that(output, is_not(empty()))
    assert_that(output.split(" "), has_item(expected.format(test_dir + "/")))
コード例 #56
0
ファイル: diagnostics_test.py プロジェクト: xiaoyuluoke/ycmd
def Poll_Diagnostics_ChangeFileContents_test( app ):
  StartJavaCompleterServerInDirectory( app,
                                       PathToTestFile( DEFAULT_PROJECT_DIR ) )

  filepath = youcompleteme_Test
  old_contents = """package com.youcompleteme;

public class Test {
  public String test;
}"""

  messages_for_filepath = []

  def PollForMessagesInAnotherThread( filepath, contents ):
    try:
      for message in PollForMessages( app,
                                      { 'filepath': filepath,
                                        'contents': contents,
                                        'filetype': 'java' } ):
        if 'filepath' in message and message[ 'filepath' ] == filepath:
          messages_for_filepath.append( message )
    except PollForMessagesTimeoutException:
      pass

  StartThread( PollForMessagesInAnotherThread, filepath, old_contents )

  new_contents = """package com.youcompleteme;

public class Test {
  public String test;
  public String test;
}"""

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

  expiration = time.time() + 10
  while True:
    try:
      assert_that(
        messages_for_filepath,
        has_item( has_entries( {
          'filepath': filepath,
          'diagnostics': contains(
            has_entries( {
              'kind': 'ERROR',
              'text': 'Duplicate field Test.test',
              'location': LocationMatcher( youcompleteme_Test, 4, 17 ),
              'location_extent': RangeMatcher( youcompleteme_Test,
                                               ( 4, 17 ),
                                               ( 4, 21 ) ),
              'ranges': contains( RangeMatcher( youcompleteme_Test,
                                                ( 4, 17 ),
                                                ( 4, 21 ) ) ),
              'fixit_available': False
            } ),
            has_entries( {
              'kind': 'ERROR',
              'text': 'Duplicate field Test.test',
              'location': LocationMatcher( youcompleteme_Test, 5, 17 ),
              'location_extent': RangeMatcher( youcompleteme_Test,
                                               ( 5, 17 ),
                                               ( 5, 21 ) ),
              'ranges': contains( RangeMatcher( youcompleteme_Test,
                                                ( 5, 17 ),
                                                ( 5, 21 ) ) ),
              'fixit_available': False
            } )
          )
        } ) )
      )
      break
    except AssertionError:
      if time.time() > expiration:
        raise

      time.sleep( 0.25 )
コード例 #57
0
 def assert_function():
     expected_message = 'PUTVAL [^/]+/channels-global/counter-ended .* N:1'
     assert_that(events.accumulate(), has_item(matches_regexp(expected_message)))
コード例 #58
0
 def assert_function():
     expected_message = 'PUTVAL [^/]+/calls-{app}.{app_instance}/counter-end .* N:1'
     expected_message = expected_message.format(app=STASIS_APP,
                                                app_instance=STASIS_APP_INSTANCE)
     assert_that(events.accumulate(), has_item(matches_regexp(expected_message)))
コード例 #59
0
ファイル: test_artwork.py プロジェクト: Iconoclasteinc/tgit
def test_supports_png_format():
    assert_that(make_cover_art_selection().extensions, has_item("png"),
                "PNG extension supported.")
コード例 #60
0
def assert_does_not_have_any_dicts(haystack, needles):
    for needle in needles:
        h.assert_that(haystack, h.is_not(h.has_item(h.has_entries(needle))))