Ejemplo n.º 1
0
def test_get_file(sound):
    client = _new_sound_file_client()
    client.url.sounds(sound['name']).files('ivr').put(
        content='ivr_slin_fr_FR', query_string={'format': 'slin', 'language': 'fr_FR'}
    ).assert_updated()
    client.url.sounds(sound['name']).files('ivr').put(
        content='ivr_ogg_fr_FR', query_string={'format': 'ogg', 'language': 'fr_FR'}
    ).assert_updated()
    client.url.sounds(sound['name']).files('ivr').put(
        content='ivr_ogg_fr_CA', query_string={'format': 'ogg', 'language': 'fr_CA'}
    ).assert_updated()

    response = confd.sounds(sound['name']).files('ivr').get(format='ogg')
    assert_that(response.raw, any_of('ivr_ogg_fr_FR', 'ivr_ogg_fr_CA'))
    response.assert_content_disposition('ivr.ogg')

    response = (
        confd.sounds(sound['name']).files('ivr').get(format='ogg', language='fr_FR')
    )
    assert_that(response.raw, equal_to('ivr_ogg_fr_FR'))
    response.assert_content_disposition('ivr.ogg')

    response = confd.sounds(sound['name']).files('ivr').get(language='fr_FR')
    assert_that(response.raw, any_of('ivr_ogg_fr_FR', 'ivr_slin_fr_FR'))

    response = (
        confd.sounds(sound['name'])
        .files('ivr')
        .get(wazo_tenant=MAIN_TENANT, format='slin', language='fr_FR')
    )
    assert_that(response.raw, equal_to('ivr_slin_fr_FR'))
    response.assert_content_disposition('ivr.wav')
Ejemplo n.º 2
0
def test_get_file_system():
    asterisk_sound.create_directory('fr_FR')
    asterisk_sound.create_directory('fr_CA')
    asterisk_sound.create_file('fr_FR/asterisk-sound.ogg',
                               content='asterisk_sound_ogg_fr_FR')
    asterisk_sound.create_file('fr_FR/asterisk-sound.wav',
                               content='asterisk_sound_slin_fr_FR')
    asterisk_sound.create_file('fr_CA/asterisk-sound.ogg',
                               content='asterisk_sound_ogg_fr_CA')
    sound = {
        'id':
        'asterisk-sound',
        'formats': [
            {
                'language': 'fr_FR',
                'format': 'slin'
            },
            {
                'language': 'fr_FR',
                'format': 'ogg'
            },
            {
                'language': 'fr_CA',
                'format': 'ogg'
            },
        ],
        'text':
        'Asterisk Sound test',
    }
    ari.set_sound(sound)

    response = confd.sounds('system').files(sound['id']).get(format='ogg')
    assert_that(response.raw,
                any_of('asterisk_sound_ogg_fr_FR', 'asterisk_sound_ogg_fr_CA'))
    response.assert_content_disposition('asterisk-sound.ogg')

    response = (confd.sounds('system').files(sound['id']).get(
        format='ogg', language='fr_FR'))
    assert_that(response.raw, any_of('asterisk_sound_ogg_fr_FR'))
    response.assert_content_disposition('asterisk-sound.ogg')

    response = confd.sounds('system').files(sound['id']).get(language='fr_FR')
    assert_that(
        response.raw,
        any_of('asterisk_sound_ogg_fr_FR', 'asterisk_sound_slin_fr_FR'))

    response = (confd.sounds('system').files(sound['id']).get(
        format='slin', language='fr_FR'))
    assert_that(response.raw, any_of('asterisk_sound_slin_fr_FR'))
    response.assert_content_disposition('asterisk-sound.wav')

    ari.reset()
Ejemplo n.º 3
0
def DebugInfo_test(app):
    request_data = BuildRequest(filetype='rust')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entries({
                'name':
                'Rust',
                'servers':
                contains(
                    has_entries({
                        'name':
                        'Racerd',
                        '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))
                    })),
                'items':
                contains(
                    has_entries({
                        'key': 'Rust sources',
                        'value': any_of(none(), instance_of(str))
                    }))
            })))
