ajjNV5 / Potential-Study-Tool

NV5 Demand Side Management Interactive Tool
0 stars 1 forks source link

Add unit tests #16

Open mcfink-NV5 opened 3 months ago

mcfink-NV5 commented 3 months ago

We should add a pytest unit test for most (all?) individual functions. These are important when we're collaborating on a big project like this because, before you're starting coding on a feature or issue, you will make a new branch in the repository, pull down the code, and be able to press 'run all tests'. If they all pass, you can comfortably proceed knowing that everything is working as it should. If any of those tests break while you're working on your feature, it can alert you to exactly what bit broke because of your new code. Here is an example of a simple function and its corresponding unit test:

function:

import pandas as pd
from pandas import DataFrame

def read_excel_to_dataframe(file_path: str, sheet_name: str, skiprows: int, nrows: int) -> DataFrame:
    """
    Read a specified range of rows from an Excel sheet into a pandas DataFrame.

    Parameters:
    file_path (str): The path to the Excel file.
    sheet_name (str): The name of the sheet to read from.
    skiprows (int): The number of rows to skip at the beginning.
    nrows (int): The number of rows to read.

    Returns:
    DataFrame: The resulting pandas DataFrame.
    """
    return pd.read_excel(file_path, sheet_name=sheet_name, skiprows=skiprows, nrows=nrows)

unit test:

import pandas as pd
import pytest
from pandas import DataFrame
from your_module import read_excel_to_dataframe  # Replace 'your_module' with the actual module name

@pytest.fixture
def mock_excel_file(tmp_path):
    # Create a mock Excel file
    file_path = tmp_path / "test.xlsx"
    df = pd.DataFrame({
        'A': range(10),
        'B': range(10, 20)
    })
    df.to_excel(file_path, index=False)
    return file_path

def test_read_excel_to_dataframe(mock_excel_file):
    file_path = mock_excel_file
    sheet_name = 'Sheet1'
    skiprows = 0
    nrows = 5

    result = read_excel_to_dataframe(file_path, sheet_name, skiprows, nrows)

    expected = pd.DataFrame({
        'A': range(5),
        'B': range(10, 15)
    })

    pd.testing.assert_frame_equal(result, expected)

We should pair-program some unit tests together -- pytest can sometimes be finicky in VS Code at recognizing where the tests are.