Search code examples
pythonseleniumdashboardplotly-dash

Dash testing dcc.upload with dash.testing


When writing production ready code we want to be able to automatically test our webapp everytime we update the code. Dash for python allows this through dash.testing. However in my app I upload an excel file utilizing the dcc.Upload() component.

How do I write a test that can send the upload link to this component?


Solution

  • The dcc.Upload component does not allow you to put an id on the that stores the upload link.

    It is easy to work around this by inspecting the upload button/field that you have created with web developer tools. look for the line that contains "<input type=file ... >". in the elements tab. Right click it and press copy xpath and it should give you a relative path like //*[@id="upload-data"]/div/input

    The test case would look like this

    from dash.testing.application_runners import import_app
    def test_xxxx001_upload(dash_duo):
        
        # get app from app.py
        app = import_app("src.app")
        dash_duo.start_server(app)
    
        # find element that contains input link. Utilize the web driver to get the element
        element = dash_duo.driver.find_element_by_xpath('//*[@id="upload-data"]/div/input')
        element.send_keys("C:\\path\\to\\testData.xlsx")
    

    folder structure

    myapp
       --src
          --app.py
          --server.py
          --run.py
       --tests
          --test_app
    

    the use of the dcc.Upload component to create an upload button

    import dash_core_components as dcc
    import dash_html_components as html
    
    html.Div(
        id="file-drop",
        children=[
            dcc.Upload(
                id="upload-data",
                children=html.Div(
                    ["Drag and Drop or ", html.A("Select File"),],
                    id="select-file",
                ),
                multiple=False,
            ),
            html.Div(id="output-data-upload"),
        ],
    )