Ejemplo n.º 4
0
def MiscHandlers_DebugInfo_ExtraConfLoaded_test(app):
    filepath = PathToTestFile('extra_conf', 'project', '.ycm_extra_conf.py')
    app.post_json('/load_extra_conf_file', {'filepath': filepath})

    request_data = BuildRequest(filepath=filepath)
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entries({
            'python':
            has_entries({
                'executable': instance_of(str),
                'version': instance_of(str),
            }),
            'clang':
            has_entries({
                'has_support': instance_of(bool),
                'version': any_of(None, instance_of(str))
            }),
            'extra_conf':
            has_entries({
                'path': instance_of(str),
                'is_loaded': True
            }),
            'completer':
            None
        }))
Ejemplo n.º 5
0
    def test_that_empty_fields_are_not_valid(self):
        username, password, email_address = 'foobar', 'b3h01D', '*****@*****.**'
        valid_body = {
            'username': username,
            'password': password,
            'email_address': email_address,
        }

        for field in ['username', 'password', 'email_address']:
            body = dict(valid_body)
            body[field] = ''

            result = self.app.post(self.url, json=body)

            assert_that(result.status_code, equal_to(400), field)
            assert_that(
                result.json,
                has_entries(
                    'error_id',
                    'invalid-data',
                    'resource',
                    'users',
                    'details',
                    has_entries(
                        field, has_entries('constraint_id', any_of('length', 'type'))
                    ),
                ),
                field,
            )
Ejemplo n.º 6
0
 def test_given_id_when_get_cdr_by_id_csv_then_get_cdr_by_id_csv(self):
     result_raw = self.call_logd.cdr.get_by_id_csv(12)
     result = list(csv.DictReader(StringIO(result_raw)))[0]
     assert_that(
         result,
         has_entries(
             id='12',
             tenant_uuid=MASTER_TENANT,
             answered='True',
             start='2017-03-23T00:00:00+00:00',
             answer='2017-03-23T00:01:00+00:00',
             end='2017-03-23T00:02:27+00:00',
             destination_extension='3378',
             destination_name='dést,ination',
             destination_internal_extension='3245',
             destination_internal_context='internal',
             duration='87',
             requested_name='réques,ted',
             requested_extension='3958',
             requested_internal_extension='3490',
             requested_internal_context='internal',
             call_direction='internal',
             source_extension='7687',
             source_name='soùr.',
             source_internal_extension='5938',
             source_internal_context='internal',
             source_user_uuid=USER_1_UUID,
             tags=any_of('rh;Poudlard', 'Poudlard;rh'),
         ),
     )
Ejemplo n.º 7
0
def DebugInfo_TypeScriptCompleter_test(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))
                            }))
                    }))
            })))
Ejemplo n.º 8
0
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' ) } ) )
          ) )
        )
      } )
    }
  } )
Ejemplo n.º 9
0
def has_test_case(name, *matchers):
    return has_property(
        'test_cases',
        has_item(
            all_of(
                any_of(has_entry('fullName', ends_with(name)),
                       has_entry('name', starts_with(name))), *matchers)))
Ejemplo n.º 10
0
    def check_volume_status(self,
                            volume,
                            statuses,
                            transit_statuses=(),
                            timeout=0):
        """Check step volume status.

        Args:
            volume (object|str): cinder volume to check status or its id
            statuses (list): list of statuses to check
            transit_statuses (tuple): possible volume transitional statuses
            timeout (int): seconds to wait a result of check

        Raises:
            TimeoutExpired|AssertionError: if check failed after timeout
        """
        transit_matchers = [
            equal_to_ignoring_case(status) for status in transit_statuses
        ]

        if not hasattr(volume, 'id'):
            volume = self.get_volume_by_id(volume)

        def _check_volume_status():
            volume.get()
            return waiter.expect_that(volume.status,
                                      is_not(any_of(*transit_matchers)))

        waiter.wait(_check_volume_status, timeout_seconds=timeout)
        matchers = [equal_to_ignoring_case(status) for status in statuses]
        assert_that(volume.status, any_of(*matchers))
Ejemplo n.º 11
0
 def test_dict_to_filter_unity_resource(self):
     ret = UnityClient.dict_to_filter_string({
         'a': 1,
         'b': UnityLun(_id='lun_1')
     })
     assert_that(
         ret, any_of('a eq 1 and b eq "lun_1"', 'b eq "lun_1" and a eq 1'))
