Week 2#

Exercise 1 - Checking primes#

def is_prime(n):
    print(type(n))
    if not isinstance(n, int):
        raise ValueError(f'Expected int: {type(n)}')
    elif n < 0:
        raise ValueError(f'Expected positive int: {n}')
    elif n in [1, 2]:
        return True
    for i in range(2, n):
        if n%i == 0:
            return False

    return True
import pytest
from prime import is_prime

def test_is_prime_with_neg_int_raise_value_error():
    with pytest.raises(ValueError):
        is_prime(-1)

def test_is_prime_with_non_int_raise_value_error():
    for value in ('str', 1.1, {}, []):
        with pytest.raises(ValueError):
            is_prime(value)

def test_is_prime_primes():
    for prime in (1, 2, 3, 5, 7, 11, 13):
        assert is_prime(prime)

def test_is_prime_non_primes():
    for non_prime in (4, 6, 9, 12, 15):
        assert not is_prime(non_prime)
» pytest -v test_prime.py
collected 4 items

test_prime.py::test_is_prime_with_neg_int_raise_value_error PASSED                                               [ 25%]
test_prime.py::test_is_prime_with_non_int_raise_value_error PASSED                                               [ 50%]
test_prime.py::test_is_prime_primes PASSED                                                                       [ 75%]
test_prime.py::test_is_prime_non_primes PASSED                                                                   [100%]

============================================== 4 passed in 0.09 seconds ===============================================

Exercise 2 - Writing Bubble Sort#

def bubble_sort(lst):
    if not isinstance(lst, list):
        raise ValueError(f'Expected list: {type(lst)}')
    elif len(lst) < 2:
        return lst.copy()

    copy = lst.copy()

    for i in range(len(lst), 1, -1):
        for j in range(i-1):
            if copy[j+1] > copy[j]:
                copy[j], copy[j+1] = copy[j+1], copy[j]

    return copy

Exercise 3 - Testing Bubble Sort#

import pytest
from bubble_sort import bubble_sort

def test_bubble_sort_correct():
    unordered = [5, 3, 2, 8, 2, 7, 9, 2]
    expected = sorted(unordered, reverse=True)

    assert expected == bubble_sort(unordered)

def test_bubble_sort_not_list_raise_value_error():
    for value in ('str', 1.1, {}, 1, True):
        with pytest.raises(ValueError):
            bubble_sort(value)

def test_bubble_sort_empty_list_return_empty_list():
    assert [] == bubble_sort([])

def test_bubble_sort_one_element_return_same_element_list():
    assert [1] == bubble_sort([1])

def test_bubble_sort_original_list_unaltered():
    original = [1, 4, 2, 5, 6]
    expected = original.copy()
    ordered = bubble_sort(original)
    assert original == expected
» pytest -v test_bubble_sort.py
collected 5 items

test_bubble_sort.py::test_bubble_sort_correct PASSED                                                             [ 20%]
test_bubble_sort.py::test_bubble_sort_not_list_raise_value_error PASSED                                          [ 40%]
test_bubble_sort.py::test_bubble_sort_empty_list_return_empty_list PASSED                                        [ 60%]
test_bubble_sort.py::test_bubble_sort_one_element_return_same_element_list PASSED                                [ 80%]
test_bubble_sort.py::test_bubble_sort_original_list_unaltered PASSED                                             [100%]

============================================== 5 passed in 0.14 seconds ===============================================

Exercise 4 - Testing a median function#

