Python hypothesis 模块,given() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用hypothesis.given()

项目:dustbunny    作者:Teamworksapp    | 项目源码 | 文件源码
def _do(self, **parents):
        if self.dist is not None:
            k = self.dist(1)[0]
            if k == 0:
                k = 1
        else:
            k = self.n

        recs = []

        @settings(max_examples=k)
        def gen(**kwargs):
            rels = {}
            for rv in self.relative_values:
                rels.update({name: xform(**kwargs, **parents, **self.fixtures, **rels, **self.extras) for name, xform in rv.items()})
            recs.append(self.create(self.model, **kwargs, **parents, **self.fixtures, **rels))

        if self.strategy:    
            given(**self.strategy)(gen)()
        else:
            gen()

        self.db.session.commit()
        return recs
项目:telepresence    作者:datawire    | 项目源码 | 文件源码
def test_covering_cidr(ips):
    """
    covering_cidr() gets the minimal CIDR that covers given IPs.

    In particular, that means any subnets should *not* cover all given IPs.
    """
    cidr = telepresence.vpn.covering_cidr(ips)
    assert isinstance(cidr, str)
    cidr = ipaddress.IPv4Network(cidr)
    assert cidr.prefixlen <= 24
    # All IPs in given CIDR:
    ips = [ipaddress.IPv4Address(i) for i in ips]
    assert all([ip in cidr for ip in ips])
    # Subnets do not contain all IPs if we're not in minimum 24 bit CIDR:
    if cidr.prefixlen < 24:
        for subnet in cidr.subnets():
            assert not all([ip in subnet for ip in ips])
项目:mdk    作者:datawire    | 项目源码 | 文件源码
def test_log_result_too_low_level(self):
        """
        A LoggedMessageId matching the logged message is returned by logging APIs
        even when the given level is low enough that a message wasn't sent to
        the MCP.
        """
        mdk, tracer = create_mdk_with_faketracer()
        session = mdk.session()
        session.info("cat", "message")
        lmid = session.debug("cat", "another message")
        lmid2 = session.info("cat", "message")
        # Debug message wasn't set:
        self.assertEqual([d["level"] for d in tracer.messages],
                         ["INFO", "INFO"])
        # But we still got LoggedMessageId for debug message:
        self.assertEqual((lmid.causalLevel, lmid.traceId,
                          lmid2.causalLevel, lmid2.traceId),
                         ([2], session._context.traceId,
                          [3], session._context.traceId))
项目:Nashpy    作者:drvinceknight    | 项目源码 | 文件源码
def test_creation_of_particular_halfspaces(self):
        """Test that can create a given halfspace array representation"""
        A = np.array([[3, 3], [2, 5], [0, 6]])
        expected_halfspace = np.array([[ 3.,  3., -1.],
                                       [ 2.,  5., -1.],
                                       [ 0.,  6., -1.],
                                       [-1., -0.,  0.],
                                       [-0., -1.,  0.]])
        halfspace = build_halfspaces(A)
        self.assertTrue(np.array_equal(halfspace, expected_halfspace))

        B = np.array([[3, 2], [2, 6], [3, 1]])
        expected_halfspace = np.array([[ 3.,  2.,  3., -1.],
                                       [ 2.,  6.,  1., -1.],
                                       [-1., -0., -0.,  0.],
                                       [-0., -1., -0.,  0.],
                                       [-0., -0., -1.,  0.]])
        halfspace = build_halfspaces(B.transpose())
        self.assertTrue(np.array_equal(halfspace, expected_halfspace))
项目:hypothesis-regex    作者:maximkulkin    | 项目源码 | 文件源码
def assert_all_examples(strategy, predicate):
    '''
    Checks that there are no examples with given strategy
    that do not match predicate.

    :param strategy: Hypothesis strategy to check
    :param predicate: (callable) Predicate that takes string example and returns bool
    '''
    @h.settings(max_examples=1000, max_iterations=5000)
    @h.given(strategy)
    def assert_examples(s):
        assert predicate(s),'Found %r using strategy %s which does not match' % (
            s, strategy,
        )

    assert_examples()
