How to use _hypothesis_do_random method in hypothesis

Best Python code snippet using hypothesis

random.py

Source:random.py Github

copy

Full Screen

...52 ),53 result,54 )55 )56 def _hypothesis_do_random(self, method, kwargs):57 raise NotImplementedError()58RANDOM_METHODS = [59 name60 for name in [61 "_randbelow",62 "betavariate",63 "choice",64 "choices",65 "expovariate",66 "gammavariate",67 "gauss",68 "getrandbits",69 "lognormvariate",70 "normalvariate",71 "paretovariate",72 "randint",73 "random",74 "randrange",75 "sample",76 "shuffle",77 "triangular",78 "uniform",79 "vonmisesvariate",80 "weibullvariate",81 "randbytes",82 ]83 if hasattr(Random, name)84]85# Fake shims to get a good signature86def getrandbits(self, n: int) -> int:87 raise NotImplementedError()88def random(self) -> float:89 raise NotImplementedError()90def _randbelow(self, n: int) -> int:91 raise NotImplementedError()92STUBS = {f.__name__: f for f in [getrandbits, random, _randbelow]}93SIGNATURES = {}94def sig_of(name):95 try:96 return SIGNATURES[name]97 except KeyError:98 pass99 target = getattr(Random, name)100 result = inspect.signature(STUBS.get(name, target))101 SIGNATURES[name] = result102 return result103def define_copy_method(name):104 target = getattr(Random, name)105 def implementation(self, **kwargs):106 result = self._hypothesis_do_random(name, kwargs)107 self._hypothesis_log_random(name, kwargs, result)108 return result109 spec = inspect.getfullargspec(STUBS.get(name, target))110 result = define_function_signature(target.__name__, target.__doc__, spec)(111 implementation112 )113 result.__module__ = __name__114 result.__qualname__ = "HypothesisRandom." + result.__name__115 setattr(HypothesisRandom, name, result)116for r in RANDOM_METHODS:117 define_copy_method(r)118@attr.s(slots=True)119class RandomState:120 next_states = attr.ib(default=attr.Factory(dict))121 state_id = attr.ib(default=None)122def state_for_seed(data, seed):123 try:124 seeds_to_states = data.seeds_to_states125 except AttributeError:126 seeds_to_states = {}127 data.seeds_to_states = seeds_to_states128 try:129 state = seeds_to_states[seed]130 except KeyError:131 state = RandomState()132 seeds_to_states[seed] = state133 return state134UNIFORM = st.floats(0, 1)135def normalize_zero(f):136 if f == 0.0:137 return 0.0138 else:139 return f140class ArtificialRandom(HypothesisRandom):141 VERSION = 10 ** 6142 def __init__(self, note_method_calls, data):143 HypothesisRandom.__init__(self, note_method_calls=note_method_calls)144 self.__data = data145 self.__state = RandomState()146 def __repr__(self):147 return "HypothesisRandom(generated data)"148 def __copy__(self):149 result = ArtificialRandom(150 note_method_calls=self._HypothesisRandom__note_method_calls,151 data=self.__data,152 )153 result.setstate(self.getstate())154 return result155 def __convert_result(self, method, kwargs, result):156 if method == "choice":157 return kwargs.get("seq")[result]158 if method in ("choices", "sample"):159 seq = kwargs["population"]160 return [seq[i] for i in result]161 if method == "shuffle":162 seq = kwargs["x"]163 original = list(seq)164 for i, i2 in enumerate(result):165 seq[i] = original[i2]166 return167 return result168 def _hypothesis_do_random(self, method, kwargs):169 if method == "choices":170 key = (method, len(kwargs["population"]), kwargs.get("k"))171 elif method == "choice":172 key = (method, len(kwargs["seq"]))173 elif method == "shuffle":174 key = (method, len(kwargs["x"]))175 else:176 key = (method,) + tuple(sorted(kwargs))177 try:178 result, self.__state = self.__state.next_states[key]179 except KeyError:180 pass181 else:182 return self.__convert_result(method, kwargs, result)183 if method == "_randbelow":184 result = cu.integer_range(self.__data, 0, kwargs["n"] - 1)185 elif method in ("betavariate", "random"):186 result = self.__data.draw(UNIFORM)187 elif method == "uniform":188 a = normalize_zero(kwargs["a"])189 b = normalize_zero(kwargs["b"])190 result = self.__data.draw(st.floats(a, b))191 elif method in ("weibullvariate", "gammavariate"):192 result = self.__data.draw(st.floats(min_value=0.0, allow_infinity=False))193 elif method in ("gauss", "normalvariate"):194 mu = kwargs["mu"]195 result = mu + self.__data.draw(196 st.floats(allow_nan=False, allow_infinity=False)197 )198 elif method == "vonmisesvariate":199 result = self.__data.draw(st.floats(0, 2 * math.pi))200 elif method == "randrange":201 if kwargs["stop"] is None:202 stop = kwargs["start"]203 start = 0204 else:205 start = kwargs["start"]206 stop = kwargs["stop"]207 step = kwargs["step"]208 if start == stop:209 raise ValueError(210 "empty range for randrange(%d, %d, %d)" % (start, stop, step)211 )212 if step != 1:213 endpoint = (stop - start) // step214 if (start - stop) % step == 0:215 endpoint -= 1216 i = cu.integer_range(self.__data, 0, endpoint)217 result = start + i * step218 else:219 result = cu.integer_range(self.__data, start, stop - 1)220 elif method == "randint":221 result = cu.integer_range(self.__data, kwargs["a"], kwargs["b"])222 elif method == "choice":223 seq = kwargs["seq"]224 result = cu.integer_range(self.__data, 0, len(seq) - 1)225 elif method == "choices":226 k = kwargs["k"]227 result = self.__data.draw(228 st.lists(229 st.integers(0, len(kwargs["population"]) - 1),230 min_size=k,231 max_size=k,232 )233 )234 elif method == "sample":235 k = kwargs["k"]236 seq = kwargs["population"]237 if k > len(seq) or k < 0:238 raise ValueError(239 "Sample size %d not in expected range 0 <= k <= %d" % (k, len(seq))240 )241 result = self.__data.draw(242 st.lists(243 st.sampled_from(range(len(seq))),244 min_size=k,245 max_size=k,246 unique=True,247 )248 )249 elif method == "getrandbits":250 result = self.__data.draw_bits(kwargs["n"])251 elif method == "triangular":252 low = normalize_zero(kwargs["low"])253 high = normalize_zero(kwargs["high"])254 mode = normalize_zero(kwargs["mode"])255 if mode is None:256 result = self.__data.draw(st.floats(low, high))257 elif self.__data.draw_bits(1):258 result = self.__data.draw(st.floats(mode, high))259 else:260 result = self.__data.draw(st.floats(low, mode))261 elif method in ("paretovariate", "expovariate", "lognormvariate"):262 result = self.__data.draw(st.floats(min_value=0.0))263 elif method == "shuffle":264 result = self.__data.draw(st.permutations(range(len(kwargs["x"]))))265 # This is tested for but only appears in 3.9 so doesn't appear in coverage.266 elif method == "randbytes": # pragma: no cover267 n = kwargs["n"]268 result = self.__data.draw(st.binary(min_size=n, max_size=n))269 else:270 raise NotImplementedError(method)271 new_state = RandomState()272 self.__state.next_states[key] = (result, new_state)273 self.__state = new_state274 return self.__convert_result(method, kwargs, result)275 def seed(self, seed):276 self.__state = state_for_seed(self.__data, seed)277 def getstate(self):278 if self.__state.state_id is not None:279 return self.__state.state_id280 try:281 states_for_ids = self.__data.states_for_ids282 except AttributeError:283 states_for_ids = {}284 self.__data.states_for_ids = states_for_ids285 self.__state.state_id = len(states_for_ids)286 states_for_ids[self.__state.state_id] = self.__state287 return self.__state.state_id288 def setstate(self, state):289 self.__state = self.__data.states_for_ids[state]290DUMMY_RANDOM = Random(0)291def convert_kwargs(name, kwargs):292 kwargs = dict(kwargs)293 signature = sig_of(name)294 bound = signature.bind(DUMMY_RANDOM, **kwargs)295 bound.apply_defaults()296 for k in list(kwargs):297 if (298 kwargs[k] is signature.parameters[k].default299 or signature.parameters[k].kind != inspect.Parameter.KEYWORD_ONLY300 ):301 kwargs.pop(k)302 arg_names = list(signature.parameters)[1:]303 args = []304 for a in arg_names:305 if signature.parameters[a].kind == inspect.Parameter.KEYWORD_ONLY:306 break307 args.append(bound.arguments[a])308 kwargs.pop(a, None)309 while args:310 name = arg_names[len(args) - 1]311 if args[-1] is signature.parameters[name].default:312 args.pop()313 else:314 break # pragma: no cover # Only on Python < 3.8315 return (args, kwargs)316class TrueRandom(HypothesisRandom):317 def __init__(self, seed, note_method_calls):318 HypothesisRandom.__init__(self, note_method_calls)319 self.__seed = seed320 self.__random = Random(seed)321 def _hypothesis_do_random(self, method, kwargs):322 args, kwargs = convert_kwargs(method, kwargs)323 return getattr(self.__random, method)(*args, **kwargs)324 def __copy__(self):325 result = TrueRandom(326 seed=self.__seed,327 note_method_calls=self._HypothesisRandom__note_method_calls,328 )329 result.setstate(self.getstate())330 return result331 def __repr__(self):332 return "Random(%r)" % (self.__seed,)333 def seed(self, seed):334 self.__random.seed(seed)335 self.__seed = seed...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful