unitesting
- Create a Test Class:
- Define a class that inherits from
unittest.TestCase
. This class will contain your test methods (TestBinarySearch
).
- Define a class that inherits from
- Test Methods:
- Each test method is a function within the test class, starting with the prefix
test_
. - Test methods should assert specific conditions about the code. The
unittest.TestCase
class provides various assertion methods likeassertEqual
,assertNotEqual
,assertTrue
,assertFalse
, etc.
- Each test method is a function within the test class, starting with the prefix
Each test method (
test_found
,test_not_found
, etc.) checks different scenarios of the binary search function.
- Running Tests:
- The
if __name__ == '__main__'
: block runs the tests. unittest.main()
executes all the tests (as defined within your test class).
- The
def binary_search(arr, target):
# Initialize the low and high pointers
low = 0
high = len(arr) - 1
# While the search space is valid
while low <= high:
# Find the middle index
mid = (low + high) // 2
# Check if the target is at the mid index
if arr[mid] == target:
return mid
# If the target is greater than the mid element, ignore the left half
elif arr[mid] < target:
low = mid + 1
# If the target is less than the mid element, ignore the right half
else:
high = mid - 1
# Return -1 if the target is not found
return -1
# Example
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 7
result = binary_search(arr, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found in the list")
import unittest
def binary_search(arr, target):
# ... (Your binary_search function code)
class TestBinarySearch(unittest.TestCase):
def test_found(self):
arr = [2, 3, 4, 10, 40]
target = 10
expected_index = 3
self.assertEqual(binary_search(arr, target), expected_index)
def test_not_found(self):
arr = [2, 3, 4, 10, 40]
target = 20
expected_index = -1
self.assertEqual(binary_search(arr, target), expected_index)
def test_empty_array(self):
arr = []
target = 10
expected_index = -1
self.assertEqual(binary_search(arr, target), expected_index)
def test_single_element(self):
arr = [1]
target = 1
expected_index = 0
self.assertEqual(binary_search(arr, target), expected_index)
def test_target_at_beginning(self):
arr = [1, 2, 3, 4, 5]
target = 1
expected_index = 0
self.assertEqual(binary_search(arr, target), expected_index)
def test_target_at_end(self):
arr = [1, 2, 3, 4, 5]
target = 5
expected_index = 4
self.assertEqual(binary_search(arr, target), expected_index)
if __name__ == '__main__':
unittest.main()