Ejemplo n.º 12
0
    def test_should_return_shortest_distances_and_predecessors_for_equally_weighted_graph_with_many_paths(
            self):

        dg = nx.DiGraph()
        dg.add_weighted_edges_from([(0, 1, 1), (0, 2, 1), (1, 3, 1),
                                    (2, 3, 1)])

        distances, predecessors = dijkstra(graph=graph.Graph(dg),
                                           source_node=0,
                                           distance_struct=self.struct)

        assert_that(distances, has_length(4))
        assert_that(distances, has_entries({0: 0, 1: 1, 2: 1, 3: 2}))

        assert_that(predecessors, has_length(3))
        assert_that(
            predecessors,
            any_of(has_entries({
                1: 0,
                2: 0,
                3: 2
            }), has_entries({
                1: 0,
                2: 0,
                3: 1
            })))
Ejemplo n.º 13
0
def test_select_by_testcase_id_test(ids, expected_tests, allured_testdir):
    """
    >>> import allure

    >>> @allure.id("1")
    ... def test_number_one():
    ...     pass

    >>> @allure.id("2")
    ... def test_number_two():
    ...     pass

    >>> @allure.id("3")
    ... @allure.id("3+")
    ... def test_number_three():
    ...     pass

    >>> def test_without_number():
    ...     pass
    """
    allured_testdir.parse_docstring_source()

    if ids:
        py_path = allured_testdir.testdir.makefile(".json", json.dumps(ids))
        os.environ["AS_TESTPLAN_PATH"] = py_path.strpath
    else:
        del os.environ["AS_TESTPLAN_PATH"]

    allured_testdir.run_with_allure()
    test_cases = [test_case["fullName"] for test_case in allured_testdir.allure_report.test_cases]
    assert_that(test_cases, only_contains(
        any_of(
            *[ends_with(name) for name in expected_tests]
        )
    ))
Ejemplo n.º 14
0
    def test_reverse_when_multi_result(self):
        result = self.reverse('1111', 'default', VALID_UUID)

        assert_that(
            result,
            any_of(self.alice_result, self.qwerty_result_1,
                   self.qwerty_result_2))
Ejemplo n.º 15
0
    def test_given_call_logs_when_list_cdr_in_csv_then_list_cdr_in_csv(self):
        result_raw = self.call_logd.cdr.list_csv()
        result = list(csv.DictReader(StringIO(result_raw)))

        assert_that(
            result,
            contains_inanyorder(
                has_entries(id='12',
                            answered='True',
                            start='2017-03-23T00:00:00+00:00',
                            answer='2017-03-23T00:01:00+00:00',
                            end='2017-03-23T00:02:27+00:00',
                            destination_extension='3378',
                            destination_name='dést,ination',
                            duration='87',
                            call_direction='internal',
                            source_extension='7687',
                            source_name='soùr.',
                            tags=any_of('rh;Poudlard', 'Poudlard;rh')),
                has_entries(id='34',
                            answered='False',
                            start='2017-03-23T11:11:11+00:00',
                            answer='',
                            end='2017-03-23T11:13:29+00:00',
                            destination_extension='8733',
                            destination_name='noitani,tsèd',
                            duration='',
                            call_direction='outbound',
                            source_extension='7867',
                            source_name='.rùos',
                            tags='')), 'CSV received: {}'.format(result_raw))
Ejemplo n.º 16
0
def is_feature(props: dict) -> BaseMatcher:
    """Return matcher for Feature with given feature & properties."""
    return has_entries({
        "type": "Feature",
        "geometry": any_of(None, is_multipoly()),
        "properties": has_entries(props),
    })
Ejemplo n.º 17
0
def has_failure(test_name, message=anything()):
    return has_property('{}test-cases',
                        has_property('test-case',
                                     has_item(
                                         has_properties({'name': equal_to(test_name),
                                                         'failure': any_of(
                                                             has_property('stack-trace', equal_to(message)),
                                                             has_property('message', equal_to(message)))}))))
Ejemplo n.º 18
0
def has_failure(test_name, message=anything()):
    return has_property('{}test-cases',
                        has_property('test-case',
                                     has_item(
                                         has_properties({'name': equal_to(test_name),
                                                         'failure': any_of(
                                                             has_property('stack-trace', equal_to(message)),
                                                             has_property('message', equal_to(message)))}))))
Ejemplo n.º 19
0
def has_only_n_test_cases(name, num, *matchers):
    return has_property(
        'test_cases',
        ContainsExactly(
            num,
            all_of(
                any_of(has_entry('fullName', ends_with(name)),
                       has_entry('name', ends_with(name))), *matchers)))