项目:vws-python    作者:adamtheturtle    | 项目源码 | 文件源码
def assert_valid_credentials(access_key: str, secret_key: str) -> None:
    """
    Given credentials, assert that they can authenticate with a Vuforia
    database.

    Raises:
        AssertionError: The given credentials fail to authenticate with a
            Vuforia database.
    """
    credentials = VuforiaServerCredentials(
        database_name=uuid.uuid4().hex,
        access_key=access_key,
        secret_key=secret_key,
    )

    response = get_vws_target(
        vuforia_server_credentials=credentials,
        target_id=uuid.uuid4().hex,
    )

    # This shows that the response does not give an authentication
    # error which is what would happen if the keys were incorrect.
    assert response.status_code == codes.NOT_FOUND
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def test_non_annotated_function_call_bad_arguments():
    """ User tries to call a non-annotated function on arguments of the wrong type.
    """
    program = f'def add_num(num1, num2):\n' \
              f'    return num1 + num2\n' \
              f'\n' \
              f'add_num("bob", 1.0)\n'
    try:
        module, inferer = cs._parse_text(program)
    except:
        raise SkipTest()
    call_node = next(module.nodes_of_class(astroid.Call))
    expected_msg = f'In the Call node in line 4, there was an error in calling the function "add_num":\n' \
                   f'in parameter (1), the function was expecting an object of inferred type ' \
                   f'int but was given an object of type str.\n' \
                   f'in parameter (1), the function was expecting an object of inferred type ' \
                   f'int but was given an object of type float.\n'
                   # TODO: should we use the term inferred?
    assert call_node.type_constraints.type.msg == expected_msg
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def test_user_defined_annotated_call_wrong_arguments_type():
    """ User tries to call an annotated user-defined function on the wrongly-typed arguments.
    """
    program = f'def add_3(num1: int, num2: int, num3: int) -> int:\n' \
              f'    return num1 + num2 + num3\n' \
              f'\n' \
              f'add_3(1, "bob", 1.0)\n'
    try:
        module, inferer = cs._parse_text(program)
    except:
        raise SkipTest()
    call_node = list(module.nodes_of_class(astroid.Call))[0]
    expected_msg = f'In the Call node in line 4, there was an error in calling the annotated function "add_3":\n' \
                   f'in parameter (2), the annotated type is int but was given an object of type str.\n' \
                   f'in parameter (3), the annotated type is int but was given an object of type float.\n'
    assert call_node.type_constraints.type.msg == expected_msg
项目:djinn    作者:ordjinnization    | 项目源码 | 文件源码
def gen_data_from_z(z):
    """
    Given the z axis values (2d list of failures) generate data that would have
    given us this z value.
    :param z: a list of lists of failures.
    :return: the data that would have given this z value, the z value, the x value
        (stages) and the y value (projects).
    """
    data = []
    projects_len = len(z)
    stages_len = 0 if projects_len == 0 else len(z[0])
    projects = [uuid4() for _ in xrange(projects_len)]
    stages = [uuid4() for _ in xrange(stages_len)]
    for pidx, project in enumerate(projects):
        for sidx, stage in enumerate(stages):
            failures = z[pidx][sidx]
            repo = strings.example()
            for _ in xrange(failures):
                data.append(MockPipelineRun(stage_failed=stage, project=project, repository=repo))
    return data, z, stages, projects
项目:dustbunny    作者:Teamworksapp    | 项目源码 | 文件源码
def with_fixed_values_for(self, **fixtures):
        """
        Use fixed values for the given set of attributes.

        :param fixtures (attr_name -> attr_value): A mapping of attribute names to static values. These will be used 
            directly to assign to attribute values on the database record.

        :return: Generate 
        """
        ret = copy.copy(self)
        ret.fixtures = copy.copy(self.fixtures)
        ret.fixtures.update(fixtures)
        return ret
项目:dustbunny    作者:Teamworksapp    | 项目源码 | 文件源码
def with_relative_values_for(self, **kwargs):
        """
        Use relative values for the given set of attributes.

        :param kwargs (attr_name -> function): A mapping of attibute names to functions of a single dictionary argument
            containing all values already set for any given record so far.  Fixed, random, and "extra" values. The 
            function should return the value you wnat to use for the attribute for that record.

        :return: Generate
        """
        ret = copy.copy(self)
        ret.relative_values = copy.copy(ret.relative_values)
        ret.relative_values.append(kwargs)
        return ret
