Python 3 unittest example

Here is a simple example on how to use unittest in python 3.

The directory structure looks like this:

.
`-- py-unittest
    |-- data.csv
    |-- script.py
    `-- script_test.py

./py-unittest/data.csv

This will be the CSV file that we'll have to parse with the python script

Brand;Models
Mercedes-Benz;A class # B class # C class # E class
BMW;1 series # 2 series # 3 series
Audi;A1 # A3 # A4
Opel;Astra# Vectra# Insignia # Zafira

./py-unittest/script_test.py

This will be the unittest script where we'll add the use cases tests for our class.

I recommend to use classes in Python instead of functions. Using classes is much easier to create tests for them and will help you to have a much cleaner code
#!/usr/bin/env python3

import unittest
import os
import sys

sys.path.append(os.path.dirname(os.path.realpath(__file__)))

from script import AutoParser


class TestRequest(unittest.TestCase):
    def test_models(self):
        reg = AutoParser()
        reg.parse(['Mercedes-Benz', 'A class # B class # C class # E class'])

        self.assertEqual(reg.car_models, {'Mercedes-Benz': ['A class', 'B class', 'C class', 'E class']})

    def test_models_with_empty_ending_item(self):
        reg = AutoParser()
        reg.parse(['Mercedes-Benz', 'A class # B class # C class # E class #'])

        self.assertEqual(reg.car_models, {'Mercedes-Benz': ['A class', 'B class', 'C class', 'E class']})

    def test_models_with_another_brand(self):
        reg = AutoParser()
        reg.parse(['Opel', 'Astra# Vectra# Insignia # Zafira'])

        self.assertEqual(reg.car_models, {'Opel': ['Astra', 'Vectra', 'Insignia', 'Zafira']})

    def test_models_with_no_items(self):
        reg = AutoParser()
        reg.parse(['Mercedes-Benz', ''])

        self.assertEqual(reg.car_models, {'Mercedes-Benz': []})

    def test_multiple_models_at_once(self):
        reg = AutoParser()
        reg.parse(['Mercedes-Benz', 'A class # B class # C class # E class'])
        reg.parse(['BMW', '1 series # 2 series # 3 series'])

        self.assertEqual(reg.car_models['Mercedes-Benz'], ['A class', 'B class', 'C class', 'E class'])
        self.assertEqual(reg.car_models['BMW'], ['1 series', '2 series', '3 series'])


if __name__ == '__main__':
    unittest.main()

./py-unittest/script.py

Here is our actual code that we'll write for our application or use case.

#!/usr/bin/env python3

import csv


class AutoParser:
    def __init__(self):
        self.car_models = {}

    def parse(self, mylist):
        raw_models = mylist[1].split('#')

        buffer = []
        for model in raw_models:
            if len(model.strip()) < 1:
                continue
            buffer.append(model.strip())

        self.car_models.update({
            mylist[0].strip(): buffer
        })


if __name__ == '__main__':
    auto = AutoParser()

    # read csv file and extract each row
    with open('./py-unittest/data.csv', 'r', encoding='utf-8') as file:
        file_lines = csv.reader(file, delimiter=';', quotechar='"')

        # skip first line in csv which is the header
        file_lines.__next__()

        for line in file_lines:
            # process each line from csv taken as a python list
            auto.parse(line)

        print(auto.car_models)
This was a simple example. Feel free to add more methods in the class and create a test for each method and cover mode edge use cases