Ejemplo n.º 20
0
 def matcher(self):
     """Return matcher."""
     matcher = super().matcher
     if self.optional:
         matcher = any_of(none(), matcher)
     else:
         matcher = all_of(not_none(), matcher)
     return has_entries(data=matcher)
Ejemplo n.º 21
0
        def _check_snapshot_status():

            if hasattr(snapshot, 'id'):
                snapshot_id = snapshot.id
            else:
                snapshot_id = snapshot
            status = self.get_snapshot_by_id(snapshot_id).status
            return waiter.expect_that(status, any_of(*matchers))
Ejemplo n.º 22
0
 def test_response(self, order_with_item, json, response):
     # I use the direct status_code check because the DRF test is just an
     # abstraction for checking what the REST Framework returns. If I stop
     # using the tool, there will be less rewriting left for me.
     # For pytest_drf, we can use the Returns200 mixin to test the response code.
     assert response.status_code == HTTPStatus.OK
     assert json["count"] == order_with_item.events.count() > 0
     assert_that(
         json["results"],
         only_contains(
             has_entries({
                 "id": instance_of(int),
                 "event_type": instance_of(str),
                 "subtype": any_of(instance_of(str), none()),
                 "user": none(),
                 "difference": any_of(instance_of(str), none()),
             })))
Ejemplo n.º 23
0
    def test_should_execute_work_if_the_solution_list_contains_two_non_dominated_solutions(self):
        solution1 = Solution(2, 2)
        solution1.variables = [1.0, 2.0]
        solution2 = Solution(2, 2)
        solution2.variables = [0.0, 3.0]

        solution_list = [solution1, solution2]

        assert_that(any_of(solution1, solution2), self.selection.execute(solution_list))
Ejemplo n.º 24
0
    def evaluate(self):
        """ Converts the current expression into a single matcher, applying
            coordination operators to operands according to their binding rules
        """

        # Apply Shunting Yard algorithm to convert the infix expression
        # into Reverse Polish Notation. Since we have a very limited
        # set of operators and binding rules, the implementation becomes
        # really simple. The expression is formed of hamcrest matcher instances
        # and operators identifiers (ints).
        ops = []
        rpn = []
        for token in self.expr:
            if isinstance(token, int):
                while len(ops) and token <= ops[-1]:
                    rpn.append(ops.pop())
                ops.append(token)
            else:
                rpn.append(token)

        # Append the remaining operators
        while len(ops):
            rpn.append(ops.pop())

        # Walk the RPN expression to create AllOf/AnyOf matchers
        stack = []
        for token in rpn:
            if isinstance(token, int):
                # Handle the NOT case in a special way since it's unary
                if token == OPERATOR.NOT:
                    stack[-1] = IsNot(stack[-1])
                    continue

                # Our operators always need two operands
                if len(stack) < 2:
                    raise RuntimeError('Unable to build a valid expression. Not enough operands available.')

                # Check what kind of matcher we need to create
                if token == OPERATOR.OR:
                    matcher = hc.any_of(*stack[-2:])
                else:  # AND, BUT
                    matcher = hc.all_of(*stack[-2:])

                stack[-2:] = [matcher]
            else:
                stack.append(token)

        if len(stack) != 1:
            raise RuntimeError('Unable to build a valid expression. The RPN stack should have just one item.')

        matcher = stack.pop()

        # If a description has been given include it in the matcher
        if self.description:
            matcher = hc.described_as(self.description, matcher)

        return matcher
Ejemplo n.º 25
0
def test_removes_contributor_from_chain_of_title():
    chain_of_title = make_chain_of_title(
        authors_composers=[joel_miller(), john_roney(), contributor("Yoko Ono"), contributor("John Lennon")],
        publishers=[effendi_records(), contributor("Effendi Records")])

    chain_of_title.update(lyricists=["Joel Miller"], composers=["John Lennon"], publishers=["Effendi Records"])

    assert_that(chain_of_title, not_(any_of(has_key("John Roney"), has_key("Yoko Ono"), has_key("Universals"))),
                "The chain of title")