项目:mdk    作者:datawire    | 项目源码 | 文件源码
def assertPolicyState(self, policies, successes, failures):
        """
        Assert that the given FailurePolicy instances has the given number of
        success() and failure() calls.
        """
        for policy in policies:
            self.assertEqual((policy.successes, policy.failures),
                             (successes, failures))
项目:mdk    作者:datawire    | 项目源码 | 文件源码
def assertSessionHas(self, session, trace_id, clock_level, **properties):
        """
        Assert the given SessionImpl has the given trace, clock and properties.
        """
        self.assertEqual(session._context.traceId, trace_id)
        self.assertEqual(session._context.clock.clocks, clock_level)
        self.assertEqual(session._context.properties, properties)
项目:mdk    作者:datawire    | 项目源码 | 文件源码
def assertEnvironmentEquals(test, environment, name, fallback):
    """
    Assert the given environment has the given name and fallback name.
    """
    test.assertEqual(environment.name, name)
    test.assertEqual(environment.fallbackName, fallback)
项目:mdk    作者:datawire    | 项目源码 | 文件源码
def assert_log_level_enforced(self, minimum_level):
        """Only log messages at or above the given level are sent."""
        mdk, tracer = create_mdk_with_faketracer()
        session = mdk.session()
        messages = ["a", "b", "c", "d", "e"]

        # Set logging level of the session:
        session.trace(minimum_level)
        # Log messages at all levels:
        for (l, m) in zip(self.LEVELS, messages):
            getattr(session, l.lower())("category", m)
        # Only messages at or above current level should actually be logged:
        result = [d["level"] for d in tracer.messages]
        expected_levels = self.LEVELS[self.LEVELS.index(minimum_level):]
        self.assertEqual(result, expected_levels)
项目:swagger-fuzzer    作者:Lothiraldan    | 项目源码 | 文件源码
def do(settings):
    PARSED_HOST = urlparse(settings.spec_url)

    swagger_spec = requests.get(settings.spec_url)
    swagger_spec.raise_for_status()
    SPEC = swagger_spec.json()

    validator = get_validator(SPEC, settings.spec_url)
    validator.validate_spec(swagger_spec.json(), settings.spec_url)

    SPEC_HOST = urlunparse(list(PARSED_HOST)[:2] + [SPEC['basePath']] + ['', '', ''])

    s = requests.Session()

    @given(data())
    @hsettings(max_examples=settings.iterations)
    def swagger_fuzzer(data):
        request = get_request(data, SPEC, SPEC_HOST)
        note("Curl command: {}".format(to_curl_command(request)))

        result = s.send(request)

        for validator in VALIDATORS:
            validator(SPEC, request, result, settings)

    # Call the function
    swagger_fuzzer()
项目:hypothesis-regex    作者:maximkulkin    | 项目源码 | 文件源码
def assert_can_generate(pattern):
    '''
    Checks that regex strategy for given pattern generates examples
    that match that regex pattern
    '''
    compiled_pattern = re.compile(pattern)
    strategy = regex(pattern)

    assert_all_examples(strategy, compiled_pattern.match)
项目:vws-python    作者:adamtheturtle    | 项目源码 | 文件源码
def test_decorator_real_http(self) -> None:
        """
        When the `real_http` parameter given to the decorator is set to `True`,
        requests made to unmocked addresses are not stopped.
        """
        with pytest.raises(requests.exceptions.ConnectionError):
            request_unmocked_address()
项目:vws-python    作者:adamtheturtle    | 项目源码 | 文件源码
def test_real_http(self) -> None:
        """
        When the `real_http` parameter given to the context manager is set to
        `True`, requests made to unmocked addresses are not stopped.
        """
        with MockVWS(real_http=True):
            with pytest.raises(requests.exceptions.ConnectionError):
                request_unmocked_address()
项目:TopChef    作者:TopChef    | 项目源码 | 文件源码
def setUp(self) -> None:
        """
        Overload the getter for SQLAlchemy sessions for a given database
        model with a mock. This method should work similarly to
        ``Session.object_session``, which returns the SQLAlchemy ORM session
        to which the model class is bound
        """
        TestService.setUp(self)
        self.session_getter = mock.MagicMock(spec=Session.object_session)
        self.service = Service(
            self.database_service, session_getter_for_model=self.session_getter
        )
