1- import sys
2- import os
31from hypothesis import given , strategies as st
42
5- # Add root directory to python path
6- sys .path .append (os .path .dirname (os .path .dirname (os .path .abspath (__file__ ))))
7-
83from searches .binary_search import binary_search
94
105# Strategy to generate a sorted list of integers
11- sorted_list_strategy = st .lists (st .integers (), min_size = 0 ).map (sorted )
6+ sorted_list_strategy = st .lists (st .integers ()).map (sorted )
7+
128
139@given (
1410 arr = sorted_list_strategy ,
15- # Pick a random integer as a potential target
16- target = st .integers ()
11+ target = st .integers (),
1712)
18- def test_binary_search_property_based (arr , target ) :
13+ def test_binary_search_property_based (arr : list [ int ] , target : int ) -> None :
1914 """
2015 Property-based test:
21- 1. If target is in arr, binary_search MUST return an index 'i'
16+ 1. If target is in arr, binary_search MUST return an index 'i'
2217 such that arr[i] == target.
2318 2. If target is in arr, it MUST be the FIRST occurrence.
2419 3. If target is not in arr, binary_search MUST return -1.
2520 """
26-
2721 result = binary_search (arr , target )
28-
22+
2923 if target in arr :
3024 assert result != - 1 , f"Target { target } was in { arr } but not found."
31- assert arr [result ] == target , f"Index { result } pointed to { arr [result ]} , not { target } ."
32-
25+ assert arr [result ] == target , f"Index { result } pointed to { arr [result ]} ."
26+
3327 # Property: Verify it is the FIRST occurrence
34- # Only check if the target is actually at the result index
28+ # Check that target does not exist at any index before 'result'
3529 for i in range (result ):
36- assert arr [i ] != target , f"Found target { target } at index { result } , but earlier occurrence at { i } ."
30+ assert arr [i ] != target , f"Target at { result } , but earlier at { i } ."
3731 else :
38- assert result == - 1 , f"Target { target } was not in { arr } , but found at index { result } ."
32+ assert result == - 1 , f"Target { target } not in { arr } , but found at { result } ."
0 commit comments