Ejemplo n.º 26
0
    def evaluate(self):
        """ Converts the current expression into a single matcher, applying
            coordination operators to operands according to their binding rules
        """

        # Apply Shunting Yard algorithm to convert the infix expression
        # into Reverse Polish Notation. Since we have a very limited
        # set of operators and binding rules, the implementation becomes
        # really simple. The expression is formed of hamcrest matcher instances
        # and operators identifiers (ints).
        ops = []
        rpn = []
        for token in self.expr:
            if isinstance(token, int):
                while len(ops) and token <= ops[-1]:
                    rpn.append(ops.pop())
                ops.append(token)
            else:
                rpn.append(token)

        # Append the remaining operators
        while len(ops):
            rpn.append(ops.pop())

        # Walk the RPN expression to create AllOf/AnyOf matchers
        stack = []
        for token in rpn:
            if isinstance(token, int):
                # Handle the NOT case in a special way since it's unary
                if token == OPERATOR.NOT:
                    stack[-1] = IsNot(stack[-1])
                    continue

                # Our operators always need two operands
                if len(stack) < 2:
                    raise RuntimeError('Unable to build a valid expression. Not enough operands available.')

                # Check what kind of matcher we need to create
                if token == OPERATOR.OR:
                    matcher = hc.any_of(*stack[-2:])
                else:  # AND, BUT
                    matcher = hc.all_of(*stack[-2:])

                stack[-2:] = [matcher]
            else:
                stack.append(token)

        if len(stack) != 1:
            raise RuntimeError('Unable to build a valid expression. The RPN stack should have just one item.')

        matcher = stack.pop()

        # If a description has been given include it in the matcher
        if self.description:
            matcher = hc.described_as(self.description, matcher)

        return matcher
Ejemplo n.º 27
0
 def test_hamcrest(self):
     # 通过:校验hamcrest.has_item函数的参数是否在前面assert_that的第一个参数中
     # assert_that(['a','v','b'],hamcrest.has_item('a'))
     # 通过:校验hamcrest.has_items函数的参数是否全部都在前面assert_that的第一个参数中
     # assert_that(['a','v','b'],hamcrest.has_items('a','v'))
     # 不通过
     # assert_that(['a','b','c'], hamcrest.has_items('a','x'))
     # 通过
     assert_that(['a', 'v'], any_of(['a', 'v'], 'b'))
Ejemplo n.º 28
0
    def test_it_should_search_stations_by_name(self):
        query = 'callEaVapiés'
        stations = list(self.stations.by_search(query))

        assert_that(stations, only_contains(any_of(
            has_property('nombre', contains_string('Lavapies')),
            has_property('address', contains_string('Lavapies')),
        )))
        assert_that(stations, has_length(greater_than(0)))
Ejemplo n.º 29
0
    def matcher(self) -> BaseMatcher:
        """Return matcher."""
        matcher = self.resource_matcher
        if self.many:
            matcher = all_of(instance_of(list), only_contains(matcher))
            if self.optional:
                matcher = any_of(empty(), matcher)
        elif self.optional:
            matcher = any_of(none(), matcher)
        else:
            matcher = all_of(not_none(), matcher)
        include_matcher = any_of(
            not_(has_key("included")),
            has_entries(
                included=any_of(empty(), only_contains(
                    *self.included_matchers))),
        )

        return all_of(has_entries(data=matcher), include_matcher)
Ejemplo n.º 30
0
    def test_find_user_two_users_same_name(self):
        firstname = 'Lord'
        lastname = 'Sanderson'

        user1 = self.add_user(firstname=firstname, lastname=lastname)
        user2 = self.add_user(firstname=firstname, lastname=lastname)

        result = user_dao.find_user(firstname, lastname)

        assert_that(result, has_property('id', any_of(user1.id, user2.id)))
Ejemplo n.º 31
0
    def test_request_current_sessions_user_unauthorized(self):
        github_session = GithubSession()
        _, headers, _ = github_session.request_api('/user')

        assert_that(headers, not_none())
        assert_that(headers["Status"], is_(any_of(UNAUTHORIZED, FORBIDDEN)))
        if headers["Status"] == UNAUTHORIZED:
            assert_that(int(headers[RATE_REMAINING]), is_(greater_than(0)))
        if headers["Status"] == FORBIDDEN:
            assert_that(int(headers[RATE_REMAINING]), is_(0))
