Best Python code snippet using hypothesis
collections.py
Source:collections.py  
1# coding=utf-82#3# This file is part of Hypothesis, which may be found at4# https://github.com/HypothesisWorks/hypothesis/5#6# Most of this work is copyright (C) 2013-2019 David R. MacIver7# (david@drmaciver.com), but it contains contributions by others. See8# CONTRIBUTING.rst for a full list of people who may hold copyright, and9# consult the git log if you need to determine who owns an individual10# contribution.11#12# This Source Code Form is subject to the terms of the Mozilla Public License,13# v. 2.0. If a copy of the MPL was not distributed with this file, You can14# obtain one at https://mozilla.org/MPL/2.0/.15#16# END HEADER17from __future__ import absolute_import, division, print_function18import hypothesis.internal.conjecture.utils as cu19from hypothesis.errors import InvalidArgument20from hypothesis.internal.compat import OrderedDict21from hypothesis.internal.conjecture.utils import combine_labels22from hypothesis.searchstrategy.strategies import MappedSearchStrategy, SearchStrategy23class TupleStrategy(SearchStrategy):24    """A strategy responsible for fixed length tuples based on heterogenous25    strategies for each of their elements."""26    def __init__(self, strategies):27        SearchStrategy.__init__(self)28        self.element_strategies = tuple(strategies)29    def do_validate(self):30        for s in self.element_strategies:31            s.validate()32    def calc_label(self):33        return combine_labels(34            self.class_label, *[s.label for s in self.element_strategies]35        )36    def __repr__(self):37        if len(self.element_strategies) == 1:38            tuple_string = "%s," % (repr(self.element_strategies[0]),)39        else:40            tuple_string = ", ".join(map(repr, self.element_strategies))41        return "TupleStrategy((%s))" % (tuple_string,)42    def calc_has_reusable_values(self, recur):43        return all(recur(e) for e in self.element_strategies)44    def do_draw(self, data):45        return tuple(data.draw(e) for e in self.element_strategies)46    def calc_is_empty(self, recur):47        return any(recur(e) for e in self.element_strategies)48class ListStrategy(SearchStrategy):49    """A strategy for lists which takes a strategy for its elements and the50    allowed lengths, and generates lists with the correct size and contents."""51    def __init__(self, elements, min_size=0, max_size=float("inf")):52        SearchStrategy.__init__(self)53        self.min_size = min_size or 054        self.max_size = max_size if max_size is not None else float("inf")55        assert 0 <= self.min_size <= self.max_size56        self.average_size = min(57            max(self.min_size * 2, self.min_size + 5),58            0.5 * (self.min_size + self.max_size),59        )60        self.element_strategy = elements61    def calc_label(self):62        return combine_labels(self.class_label, self.element_strategy.label)63    def do_validate(self):64        self.element_strategy.validate()65        if self.is_empty:66            raise InvalidArgument(67                (68                    "Cannot create non-empty lists with elements drawn from "69                    "strategy %r because it has no values."70                )71                % (self.element_strategy,)72            )73        if self.element_strategy.is_empty and 0 < self.max_size < float("inf"):74            raise InvalidArgument(75                "Cannot create a collection of max_size=%r, because no "76                "elements can be drawn from the element strategy %r"77                % (self.max_size, self.element_strategy)78            )79    def calc_is_empty(self, recur):80        if self.min_size == 0:81            return False82        else:83            return recur(self.element_strategy)84    def do_draw(self, data):85        if self.element_strategy.is_empty:86            assert self.min_size == 087            return []88        elements = cu.many(89            data,90            min_size=self.min_size,91            max_size=self.max_size,92            average_size=self.average_size,93        )94        result = []95        while elements.more():96            result.append(data.draw(self.element_strategy))97        return result98    def __repr__(self):99        return "%s(%r, min_size=%r, max_size=%r)" % (100            self.__class__.__name__,101            self.element_strategy,102            self.min_size,103            self.max_size,104        )105class UniqueListStrategy(ListStrategy):106    def __init__(self, elements, min_size, max_size, key):107        super(UniqueListStrategy, self).__init__(elements, min_size, max_size)108        self.key = key109    def do_draw(self, data):110        if self.element_strategy.is_empty:111            assert self.min_size == 0112            return []113        elements = cu.many(114            data,115            min_size=self.min_size,116            max_size=self.max_size,117            average_size=self.average_size,118        )119        seen = set()120        result = []121        while elements.more():122            value = data.draw(self.element_strategy)123            k = self.key(value)124            if k in seen:125                elements.reject()126            else:127                seen.add(k)128                result.append(value)129        assert self.max_size >= len(result) >= self.min_size130        return result131class FixedKeysDictStrategy(MappedSearchStrategy):132    """A strategy which produces dicts with a fixed set of keys, given a133    strategy for each of their equivalent values.134    e.g. {'foo' : some_int_strategy} would generate dicts with the single135    key 'foo' mapping to some integer.136    """137    def __init__(self, strategy_dict):138        self.dict_type = type(strategy_dict)139        if isinstance(strategy_dict, OrderedDict):140            self.keys = tuple(strategy_dict.keys())141        else:142            try:143                self.keys = tuple(sorted(strategy_dict.keys()))144            except TypeError:145                self.keys = tuple(sorted(strategy_dict.keys(), key=repr))146        super(FixedKeysDictStrategy, self).__init__(147            strategy=TupleStrategy((strategy_dict[k] for k in self.keys))148        )149    def calc_is_empty(self, recur):150        return recur(self.mapped_strategy)151    def __repr__(self):152        return "FixedKeysDictStrategy(%r, %r)" % (self.keys, self.mapped_strategy)153    def pack(self, value):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