def median(data):
    """Returns the median of a dataset."""
    data.sort()
    return data[len(data)//2]

print(median([11, 3, 1, 5, 3]))
3
def test_median_one_element_list():
    assert 1 == median([1])

def test_median_two_element_list():
    lst = [2, 3]
    expected = 2.5
    actual = median(lst)
    assert expected == actual
» pytest -v test_median.py
collected 2 items

test_median.py::test_median_one_element_list PASSED                                                              [ 50%]
test_median.py::test_median_two_element_list FAILED                                                              [100%]

====================================================== FAILURES =======================================================
____________________________________________ test_median_two_element_list _____________________________________________

    def test_median_two_element_list():
        lst = [2, 3]
        expected = 2.5
        actual = median(lst)
>       assert expected == actual
E       assert 2.5 == 3
E         -2.5
E         +3

test_median.py:11: AssertionError
========================================= 1 failed, 1 passed in 0.35 seconds ==========================================
def median(data):
    """Returns the median of a dataset."""
    data.sort()
    if len(data) % 2 != 0:
        return data[len(data)//2]
    else:
        middle_elements = data[len(data)//2 - 1], data[len(data)//2]
        return sum(middle_elements)/2
» pytest -v test_median.py
collected 2 items

test_median.py::test_median_one_element_list PASSED                                                              [ 50%]
test_median.py::test_median_two_element_list PASSED                                                              [100%]

============================================== 2 passed in 0.51 seconds ===============================================
def test_median_original_list_unaltered():
    lst = [2, 4, 6]
    expected = lst.copy()
    med = median(lst)
    assert lst == expected
» pytest -v test_median.py
collected 3 items

test_median.py::test_median_one_element_list PASSED                                                              [ 33%]
test_median.py::test_median_two_element_list PASSED                                                              [ 66%]
test_median.py::test_median_original_list_unaltered PASSED                                                       [100%]

============================================== 3 passed in 0.16 seconds ===============================================
def test_median_empty_list_raise_value_error():
    with pytest.raises(ValueError):
        median([])

def test_median_empty_tuple_raise_value_error():
    with pytest.raises(ValueError):
        median(())
» pytest -v test_median.py
collected 5 items

test_median.py::test_median_one_element_list PASSED                                                              [ 20%]
test_median.py::test_median_two_element_list PASSED                                                              [ 40%]
test_median.py::test_median_original_list_unaltered PASSED                                                       [ 60%]
test_median.py::test_median_empty_list_raise_value_error FAILED                                                  [ 80%]
test_median.py::test_median_empty_tuple_raise_value_error FAILED                                                 [100%]

====================================================== FAILURES =======================================================
______________________________________ test_median_empty_list_raise_value_error _______________________________________

    def test_median_empty_list_raise_value_error():
        with pytest.raises(ValueError):
>           median([])

test_median.py:22:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

data = []

    def median(data):
        """Returns the median of a dataset."""
        data.sort()
        if len(data) % 2 != 0:
            return data[len(data)//2]
        else:
>           middle_elements = data[len(data)//2 - 1], data[len(data)//2]
E           IndexError: list index out of range

median.py:24: IndexError
______________________________________ test_median_empty_tuple_raise_value_error ______________________________________

    def test_median_empty_tuple_raise_value_error():
        with pytest.raises(ValueError):
>           median(())

test_median.py:26:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

data = ()

    def median(data):
        """Returns the median of a dataset."""
>       data.sort()
E       AttributeError: 'tuple' object has no attribute 'sort'

median.py:20: AttributeError
========================================= 2 failed, 3 passed in 0.24 seconds ==========================================
def median(data):
    """Returns the median of a dataset."""
    if len(data) == 0:
        raise ValueError('data cannot be empty')
    data.sort()
    if len(data) % 2 != 0:
        return data[len(data)//2]
    else:
        middle_elements = data[len(data)//2 - 1], data[len(data)//2]
        return sum(middle_elements)/2
» pytest -v test_median.py
collected 5 items

test_median.py::test_median_one_element_list PASSED                                                              [ 20%]
test_median.py::test_median_two_element_list PASSED                                                              [ 40%]
test_median.py::test_median_original_list_unaltered PASSED                                                       [ 60%]
test_median.py::test_median_empty_list_raise_value_error PASSED                                                  [ 80%]
test_median.py::test_median_empty_tuple_raise_value_error PASSED                                                 [100%]

============================================== 5 passed in 0.08 seconds ===============================================