Ejemplo n.º 32
0
    def test_request_github_api_root(self):
        github_session = GithubSession()
        _, headers, _ = github_session.request_api('/')

        assert_that(headers, not_none())
        assert_that(headers["Status"], is_(any_of(OK, FORBIDDEN)))
        if headers["Status"] == OK:
            assert_that(int(headers[RATE_REMAINING]), is_(greater_than(0)))
        if headers["Status"] == FORBIDDEN:
            assert_that(int(headers[RATE_REMAINING]), is_(0))
Ejemplo n.º 33
0
 def assert_input_has_correct_label_and_value(self, element_id, label, response, value):
     assert_that(response.normal_body, contains_string(label))
     workbench_input = re.search('<input[^>]* id="{}"[^>]*>'.format(element_id), response.normal_body)
     assert_that(workbench_input, not_none(), "input file exists with id of {}".format(element_id))
     if value is None or value is "":
         assert_that(workbench_input.group(0), any_of(
             contains_string('value=""'.format(value)),
             is_not(contains_string('value="'))
             ))
     else:
         assert_that(workbench_input.group(0), contains_string('value="{}"'.format(value)))
Ejemplo n.º 34
0
Archivo: test_kv.py Proyecto: keis/omx
def test_dump_dictionary_target():
    ns = Namespace('')

    @ns.template('entry', ('@key', '@value'))
    def entry(key, value):
        return (key, int(value))

    entry.serialiser(lambda values, obj: values(*obj))

    @ns.template('object', ((AsDict, 'entry'),))
    def obj(entries):
        return entries

    omx = OMX([ns], [['testcase', 'object']])
    data = etree.tostring(omx.dump({'foo': 10, 'bar': 7}))
    if not isinstance(data, str):
        data = data.decode('utf-8')
    assert_that(data, any_of(contains_string('<entry key="bar" value="7"/>'),
                             contains_string('<entry value="7" key="bar"/>')))
    assert_that(data, any_of(contains_string('<entry key="foo" value="10"/>'),
                             contains_string('<entry value="10" key="foo"/>')))
Ejemplo n.º 35
0
def has_only_n_test_cases(name, num, *matchers):
    return has_property('test_cases',
                        ContainsExactly(num,
                                        all_of(
                                            any_of(
                                                has_entry('fullName', ends_with(name)),
                                                has_entry('name', ends_with(name))
                                            ),
                                            *matchers
                                        )
                                        )
                        )
Ejemplo n.º 36
0
def has_test_case(name, *matchers):
    return has_property('test_cases',
                        has_item(
                            all_of(
                                any_of(
                                    has_entry('fullName', ends_with(name)),
                                    has_entry('name', starts_with(name))
                                ),
                                *matchers
                            )
                        )
                        )
Ejemplo n.º 37
0
    def test_it_should_search_stations_by_name(self):
        query = 'callEaVapiés'
        stations = list(self.stations.by_search(query))

        assert_that(
            stations,
            only_contains(
                any_of(
                    has_property('nombre', contains_string('Lavapies')),
                    has_property('address', contains_string('Lavapies')),
                )))
        assert_that(stations, has_length(greater_than(0)))
Ejemplo n.º 38
0
    def test_extract_specific_error_id_from_fields_when_field_with_multiple_errors(
            self):
        fields = {
            'name': ['Missing data for required field'
                     'Not a valid choice']
        }
        error_ids = ConfdErrorExtractor.extract_specific_error_id_from_fields(
            fields)

        expected1 = {'name': 'required'}
        expected2 = {'name': 'invalid-choice'}
        assert_that(error_ids, any_of(expected1, expected2))
Ejemplo n.º 39
0
def test_select_by_severity_level(allured_testdir, severities, expected_tests):
    allured_testdir.parse_docstring_path()

    allured_testdir.run_with_allure("--allure-severities",
                                    ",".join(severities))
    test_cases = [
        test_case["fullName"]
        for test_case in allured_testdir.allure_report.test_cases
    ]

    assert_that(
        test_cases,
        only_contains(any_of(*[ends_with(name) for name in expected_tests])))
def test_select_by_bdd_label(allured_testdir, options, expected_tests):
    allured_testdir.parse_docstring_path()

    params = []

    for key in options.keys():
        params.append("--allure-{key}".format(key=key))
        params.append(",".join(options[key]))

    allured_testdir.run_with_allure(*params)
    test_cases = [test_case["fullName"] for test_case in allured_testdir.allure_report.test_cases]

    assert_that(test_cases, only_contains(
        any_of(
            *[ends_with(name) for name in expected_tests]
        )
    ))