项目:TopChef    作者:TopChef    | 项目源码 | 文件源码
def test_name_sqlite(self) -> None:
        """
        Tests that if the name ``sqlite`` is given to the database, then a
        CHAR descriptor comes back out with 32 characters
        """
        uuid_instance = DB_UUID()
        dialect_impl = uuid_instance.load_dialect_impl(self.sqlite_dialect)
        self.assertIsInstance(
            dialect_impl, self.sqlite_dialect.type_descriptor(
                CHAR(32)
            ).__class__
        )
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def _parse_to_function(function_name, args_list, return_statement):
    """Helper to parse given data into function definition."""
    return f'def {function_name}({", ".join(args_list)}):' \
           f'    return {return_statement}'
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def _parse_to_function_no_return(function_name, args_list, function_body):
    """Helper to parse given data into function definition."""
    return f'def {function_name}({", ".join(args_list)}):\n' \
           f'    {function_body}'
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def test_user_defined_annotated_call_wrong_arguments_number():
    """ User tries to call an annotated function on the wrong number of arguments.
    """
    program = f'def add_3(num1: int, num2: int, num3: int) -> int:\n' \
              f'    return num1 + num2 + num3\n' \
              f'\n' \
              f'add_3()\n'
    try:
        module, inferer = cs._parse_text(program)
    except:
        raise SkipTest()
    call_node = list(module.nodes_of_class(astroid.Call))[0]
    expected_msg = f'In the Call node in line 4, there was an error in calling the function "add_3":\n' \
                   f'the function was expecting 3 arguments, but was given 0.'
    assert call_node.type_constraints.type.msg == expected_msg
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def _parse_to_function(function_name, args_list, return_statement):
    """Helper to parse given data into function definition."""
    return f'def {function_name}({", ".join(args_list)}):' \
           f'    return {return_statement}'
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def _parse_to_function_no_return(function_name, args_list, function_body):
    """Helper to parse given data into function definition."""
    return f'def {function_name}({", ".join(args_list)}):\n' \
           f'    {function_body}'
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def test_inference_args_simple_return(function_name, arguments):
    """Test whether visitor was able to infer type of argument given function called on it in function body."""
    assume(function_name not in arguments)
    for argument in arguments:
        program = _parse_to_function_no_return(function_name, arguments, ('return ' + argument + " + " + repr('bob')))
        module, inferer = cs._parse_text(program)
        # get the functionDef node - there is only one in this test case.
        function_def_node = next(module.nodes_of_class(astroid.FunctionDef))
        expected_arg_type_vars = [function_def_node.type_environment.lookup_in_env(argument) for argument in arguments]
        expected_arg_types = [inferer.type_constraints.lookup_concrete(type_var) for type_var in expected_arg_type_vars]
        function_type_var = module.type_environment.lookup_in_env(function_name)
        function_type = inferer.type_constraints.lookup_concrete(function_type_var)
        actual_arg_types, actual_return_type = inferer.type_constraints.types_in_callable(function_type)
        assert expected_arg_types == actual_arg_types
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def test_function_def_args_simple_return(function_name, arguments):
    """Test whether visitor was able to infer type of function given function called on it's arguments."""
    assume(function_name not in arguments)
    for argument in arguments:
        program = _parse_to_function_no_return(function_name, arguments, ('return ' + argument + " + " + repr('bob')))
        module, inferer = cs._parse_text(program)
        function_def_node = next(module.nodes_of_class(astroid.FunctionDef))
        expected_arg_type_vars = [function_def_node.type_environment.lookup_in_env(argument) for argument in arguments]
        expected_arg_types = [inferer.type_constraints.lookup_concrete(type_var) for type_var in expected_arg_type_vars]
        function_type_var = module.type_environment.lookup_in_env(function_name)
        function_type = inferer.type_constraints.lookup_concrete(function_type_var)
        actual_arg_types, actual_return_type = inferer.type_constraints.types_in_callable(function_type)
        return_type_var = function_def_node.type_environment.lookup_in_env(argument)
        expected_return_type = inferer.type_constraints.lookup_concrete(return_type_var)
        assert Callable[actual_arg_types, actual_return_type] == Callable[expected_arg_types, expected_return_type]
项目:pyta    作者:pyta-uoft    | 项目源码 | 文件源码
def test_subscript_homogeneous_list_slice(node):
    """Test visitor of Subscript node representing slicing of homogeneous list."""
    module, _ = cs._parse_text(node)
    for subscript_node in module.nodes_of_class(astroid.Subscript):
        list_node = subscript_node.value
        assert subscript_node.type_constraints.type == List[list_node.elts[0].type_constraints.type]


