How to use mark_forced method in hypothesis

Best Python code snippet using hypothesis

datatree.py

Source:datatree.py Github

copy

Full Screen

...103 def forced(self):104 if not self.__forced:105 return EMPTY106 return self.__forced107 def mark_forced(self, i):108 """Note that the value at index ``i`` was forced."""109 assert 0 <= i < len(self.values)110 if self.__forced is None:111 self.__forced = set()112 self.__forced.add(i)113 def split_at(self, i):114 """Splits the tree so that it can incorporate115 a decision at the ``draw_bits`` call corresponding116 to position ``i``, or raises ``Flaky`` if that was117 meant to be a forced node."""118 if i in self.forced:119 inconsistent_generation()120 assert not self.is_exhausted121 key = self.values[i]122 child = TreeNode(123 bit_lengths=self.bit_lengths[i + 1 :],124 values=self.values[i + 1 :],125 transition=self.transition,126 )127 self.transition = Branch(bit_length=self.bit_lengths[i], children={key: child})128 if self.__forced is not None:129 child.__forced = {j - i - 1 for j in self.__forced if j > i}130 self.__forced = {j for j in self.__forced if j < i}131 child.check_exhausted()132 del self.values[i:]133 del self.bit_lengths[i:]134 assert len(self.values) == len(self.bit_lengths) == i135 def check_exhausted(self):136 """Recalculates ``self.is_exhausted`` if necessary then returns137 it."""138 if (139 not self.is_exhausted140 and len(self.forced) == len(self.values)141 and self.transition is not None142 ):143 if isinstance(self.transition, Conclusion):144 self.is_exhausted = True145 elif len(self.transition.children) == self.transition.max_children:146 self.is_exhausted = all(147 v.is_exhausted for v in self.transition.children.values()148 )149 return self.is_exhausted150class DataTree(object):151 """Tracks the tree structure of a collection of ConjectureData152 objects, for use in ConjectureRunner."""153 def __init__(self):154 self.root = TreeNode()155 @property156 def is_exhausted(self):157 """Returns True if every possible node is dead and thus the language158 described must have been fully explored."""159 return self.root.is_exhausted160 def generate_novel_prefix(self, random):161 """Generate a short random string that (after rewriting) is not162 a prefix of any buffer previously added to the tree.163 The resulting prefix is essentially arbitrary - it would be nice164 for it to be uniform at random, but previous attempts to do that165 have proven too expensive.166 """167 assert not self.is_exhausted168 novel_prefix = bytearray()169 def append_int(n_bits, value):170 novel_prefix.extend(int_to_bytes(value, bits_to_bytes(n_bits)))171 current_node = self.root172 while True:173 assert not current_node.is_exhausted174 for i, (n_bits, value) in enumerate(175 zip(current_node.bit_lengths, current_node.values)176 ):177 if i in current_node.forced:178 append_int(n_bits, value)179 else:180 while True:181 k = random.getrandbits(n_bits)182 if k != value:183 append_int(n_bits, k)184 break185 # We've now found a value that is allowed to186 # vary, so what follows is not fixed.187 return hbytes(novel_prefix)188 else:189 assert not isinstance(current_node.transition, Conclusion)190 if current_node.transition is None:191 return hbytes(novel_prefix)192 branch = current_node.transition193 assert isinstance(branch, Branch)194 n_bits = branch.bit_length195 while True:196 k = random.getrandbits(n_bits)197 try:198 child = branch.children[k]199 except KeyError:200 append_int(n_bits, k)201 return hbytes(novel_prefix)202 if not child.is_exhausted:203 append_int(n_bits, k)204 current_node = child205 break206 def rewrite(self, buffer):207 """Use previously seen ConjectureData objects to return a tuple of208 the rewritten buffer and the status we would get from running that209 buffer with the test function. If the status cannot be predicted210 from the existing values it will be None."""211 buffer = hbytes(buffer)212 data = ConjectureData.for_buffer(buffer)213 try:214 self.simulate_test_function(data)215 return (data.buffer, data.status)216 except PreviouslyUnseenBehaviour:217 return (buffer, None)218 def simulate_test_function(self, data):219 """Run a simulated version of the test function recorded by220 this tree. Note that this does not currently call ``stop_example``221 or ``start_example`` as these are not currently recorded in the222 tree. This will likely change in future."""223 node = self.root224 try:225 while True:226 for i, (n_bits, previous) in enumerate(227 zip(node.bit_lengths, node.values)228 ):229 v = data.draw_bits(230 n_bits, forced=node.values[i] if i in node.forced else None231 )232 if v != previous:233 raise PreviouslyUnseenBehaviour()234 if isinstance(node.transition, Conclusion):235 t = node.transition236 data.conclude_test(t.status, t.interesting_origin)237 elif node.transition is None:238 raise PreviouslyUnseenBehaviour()239 else:240 v = data.draw_bits(node.transition.bit_length)241 try:242 node = node.transition.children[v]243 except KeyError:244 raise PreviouslyUnseenBehaviour()245 except StopTest:246 pass247 def new_observer(self):248 return TreeRecordingObserver(self)249class TreeRecordingObserver(DataObserver):250 def __init__(self, tree):251 self.__current_node = tree.root252 self.__index_in_current_node = 0253 self.__trail = [self.__current_node]254 def draw_bits(self, n_bits, forced, value):255 i = self.__index_in_current_node256 self.__index_in_current_node += 1257 node = self.__current_node258 assert len(node.bit_lengths) == len(node.values)259 if i < len(node.bit_lengths):260 if n_bits != node.bit_lengths[i]:261 inconsistent_generation()262 # Note that we don't check whether a previously263 # forced value is now free. That will be caught264 # if we ever split the node there, but otherwise265 # may pass silently. This is acceptable because it266 # means we skip a hash set lookup on every267 # draw and that's a pretty niche failure mode.268 if forced and i not in node.forced:269 inconsistent_generation()270 if value != node.values[i]:271 node.split_at(i)272 assert i == len(node.values)273 new_node = TreeNode()274 branch = node.transition275 branch.children[value] = new_node276 self.__current_node = new_node277 self.__index_in_current_node = 0278 else:279 trans = node.transition280 if trans is None:281 node.bit_lengths.append(n_bits)282 node.values.append(value)283 if forced:284 node.mark_forced(i)285 elif isinstance(trans, Conclusion):286 assert trans.status != Status.OVERRUN287 # We tried to draw where history says we should have288 # stopped289 inconsistent_generation()290 else:291 assert isinstance(trans, Branch)292 if n_bits != trans.bit_length:293 inconsistent_generation()294 try:295 self.__current_node = trans.children[value]296 except KeyError:297 self.__current_node = trans.children.setdefault(value, TreeNode())298 self.__index_in_current_node = 0...