Ejemplo n.º 41
0
def MiscHandlers_DebugInfo_NoExtraConfFound_test( app ):
  request_data = BuildRequest()
  assert_that(
    app.post_json( '/debug_info', request_data ).json,
    has_entries( {
      'python': has_entries( {
        'executable': instance_of( str ),
        'version': instance_of( str ),
      } ),
      'clang': has_entries( {
        'has_support': instance_of( bool ),
        'version': any_of( None, instance_of( str ) )
      } ),
      'extra_conf': has_entries( {
        'path': None,
        'is_loaded': False
      } ),
      'completer': None
    } )
  )
Ejemplo n.º 42
0
def DebugInfo_test( app ):
  request_data = BuildRequest( filetype = 'typescript' )
  assert_that(
    app.post_json( '/debug_info', request_data ).json,
    has_entry( 'completer', has_entries( {
      'name': 'TypeScript',
      'servers': contains( has_entries( {
        'name': 'TSServer',
        'is_running': True,
        'executable': instance_of( str ),
        'pid': instance_of( int ),
        'address': None,
        'port': None,
        'logfiles': contains( instance_of( str ) ),
        'extras': contains( has_entries( {
          'key': 'version',
          'value': any_of( None, instance_of( str ) )
        } ) )
      } ) )
    } ) )
  )
Ejemplo n.º 43
0
def MiscHandlers_DebugInfo_ExtraConfFoundButNotLoaded_test( app ):
  filepath = PathToTestFile( 'extra_conf', 'project', '.ycm_extra_conf.py' )
  request_data = BuildRequest( filepath = filepath )
  assert_that(
    app.post_json( '/debug_info', request_data ).json,
    has_entries( {
      'python': has_entries( {
        'executable': instance_of( str ),
        'version': instance_of( str ),
      } ),
      'clang': has_entries( {
        'has_support': instance_of( bool ),
        'version': any_of( None, instance_of( str ) )
      } ),
      'extra_conf': has_entries( {
        'path': instance_of( str ),
        'is_loaded': False
      } ),
      'completer': None
    } )
  )
Ejemplo n.º 44
0
def DebugInfo_test( app ):
  request_data = BuildRequest( filetype = 'rust' )
  assert_that(
    app.post_json( '/debug_info', request_data ).json,
    has_entry( 'completer', has_entries( {
      'name': 'Rust',
      'servers': contains( has_entries( {
        'name': 'Racerd',
        '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 ) )
      } ) ),
      'items': contains( has_entries( {
        'key': 'Rust sources',
        'value': any_of( none(), instance_of( str ) )
      } ) )
    } ) )
  )
Ejemplo n.º 45
0
def test_ends_like_composite():
    assert_that('hello', any_of(ends_like('bella'), ends_like('chello')))
Ejemplo n.º 46
0
 def test_dict_to_filter_string_normal(self):
     ret = UnityClient.dict_to_filter_string({'a': 1, 'b': 'c'})
     assert_that(ret, any_of('a eq 1 and b eq "c"', 'b eq "c" and a eq 1'))
Ejemplo n.º 47
0
 def __init__(self, *element_matchers):
     delegates = [hc.has_item(e) for e in element_matchers]
     self.matcher_all = hc.all_of(*delegates)
     self.matcher_any = hc.any_of(*delegates)
     self.matcher_order = hc.contains(*element_matchers)
     self.order_seq = None
