How to test dash app app functions?

I am trying to test some of the functions I have written for my dash app. Not the actual component yet. Here is one of my functions:

import base64
import io
from typing import Any
import pandas as pd

def parse_contents(contents: str, filename: str) -> Any:
    This function takes the contents of the csv or xls file in a string and decodes it using StringIO
     then places it in a pandas dataframe then it returns a html.Div of a datatable and a list of rows
      content with the attributes in a dictionary
        contents: a string of the data within the csv file
        filename: a string of the filename


    df = pd.DataFrame
    content_type, content_string = contents.split(",")
    decoded = base64.b64decode(content_string)
        if "csv" in filename:
            # Assume that the user uploaded a CSV file
            df = pd.read_csv(io.StringIO(decoded.decode("utf-8")))
        elif "xls" in filename:
            # Assume that the user uploaded an Excel file
            df = pd.read_excel(io.BytesIO(decoded))
    except Exception as e:
        return []
    return df.to_dict("records")

I am used to creating a temporary file, creating a simple test dataframe to test my functions but here I am not sure how do I simulate the way that the upload function puts the file data into a string… my callback function uses this function to process the file and then stores it. So I am wondering how do I simulate dcc.upload in my test so that the this parse_contents function can be tested?

any suggestion would be great.

Hi @MauriD

You could check out how Dash tests the dcc.Upload component:

More on dash testing here:

1 Like