My QA Projects

QA Projects I was involded.

View on GitHub

Searching Algorithms:

Linear Search with unittesting

import unittest

def linear_search(arr, target):
  """Performs a linear search on a list.

  Args:
    arr: The list to search.
    target: The element to search for.

  Returns:
    The index of the target element if found, otherwise -1.
  """
  for i in range(len(arr)):
    if arr[i] == target:
      return i
  return -1

class TestLinearSearch(unittest.TestCase):

  def test_found(self):
    arr = [1, 2, 3, 4, 5]
    target = 3
    expected_index = 2
    self.assertEqual(linear_search(arr, target), expected_index)

  def test_not_found(self):
    arr = [1, 2, 3, 4, 5]
    target = 6
    expected_index = -1
    self.assertEqual(linear_search(arr, target), expected_index)

  def test_empty_list(self):
    arr = []
    target = 5
    expected_index = -1
    self.assertEqual(linear_search(arr, target), expected_index)

  def test_multiple_occurrences(self):
    arr = [1, 2, 3, 3, 4, 5]
    target = 3
    expected_index = 2  # We return the first occurrence
    self.assertEqual(linear_search(arr, target), expected_index)

if __name__ == '__main__':
  unittest.main()
  1. linear_search function:
    • This function implements the linear search algorithm.
    • It iterates through the list arr and returns the index of the target element if found, otherwise -1.
  2. TestLinearSearch class:
    • This class inherits from unittest.TestCase and contains test methods for different scenarios of the linear_search function.
  3. Test Methods:
    • test_found: Checks if the function correctly finds the target element when it’s present in the list.
    • test_not_found: Checks if the function returns -1 when the target is not in the list.
    • test_empty_list: Checks the behavior for an empty list.
    • test_multiple_occurrences: Checks what happens when the target appears multiple times in the list (it should return the index of the first occurrence).
  4. Assertions:
    • Each test method uses self.assertEqual() to compare the actual result from linear_search with the expected_index.
  5. Running the tests:
    • The if __name__ == '__main__': block runs the tests by calling unittest.main().