Ejemplo n.º 48
0
    def test_site_sync(self):

        for site in _SITES:
            assert_that(_find_site_components((site.__name__,)),
                         is_(not_none()))

        with mock_db_trans() as conn:
            for site in _SITES:
                assert_that(_find_site_components((site.__name__,)),
                             is_(not_none()))


            ds = conn.root()['nti.dataserver']
            assert ds is not None
            sites = ds['++etc++hostsites']
            for site in _SITES:
                assert_that(sites, does_not(has_key(site.__name__)))

            synchronize_host_policies()
            synchronize_host_policies()

            assert_that(self._events, has_length(len(_SITES)))
            # These were put in in order
            # assert_that( self._events[0][0].__parent__,
            #            has_property('__name__', EVAL.__name__))

            # XXX These two lines are cover only.
            get_host_site(DEMO.__name__)
            get_host_site('DNE', True)
            assert_that(calling(get_host_site).with_args('dne'),
                        raises(LookupError))

        with mock_db_trans() as conn:
            for site in _SITES:
                assert_that(_find_site_components((site.__name__,)),
                             is_(not_none()))

            ds = conn.root()['nti.dataserver']

            assert ds is not None
            sites = ds['++etc++hostsites']

            assert_that(sites, has_key(EVAL.__name__))
            assert_that(sites[EVAL.__name__], verifiably_provides(ISite))

            # If we ask the demoalpha persistent site for an ITestSyteSync,
            # it will find us, because it goes to the demo global site
            assert_that(sites[DEMOALPHA.__name__].getSiteManager().queryUtility(ITestSiteSync),
                         is_(ASync))

            # However, if we put something in the demo *persistent* site, it
            # will find that
            sites[DEMO.__name__].getSiteManager().registerUtility(OtherSync())
            assert_that(sites[DEMOALPHA.__name__].getSiteManager().queryUtility(ITestSiteSync),
                        is_(OtherSync))

            # Verify the resolution order too
            def _name(x):
                if x.__name__ == '++etc++site':
                    return 'P' + str(x.__parent__.__name__)
                return x.__name__
            assert_that([_name(x) for x in ro.ro(sites[DEMOALPHA.__name__].getSiteManager())],
                        is_([u'Pdemo-alpha.nextthoughttest.com',
                             u'demo-alpha.nextthoughttest.com',
                             u'Pdemo.nextthoughttest.com',
                             u'demo.nextthoughttest.com',
                             u'Peval.nextthoughttest.com',
                             u'eval.nextthoughttest.com',
                             u'Pdataserver2',
                             u'PNone',
                             'base']))

            # including if we ask to travers from top to bottom
            names = list()
            def func():
                names.append(_name(component.getSiteManager()))

            run_job_in_all_host_sites(func)
            # Note that PDemo and Peval-alpha are arbitrary, they both
            # descend from eval;
            # TODO: why aren't we maintaining alphabetical order?
            # we should be, but sometimes we don't
            assert_that(names, is_(any_of(
                [u'Peval.nextthoughttest.com',
                 u'Pdemo.nextthoughttest.com',
                 u'Peval-alpha.nextthoughttest.com',
                 u'Pdemo-alpha.nextthoughttest.com'],
                [u'Peval.nextthoughttest.com',
                 u'Peval-alpha.nextthoughttest.com',
                 u'Pdemo.nextthoughttest.com',
                 u'Pdemo-alpha.nextthoughttest.com'])))

            # And that it's what we get back if we ask for it
            assert_that(get_site_for_site_names((DEMOALPHA.__name__,)),
                         is_(same_instance(sites[DEMOALPHA.__name__])))

        # No new sites created
        assert_that(self._events, has_length(len(_SITES)))
Ejemplo n.º 49
0
 def test_dict_to_filter_list(self):
     ret = UnityClient.dict_to_filter_string({'a': [2, 4]})
     assert_that(ret, any_of('a eq 2 or a eq 4', 'a eq 4 or a eq 2'))
     ret = UnityClient.dict_to_filter_string({'a': ["m", "n"]})
     assert_that(ret, any_of('a eq "m" or a eq "n"',
                             'a eq "n" or a eq "m"'))
Ejemplo n.º 50
0
 def test_dict_to_filter_string_enum_list(self):
     levels = [ServiceLevelEnum.SILVER, ServiceLevelEnum.PLATINUM]
     ret = UnityClient.dict_to_filter_string({'a': levels})
     assert_that(ret, any_of('a eq 2 or a eq 4', 'a eq 4 or a eq 2'))
Ejemplo n.º 51
0
 def _matches(self, item):
     return has_property('test_cases',
                         only_contains(any_of(*self.matchers))
                         ).matches(item)
Ejemplo n.º 52
0
def test_is_five_or_four():
    assert_that(4, any_of(is_four(), is_five()))
Ejemplo n.º 53
0
def _filter_expected_needles(haystack, needles):
    matcher = h.any_of(*_expected_needles(needles))
    return [v for v in haystack if matcher.matches(v)]
Ejemplo n.º 54
0
def _is_five_or_even(item):
    assert_that(item, any_of(is_five(), is_even()))