def from_dtype(dtype): # type: (np.dtype) -> st.SearchStrategy[Any] """Creates a strategy which can generate any value of the given dtype.""" check_type(np.dtype, dtype, "dtype") # Compound datatypes, eg 'f4,f4,f4' if dtype.names is not None: # mapping np.void.type over a strategy is nonsense, so return now. return st.tuples(*[from_dtype(dtype.fields[name][0]) for name in dtype.names]) # Subarray datatypes, eg '(2, 3)i4' if dtype.subdtype is not None: subtype, shape = dtype.subdtype return arrays(subtype, shape) # Scalar datatypes if dtype.kind == u"b": result = st.booleans() # type: SearchStrategy[Any] elif dtype.kind == u"f": if dtype.itemsize == 2: result = st.floats(width=16) elif dtype.itemsize == 4: result = st.floats(width=32) else: result = st.floats() elif dtype.kind == u"c": if dtype.itemsize == 8: float32 = st.floats(width=32) result = st.builds(complex, float32, float32) else: result = st.complex_numbers() elif dtype.kind in (u"S", u"a"): # Numpy strings are null-terminated; only allow round-trippable values. # `itemsize == 0` means 'fixed length determined at array creation' result = st.binary(max_size=dtype.itemsize or None).filter( lambda b: b[-1:] != b"\0" ) elif dtype.kind == u"u": result = st.integers(min_value=0, max_value=2 ** (8 * dtype.itemsize) - 1) elif dtype.kind == u"i": overflow = 2 ** (8 * dtype.itemsize - 1) result = st.integers(min_value=-overflow, max_value=overflow - 1) elif dtype.kind == u"U": # Encoded in UTF-32 (four bytes/codepoint) and null-terminated result = st.text(max_size=(dtype.itemsize or 0) // 4 or None).filter( lambda b: b[-1:] != u"\0" ) elif dtype.kind in (u"m", u"M"): if "[" in dtype.str: res = st.just(dtype.str.split("[")[-1][:-1]) else: res = st.sampled_from(TIME_RESOLUTIONS) result = st.builds(dtype.type, st.integers(-(2 ** 63), 2 ** 63 - 1), res) else: raise InvalidArgument(u"No strategy inference for {}".format(dtype)) return result.map(dtype.type)
def bounding_boxes(draw: Any, container: BoundingBox = None) -> BoundingBox: x_min = -10000 y_min = -10000 w_max = 10000 h_max = 10000 if container: x_min = container.x_min y_min = container.y_min w_max = container.delta_x h_max = container.delta_y x = draw(floats(min_value=x_min, max_value=10000.0)) y = draw(floats(min_value=y_min, max_value=10000.0)) w = draw(floats(min_value=0.0, max_value=w_max)) h = draw(floats(min_value=0.0, max_value=h_max)) return BoundingBox(x, x + w, y, y + h)
class TestCluster: @given(sets(floats(min_value=1e-5, max_value=100.0))) def test_map_to_empty(self, set_of_floats: Set[float]) -> None: pair_mapping: Dict[float, List[float]] = cluster(euclidean, set_of_floats, []) assert all([pair_mapping[k] == [] for k in pair_mapping]) @given(sets(floats(min_value=1e-5, max_value=100.0))) def test_map_from_empty(self, set_of_floats: Set[float]) -> None: pair_mapping: Dict[float, List[float]] = cluster(euclidean, set(), list(set_of_floats)) assert pair_mapping == {} @given(sets(floats(min_value=1e-5, max_value=100.0))) def test_map_to_self(self, set_of_floats: Set[float]) -> None: pair_mapping = cluster(euclidean, set_of_floats, list(set_of_floats)) assert all([pair_mapping[k] == [k] for k in pair_mapping]) @given(sets(floats(min_value=1e-5, max_value=100.0))) def test_include_in_self(self, set_of_floats: Set[float]) -> None: second_set = add_noise(set_of_floats) pair_mapping = cluster(euclidean, set_of_floats, list(second_set)) assert all([(k in pair_mapping[k]) for k in pair_mapping]) @given(sets(floats(min_value=1e-5, max_value=100.0))) def test_include_all_if_in_vicinity(self, set_of_floats: Set[float]) -> None: second_set = set() for f in set_of_floats: second_set.add(f + uniform(0.0, 0.99)) pair_mapping = cluster(euclidean, set_of_floats, list(second_set)) total_len = sum([len(l) for _, l in pair_mapping.items()]) assert total_len == len(second_set) @given(sets(floats(min_value=1e-5, max_value=100.0))) def test_exclude_all_outside_vicinity(self, set_of_floats: Set[float]) -> None: second_set = set() for _ in set_of_floats: second_set.add(max(set_of_floats) + uniform(1.1, 10.0)) pair_mapping = cluster(euclidean, set_of_floats, list(second_set)) total_len = sum([len(l) for _, l in pair_mapping.items()]) assert total_len == 0, (pair_mapping, second_set, set_of_floats) @given(sets(floats(min_value=1e-5, max_value=100))) def test_map_includes_all_keys(self, set_of_floats: Set[float]) -> None: second_set = add_noise(set_of_floats) pair_mapping = cluster(euclidean, set_of_floats, list(second_set)) assert len(pair_mapping) == len(set_of_floats)
def all_types(draw): return draw( one_of( text(), integers(), none(), booleans(), floats(), tuples(), times(), uuids(), lists(integers()), dictionaries(text(), text()), ))
n = randint(1, 100) r = set(l) for _ in range(n): r.add(random()) return r def test_empty_to_empty() -> None: matches, unmatched_1, unmatched_2, _ = linear_sum_match([], [], euclidean) assert matches == [] assert unmatched_1 == [] assert unmatched_2 == [] @given(lists(floats(min_value=1e-5, max_value=100.0))) def test_list_to_empty(fs: List[float]) -> None: matches, unmatched_1, unmatched_2, _ = linear_sum_match(fs, [], euclidean) assert matches == [] assert unmatched_1 == list(range(len(fs))) assert unmatched_2 == [] @given(lists(floats(min_value=1e-5, max_value=100.0))) def test_list_to_self(fs: List[float]) -> None: matches, unmatched_1, unmatched_2, _ = linear_sum_match(fs, fs, euclidean) assert matches == list(zip(range(len(fs)), range(len(fs)))) assert unmatched_1 == [] assert unmatched_2 == []
def return_test(message, output): if message: assert output.startswith(message) def run_timer(timeout): timeout, message = timeout # Run timer with Timer(message=message, log_function=lambda x: return_test(message, x)) as timer: sleep(timeout) return timer.elapsed_time @settings(deadline=None) @given(text(), floats(min_value=0.0, max_value=0.1)) def test_timer(message, timeout): repetitions = 100 input = [(timeout, message)] * repetitions with ThreadPoolExecutor(max_workers=2) as executor: result = executor.map(run_timer, input) result = list(result) total_time = sum(result) assert abs(int(timeout * 1000000000 * repetitions) - total_time) < 5000000 * repetitions # +/- Milliseconds accuracy
from format_byte import format_byte, format_bit from hypothesis import given from hypothesis._strategies import floats, integers @given(floats(allow_nan=False, allow_infinity=False)) def test_format_bit(nr): assert format_bit(nr) @given(floats(allow_nan=False, allow_infinity=False), integers()) def test_format_byte(nr, precision): assert format_byte(nr, precision) @given(integers(), integers()) def test_format_byte2(nr, precision): assert format_byte(nr, precision) if __name__ == "__main__": test_format_bit() test_format_byte() test_format_byte2()
@given(bounding_boxes(), bounding_boxes()) def test_intersection_not_contained(bbox1: BoundingBox, bbox2: BoundingBox) -> None: if contains_ratio(bbox1, bbox2) == 0.0: assert (intersection(bbox1, bbox2) != bbox2 or bbox2.area == 0.0 or bbox1.area == 0.0) @given(bounding_boxes()) def test_no_move(bbox: BoundingBox) -> None: assert bbox.move(0, 0) == bbox @given(bounding_boxes(), floats(min_value=-10.0, max_value=10.0), floats(min_value=-10.0, max_value=10.0)) def test_scale_around_origin_changes_size(bbox: BoundingBox, sx: float, sy: float) -> None: scaled_bbox = bbox.scale(Shape(sx, sy)) assert scaled_bbox.delta_x == approx(bbox.delta_x * sx, abs=1e-6) assert scaled_bbox.delta_y == approx(bbox.delta_y * sy, abs=1e-6) @given(bounding_boxes(), floats(min_value=-10.0, max_value=10.0), floats(min_value=-10.0, max_value=10.0)) def test_scale_around_origin_moves_center(bbox: BoundingBox, sx: float, sy: float) -> None: scaled_bbox = bbox.scale(Shape(sx, sy)) assert scaled_bbox.center.x == approx(bbox.center.x * sx, abs=1e-6) assert scaled_bbox.center.y == approx(bbox.center.y * sy, abs=1e-6)