Full Screen

Full Screen

stones.py

Source:stones.py Github

copy

Full Screen

1#-------------------------------------------------------------------------------2# Name: Go board recognition project3# Purpose: Go stone and stone collection class4#5# Author: kol6#7# Created: 23.12.20198# Copyright: (c) kol 20199# Licence: MIT10#-------------------------------------------------------------------------------11from .grdef import *12from .utils import format_stone_pos, stone_pos_from_str13import numpy as np14# A stone class15class GrStone(object):16 """A stone class.17 This class holds one stone parameters as a list with the following indexes:18 GR_X X position on a board (absolute, edges ignored, 0:image width)19 GR_Y Y position (0:image height)20 GR_A Position on horizontal axis (1:board_size, minimum on left side)21 GR_B Position on vertical axis (1:board size, minimum on bottom)22 GR_R Stone circle radius23 GR_BW Color (either STONE_BLACK or STONE_WHITE)24 """25 def __init__(self, stone = None, bw = None):26 self.forced = False27 self.added = False28 self.v, self.def_v = None, None29 if stone is not None:30 self.set(stone, bw)31 @property32 def pos(self):33 """Stone position in text format (A10, B2, etc)"""34 return format_stone_pos(self.v, axis = None)35 def __str__(self):36 return self.pos37 def __iter__(self):38 """Iterator"""39 yield from self.v40 def __getitem__(self, index):41 """Getter"""42 return self.v[index]43 def set(self, stone, bw = None):44 """Assign stone params"""45 if stone is None:46 return47 elif isinstance(stone, GrStone):48 self.v = stone.v49 if self.def_v is None: self.def_v = stone.def_v50 elif type(stone) is np.ndarray or type(stone) is list or type(stone) is tuple:51 if len(stone) <= GR_BW and bw is None:52 raise Exception('Color has to be provided')53 # Coordinates are expected to be integer while other props could be of any type54 self.v = [int(x) for x in stone[0:GR_BW]]55 if len(stone) <= GR_BW:56 self.v.extend([None] * (GR_BW - len(stone) + 1))57 self.v[GR_BW] = bw58 else:59 self.v[GR_BW:] = [x for x in stone[GR_BW:]]60 if self.def_v is None: self.def_v = self.v.copy()61 else:62 raise ValueError("Don't know how to handle type " + str(type(stone)))63 def tolist(self):64 """Return stone parameters as a list"""65 return self.v[0:GR_BW+1] if self.v is not None else None66 def to_fulllist(self):67 return [68 self.v[0:GR_BW],69 self.v[GR_BW],70 self.def_v[0:GR_BW],71 self.def_v[GR_BW],72 self.added] if self.v is not None else None73 def from_fulllist(self, f):74 if len(f) < 4:75 raise ValueError("Invalid forced stone list format")76 self.v = list(f[0])77 self.v.extend([f[1]])78 self.def_v = list(f[2])79 self.def_v.extend([f[3]])80 self.forced = True81 self.added = f[4] if len(f) > 4 else False82# Stone collection83class GrStones(object):84 """A collection of stones on board"""85 def __init__(self, stones = None, bw = None):86 self.__stones = dict()87 if stones is not None:88 if bw is None:89 raise ValueError("Stone color not specified")90 self.assign(stones, bw)91 @property92 def stones(self):93 """Stones collection (dictionary with position as a key)"""94 return self.__stones95 @stones.setter96 def stones(self, value):97 """Assign stones from another collection"""98 self.assign(value, True)99 @property100 def black(self):101 """List of black stones"""102 return [self.__stones[k].v for k in self.__stones if self.__stones[k][GR_BW] == STONE_BLACK]103 @property104 def white(self):105 """List of white stones"""106 return [self.__stones[k].v for k in self.__stones if self.__stones[k][GR_BW] == STONE_WHITE]107 def keys(self):108 """List of stone positions on board"""109 return self.__stones.keys()110 def forced_stones(self):111 """Positions of stones with parameters forcefully changed or stone added"""112 return [k for k in self.__stones if self.__stones[k].forced]113 def unforced_stones(self):114 """Positions of stone which were not forced"""115 return [k for k in self.__stones if not self.__stones[k].forced]116 def changed_stones(self):117 """Positions of stone with parameters changed since detection"""118 return [k for k in self.__stones119 if self.__stones[k].bw != self.__stones[k].def_bw or \120 not all(np.equal(self.__stones[k].v, self.__stones[k].def_v))]121 def relocated_stones(self):122 """List of stones which had changed color """123 return [k for k in self.__stones124 if self.__stones[k].bw != self.__stones[k].def_bw]125 def added_stones(self):126 """Positions of stone added after detection"""127 return [k for k in self.__stones if self.__stones[k].added]128 def toarray(self):129 """Represent stone collection as numpy array.130 Only integer properties (GR_X:GR_R) are returned, color flags are ommitted"""131 if len(self.__stones) == 0:132 return np.array([])133 else:134 r = np.empty((len(self.__stones), GR_R+1), dtype = np.int)135 for n, k in enumerate(self.__stones):136 r[n] = self.__stones[k].v[0:-1]137 return r138 def tolist(self):139 """List of all stones in collection"""140 r = []141 for k in self.__stones:142 r.extend([self.__stones[k].tolist()])143 return r144 def todict(self):145 """Represent all stones as a dictonary"""146 r = dict()147 for k in self.__stones:148 d = self.__stones[k].tolist()149 r[k] = d150 return r151 def add_ext(self, new_stones, bw = None, with_forced = True, mark_forced = False, mark_added = False):152 """Add or replace stones in collection - internal"""153 if new_stones is None:154 return155 if type(new_stones) is GrStones:156 for k in new_stones:157 p = self.__stones.get(k)158 if p is None:159 p = new_stones.stones[k]160 self.__stones[p.pos] = p161 if mark_added: p.added = True162 if mark_forced: p.forced = True163 elif with_forced or not p.forced:164 p.set(new_stones.stones[k])165 if mark_forced: p.forced = True166 elif type(new_stones) is dict:167 for k in new_stones:168 p = self.__stones.get(k)169 if p is None:170 n = GrStone(new_stones[k], bw)171 self.__stones[n.pos] = n172 if mark_added: p.added = True173 if mark_forced: p.forced = True174 elif with_forced or not p.forced:175 p.set(new_stones[k], bw)176 if mark_forced: p.forced = True177 elif type(new_stones) is list or type(new_stones) is np.ndarray:178 for s in new_stones:179 if type(s) is not list and type(s) is not tuple and type(s) is not np.ndarray:180 raise Exception("Invalid record type " + str(type(s)))181 p = GrStone(s, bw)182 t = self.__stones.get(p.pos)183 if t is None:184 self.__stones[p.pos] = p185 if mark_added: p.added = True186 if mark_forced: p.forced = True187 elif with_forced or not t.forced:188 t.set(p)189 if mark_forced: t.forced = True190 else:191 raise Exception("Invalid stone list type " + str(type(new_stones)))192 def add(self, new_stones, bw = None, with_forced = True):193 """Add or replace stones in collection - internal"""194 return self.add_ext(new_stones, bw, with_forced, mark_forced = True, mark_added = True)195 def assign(self, new_stones, bw = None, with_forced = False):196 """Store new stones in collection.197 Parameters:198 new_stones dict, GrStones or any iterable199 bw Stone color, has to be set when iterable or dict is provided200 with_forced Set to True to clear or keep forced stones unchanged201 """202 self.clear(with_forced)203 if not new_stones is None:204 self.add_ext(new_stones, bw, with_forced = with_forced, mark_forced = False, mark_added = False)205 def remove(self, stone):206 """Remove a stone from collection"""207 p = None208 if isinstance(stone, GrStone):209 p = stone.pos210 elif type(p) is list or type(p) is np.ndarray:211 p = format_stone_pos(stone)212 else:213 p = str(stone)214 if p in self.__stones: del self.__stones[p]215 def clear(self, with_forced = False):216 """Clear collection. If with_forced is False, forced stones remain"""217 if with_forced:218 self.__stones.clear()219 else:220 for k in self.unforced_stones(): del self.__stones[k]221 def reset(self):222 """Reset stone parameters to initial values clearing forced flag223 If stone was added after detection, this stone is removed"""224 to_remove = []225 for k in self.__stones:226 s = self.__stones[k]227 if s.added:228 to_remove.extend([k])229 else:230 s.v = s.def_v.copy()231 s.forced = False232 for k in to_remove:233 del self.__stones[k]234 def forced_tolist(self):235 """Get a list of forced stones (all parameters).236 Returns a list of stones where each entry contains:237 0 Current stone parameters (list of ints)238 1 Current stone color (str)239 2 Default stone parameters (list of ints)240 3 Default stone color241 4 Stone added flag"""242 r = []243 for k in self.__stones:244 if self.__stones[k].forced:245 r.extend([self.__stones[k].to_fulllist()])246 return r247 def forced_fromlist(self, forced_list):248 """Store forced stones in collection. See forced_tolist for list format"""249 if forced_list is None:250 return251 for f in forced_list:252 new_stone = GrStone()253 new_stone.from_fulllist(f)254 self.__stones.setdefault(new_stone.pos, new_stone)255 def get(self, key):256 """Returns a stone data for given position of None if it doesn't exist"""257 return self.__stones[key].v if key in self.__stones else None258 def get_stone(self, key = None, stone = None):259 """Returns a stone object for given position of None if it doesn't exist"""260 if key is None:261 if stone is None:262 raise ValueError("Eiher stone or position has to be provided")263 key = format_stone_pos(stone)264 return self.__stones[key] if key in self.__stones else None265 def get_stone_list(self, keys):266 """Returns a list of stones for given position keys"""267 return [self.__stones[k].v for k in keys if k in self.__stones.keys()]268 def __iter__(self):269 """Iterator"""270 yield from self.__stones271 def __getitem__(self, key):272 """Getter"""273 return self.__stones[key].v274 def __setitem__(self, key, value):275 """Setter"""276 self.__stones[key].v = value277 def __delitem__(self, key):278 """Deleter"""279 del self.__stones[key]280 def __contains__(self, item):281 """in operation support"""282 return item in self.__stones283 def __str__(self):284 """Printing support"""285 return str(self.todict())286 def __len__(self):287 return len(self.__stones)288 def __array__(self):289 return self.toarray()290 def find_coord(self, x, y):291 """Find a stone at given (X,Y) coordinates.292 If stone found returns tuple(stone properties (list of ints), stone color) otherwise - None"""293 for k in self.__stones:294 s = self.__stones[k].v295 min_x = max(1, int(s[GR_X]) - int(s[GR_R]))296 min_y = max(1, int(s[GR_Y]) - int(s[GR_R]))297 max_x = s[GR_X] + s[GR_R]298 max_y = s[GR_Y] + s[GR_R]299 if (x >= min_x and x <= max_x and y >= min_y and y <= max_y):300 return s301 return None302 def find_position(self, a, b):303 """Find a stone at given (A,B) position.304 If stone found returns tuple(stone properties (list of ints), stone color) otherwise - None"""305 s = self.__stones.get(format_stone_pos([0,0,a,b], axis = None))306 return s.v if s is not None else None307 def find(self, key):308 """Returns a stone at position specified by key.309 If stone found returns tuple(stone properties (list of ints), stone color) otherwise - None"""310 s = self.__stones.get(key)311 return s.v if s is not None else None312 def find_nearby(self, p, d = 1, straight = True):313 """Finds all stones near specified position.314 Parameters:315 p stone position coordinates as (A, B) tuple or position string (A9)316 d numer of positions to look for317 straight if True, only straight (horizontal/vertical) positions gets taken into account318 Otherwise, diagonal positions also counted319 Return: a list of stones enclosing given position320 """321 if p is None:322 return None323 elif type(p) is not tuple and type(p) is not list and type(p) is not np.ndarray:324 # Assume it is a string325 p = stone_pos_from_str(str(p))326 r = []327 rg_a = range(max(p[0]-d,1), p[0]+d+1)328 rg_b = range(max(p[1]-d,1), p[1]+d+1)329 stones = self.tolist()330 for s in stones:331 if s[GR_A] == p[0] and s[GR_B] == p[1]:332 # This very stone, ignore333 continue334 elif not straight and s[GR_A] in rg_a and s[GR_B] in rg_b:335 # A stone at any direction336 r.extend([s])337 elif straight and ((s[GR_A] in rg_a and s[GR_B] == p[1]) or \338 (s[GR_B] in rg_b and s[GR_A] == p[0])):339 # A stone at horizontal/vertical directions340 r.extend([s])...

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