Testing

Installing Pytest

In Repl.it: On the right tab, click the Packages icon. Search for pytest and add it to the project.

At Home: In your terminal type $ pip install pytest

Creating a test file

Your test file should be a separate file from the code you wish to test. Always name your test files according to the following rules:

  1. Start with test_

  2. Include the name of what you are testing

  3. End with .py

Some good examples:

  • test_vector.py

  • test_sleep_in.py

  • test_main.py

Writing tests

In the test file:

  1. Import the function you want to test.

  2. Create a test function starting with test_

  3. Write Assertions to test the function you want to test.

Assertions

Assertions consist of two main parts.

  1. Calling the function you want to test (with arguments)

  2. Comparing the actual result to an expected result.

# a general assertion pattern
assert some_function() == "expected result"

# some specific examples
assert add(5, 7) == 12
assert add(1, 1) == 2

assert say_hello("Dave") == "Hello, Dave."
assert say_hello("Mr. Gallo") == "Hello, Mr. Gallo."

A complete test file

from main import add, say_hello


def test_add():
    assert add(5, 7) == 12
    assert add(1, 1) == 2


def test_say_hello():
    assert say_hello("Dave") == "Hello, Dave."
    assert say_hello("Mr. Gallo") == "Hello, Mr. Gallo."

Running Pytest

In the terminal, just type pytest. Alternatively, if you want to run a single, specific test file, you include the name of that file. For example pytest test_main.py.

Testing Object Attributes

# test_animal.py

from animal import Animal


def test_can_create_animal():
    a = Animal("Homo", "Sapiens")
    assert a.genus == "Homo"
    assert a.species == "Sapiens"
    assert a.happiness == 100
# animal.py

class Animal:
    def __init__(self, genus: str, species: str):
        self.genus = genus
        self.species = species
        self.happiness = 100

Testing Object Methods

# test_animal.py

def test_eat():
    dog = Animal("Canis", "Familiaris")
    dog.eat()
    assert dog.happiness == 150

    dog.eat()
    dog.eat()
    assert dog.happiness == 250

def test_sleep():
    dog = Animal("Canis", "Familiaris")
    dog.sleep(5)
    assert dog.happiness == 160

    # Shouldn't award points for sleeping 0 hours
    cat = Animal("Blah", "Whocares")
    cat.sleep(0)
    assert cat.happiness == 100
# animal.py

class Animal:
    def __init__(self, genus: str, species: str):
        self.genus = genus
        self.species = species
        self.happiness = 100

    def __str__(self) -> str:
        return f"{self.genus} {self.species}"

    def eat(self) -> None:
        self.happiness += 50

    def sleep(self, time: int) -> None:
        if time > 0:
            self.happiness += 2*time + 50