# TODO: this test currently fails
# @given(cs.simple_homogeneous_dict_node(min_size=1))
# def test_inference_dict_subscript(node):
#     """Note that this test only takes in a dictionary because the subscript index
#     must be the same type as the dictionary's keys in order to type check.
#     """
#     for key, _ in node.items:
#         new_node = astroid.Subscript()
#         new_node.postinit(node, key)
#         module, _ = cs._parse_text(new_node)
#         for subscript_node in module.nodes_of_class(astroid.Subscript):
#             dict_node = subscript_node.value
#             assert subscript_node.type_constraints.type == list(dict_node.items)[0][1].type_constraints.type


# TODO: this test needs to be converted, but will also fail
# @given(cs.random_list(min_size=2), cs.random_slice_indices())
# def test_subscript_heterogeneous_list_slice(input_list, slice):
#     """Test visitor of Subscript node representing slicing of heterogeneous list."""
#     assume(not isinstance(input_list[0], type(input_list[1])))
#     input_slice = ':'.join([str(index) if index else '' for index in slice])
#     program = f'{input_list}[{input_slice}]'
#     module, _ = cs._parse_text(program)
#     subscript_node = list(module.nodes_of_class(astroid.Subscript))[0]
#     assert subscript_node.type_constraints.type == List[Any]
项目:matchpy    作者:HPAC    | 项目源码 | 文件源码
def test_completeness_and_uniqueness(self, n, m):
        solutions = set(weak_composition_iter(n, m))

        if m == 0 and n > 0:
            expected_count = 0
        else:
            # the total number of distinct partitions is given by (n+m-1)!/((m-1)!*n!)
            expected_count = 1
            for i in range(1, m):
                expected_count *= n + m - i
            for i in range(1, m):
                expected_count /= i

        assert len(solutions) == expected_count
        assert len(set(solutions)) == expected_count
项目:txacme    作者:twisted    | 项目源码 | 文件源码
def test_empty_names_invalid(self):
        """
        `~txacme.util.csr_for_names` raises `ValueError` if given an empty list
        of names.
        """
        with ExpectedException(ValueError):
            csr_for_names([], RSA_KEY_512_RAW)
项目:txacme    作者:twisted    | 项目源码 | 文件源码
def test_valid_for_names(self, names, key):
        """
        `~txacme.util.csr_for_names` returns a CSR that is actually valid for
        the given names.
        """
        assume(len(names[0]) <= 64)

        self.assertThat(
            csr_for_names(names, key),
            MatchesAll(*[ValidForName(name) for name in names]))
项目:txacme    作者:twisted    | 项目源码 | 文件源码
def test_filepath_mode(self):
        """
        The given ``FilePath`` is always converted to text mode.
        """
        store = DirectoryStore(FilePath(b'bytesbytesbytes'))
        self.assertThat(store.path.path, IsInstance(unicode))
项目:txacme    作者:twisted    | 项目源码 | 文件源码
def test_from_directory(self):
        """
        :func:`~txacme.client.Client.from_url` constructs a client with a
        directory retrieved from the given URL.
        """
        new_reg = u'https://example.org/acme/new-reg'
        sequence = RequestSequence(
            [(MatchesListwise([
                Equals(b'GET'),
                Equals(u'https://example.org/acme/'),
                Always(),
                Always(),
                Always()]),
             (http.OK,
              {b'content-type': JSON_CONTENT_TYPE,
               b'replay-nonce': jose.b64encode(b'Nonce')},
              _json_dumps({
                  u'new-reg': new_reg,
                  u'revoke-cert': u'https://example.org/acme/revoke-cert',
                  u'new-authz': u'https://example.org/acme/new-authz',
              })))],
            self.expectThat)
        treq_client = HTTPClient(
            agent=RequestTraversalAgent(
                StringStubbingResource(sequence)),
            data_to_body_producer=_SynchronousProducer)
        with sequence.consume(self.fail):
            d = Client.from_url(
                reactor, URL.fromText(u'https://example.org/acme/'),
                key=RSA_KEY_512, alg=jose.RS256,
                jws_client=JWSClient(
                    treq_client, key=RSA_KEY_512, alg=jose.RS256))
            self.assertThat(
                d,
                succeeded(
                    MatchesAll(
                        AfterPreprocessing(
                            lambda client:
                            client.directory[messages.NewRegistration()],
                            Equals(new_reg)))))
项目:txkube    作者:LeastAuthority    | 项目源码 | 文件源码
def test_from_signed_bits(self):
        """
        ``_IntegerRange.from_signed_bits`` returns an ``_IntegerRange`` with lower
        and upper bounds set to the smallest and largest values a signed
        integer of the given width can represent.
        """
        r = _IntegerRange.from_signed_bits(4)
        self.assertThat(r, Equals(_IntegerRange(min=-8, max=7)))
项目:txkube    作者:LeastAuthority    | 项目源码 | 文件源码
def test_from_unsigned_bits(self):
        """
        ``_IntegerRange.from_unsigned_bits`` returns an ``_IntegerRange`` with
        lower and upper bounds set to the smallest and largest values an
        unsigned integer of the given width can represent.
        """
        r = _IntegerRange.from_unsigned_bits(4)
        self.assertThat(r, Equals(_IntegerRange(min=0, max=15)))
项目:txkube    作者:LeastAuthority    | 项目源码 | 文件源码
def test_kind(self):
        """
        An attribute of the class retrieved from ``VersionedPClasses`` named by
        the value given in the call to ``transform_definitions`` exposes the
        **kind** the type corresponds to.
        """
        a = VersionedPClasses(self.spec, {u"a"})
        self.assertThat(
            a.foo.kind,
            MatchesAll(IsInstance(unicode), Equals(u"foo")),
        )
项目:txkube    作者:LeastAuthority    | 项目源码 | 文件源码
def test_version(self):
        """
        An attribute of the class retrieved from ``VersionedPClasses`` named by
        the value given in the call to ``transform_definitions`` exposes the
        **apiVersion** the type corresponds to.
        """
        a = VersionedPClasses(self.spec, {u"a"})
        # Aaahh.  Direct vs indirect first access can make a difference. :(
        a.foolist
        self.assertThat(
            a.foo.apiVersion,
            MatchesAll(IsInstance(unicode), Equals(u"a")),
        )
项目:txkube    作者:LeastAuthority    | 项目源码 | 文件源码
def test_unknown_version(self):
        """
        ``iobject_from_raw`` raises ``UnrecognizedVersion`` if it does not
        recognize the *apiVersion* in the given data.
        """
        model = v1_5_model

        obj = {
            u"apiVersion": u"invalid.example.txkube",
            u"kind": u"Service",
        }
        self.assertThat(
            lambda: model.iobject_from_raw(obj),
            raises(UnrecognizedVersion(obj[u"apiVersion"], obj)),
        )
项目:txkube    作者:LeastAuthority    | 项目源码 | 文件源码
def test_remove(self, collection, choose):
        """
        ``NamespaceList.remove`` creates a new ``NamespaceList`` which does not
        have the given item.
        """
        assume(len(collection.items) > 0)
        item = choose(collection.items)
        removed = collection.remove(item)
        self.assertThat(removed.items, Not(Contains(item)))
项目:djinn    作者:ordjinnization    | 项目源码 | 文件源码
def test_transform_grouping_by_projects(self, given_z):
        """
        Given a known value for z, generate the data that would give this z,
        transform the data and check that the z value from the transformed data
        matches the given z value.
        :param given_z: the generated z value.
        """
        data, expected_z, expected_stages, expected_projects = gen_data_from_z(given_z)
        actual = gen_heatmap_with_strategy(projects_stage_inner_groupby, data)
        expected_failures = build_failure_map(expected_stages, expected_projects, expected_z)
        stages = actual['x']
        projects = actual['y']
        actual_failures = build_failure_map(stages, projects, actual['z'])
        self.assertEqual(expected_failures, actual_failures)
项目:isambard    作者:woolfson-group    | 项目源码 | 文件源码
def test_helix_non_canonical(self, sequence):
        """Test Scwrl sidechain packing when given non-cannonical residue labels."""
        helix = isambard.specifications.Helix(5)
        helix.pack_new_sequence(sequence)
        r_seq = sequence[:]
        non_can = [x for x in sequence if x not in isambard.tools.amino_acids.standard_amino_acids.keys()]
        if non_can:
            for aa in non_can:
                r_seq = r_seq.replace(aa, 'G')
            self.assertEqual(helix.sequence, r_seq)
        else:
            self.assertEqual(helix.sequence, r_seq)
项目:pyrosbag    作者:masasin    | 项目源码 | 文件源码
def _run_argument_numeric(self, argument, addition, input_type):
        @hyp.given(input_type())
        def numeric_argument_run(number):
            with patch.object(prb, "sp", autospec=True) as mock_sp:
                mock_sp.PIPE = sp.PIPE
                kwargs = {argument: number}
                self.running_bag.play(**kwargs)
                arguments = ["rosbag", "play", self.running_bag.filenames[0],
                             "--{}={}".format(addition, number)]
                mock_sp.Popen.assert_called_once_with(arguments,
                        stdin=mock_sp.PIPE, stdout=None, stderr=None)

        numeric_argument_run()
项目:chandere2    作者:TsarFox    | 项目源码 | 文件源码
def test_directory_for_file_downloading(self, monkeypatch):
        monkeypatch.setattr("os.access", lambda *args: True)
        assert get_path(".", "fd", "") == "."
        assert get_path("./a_file.txt", "fd", "") is None

    # Asserts that filenames are implicity given for
    # archives if only a directory is given.
项目:chandere2    作者:TsarFox    | 项目源码 | 文件源码
def test_strip_board_with_thread(self, target_board, target_thread):
        expected_thread = str(target_thread)
        expected_board = urllib.parse.quote(target_board.strip("/"),
                                            safe="/ ", errors="ignore")

        # If the given target lacks a valid board initial but a thread
        # is given, the thread will be interpreted as a board.
        if not re.search(r"[^\s\/]", expected_board):
            expected_board = str(target_thread)
            expected_thread = None

        target = "/".join((target_board, str(target_thread)))
        assert strip_target(target) == (expected_board, expected_thread)
项目:pycryptoki    作者:gemalto    | 项目源码 | 文件源码
def reverse_case(self, pointer, leng, func):
        """
        Perform the reverse operation of the given function on (pointer, leng)
        :param pointer: c pointer
        :param leng: data length
        :param func: function type
        :return: python type
        """
        c_attr = self.create_ck_attr(pointer, leng)
        return func(c_attr, reverse=True)
项目:pycryptoki    作者:gemalto    | 项目源码 | 文件源码
def test_auto_c_array_empty(self, typ_val):
        """
        Initialize an empty array w/ elements of the given c_type.
        :param typ_val: randomly selected ctype
        """
        c_array = AutoCArray(ctype=typ_val)

        assert c_array.array is None
        assert c_array.size.contents.value == len(c_array) == 0
        assert c_array.ctype == typ_val

        if typ_val == c_char:
            assert c_array.array.contents.value == typ_val(b'\x00').value
        else:
            assert c_array.array.contents.value == typ_val(0).value
项目:vws-python    作者:adamtheturtle    | 项目源码 | 文件源码
def test_decorator(
        self,
        vuforia_server_credentials: VuforiaServerCredentials,
        png_rgb: io.BytesIO,
    ) -> None:
        """
        When the decorator is used, targets are not persisted between
        invocations.
        """
        image_data = png_rgb.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        data = {
            'name': 'example',
            'width': 1,
            'image': image_data_encoded,
        }

        @MockVWS(
            access_key=vuforia_server_credentials.access_key.decode('ascii'),
            secret_key=vuforia_server_credentials.secret_key.decode('ascii'),
        )
        def create() -> str:
            """
            Create a new target and return its id.
            """
            response = add_target_to_vws(
                vuforia_server_credentials=vuforia_server_credentials,
                data=data,
            )

            target_id = response.json()['target_id']

            response = get_vws_target(
                vuforia_server_credentials=vuforia_server_credentials,
                target_id=target_id,
            )

            assert response.status_code == codes.OK
            return target_id

        @MockVWS(
            access_key=vuforia_server_credentials.access_key.decode('ascii'),
            secret_key=vuforia_server_credentials.secret_key.decode('ascii'),
        )
        def verify(target_id: str) -> None:
            """
            Assert that there is no target with the given id.
            """
            response = get_vws_target(
                vuforia_server_credentials=vuforia_server_credentials,
                target_id=target_id,
            )

            assert response.status_code == codes.NOT_FOUND

        target_id = create()
        verify(target_id=target_id)