How to test a file upload button in a flask app using pytests

Viewed 166

Background:

I am trying to test a very simple flask app. I am having trouble testing the upload button. This uploads a CSV file on the index page (index.html) and then shows a panda table with the data contained in the csv on the page routed to by barrPath.

Problem:

a) How do I test that a file has been successfully uploaded when the button is pressed.

b) Also when the csv file is uploaded how do I test that a panda will be shows. Do I just create a dataframe in the test and then assert that it is a dataframe?

The app is as follows:

import pandas as pd
from werkzeug.utils import secure_filename
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from dominate.tags import img
import requests
import json
import numpy as np

app = Flask(__name__)
Bootstrap(app)



@app.route('/')
def form():
    return render_template('index.html')


@app.route('/barrPath', methods=["POST"])
def barrPath_view():
    if request.method == 'POST':
        # data_file is the name of the file upload field
        f = request.files['data_file']

        # for security - stops a hacker e.g. trying to overwrite system files
        filename = secure_filename(f.filename)

        # save a copy of the uploaded file
        f.save(filename)

        # And then use it ...
        df = pd.read_csv(filename)

        df.style.set_table_styles([{'selector': '',
                                    'props': [('border',
                                               '10px solid yellow')]}])

        return render_template('table_viewer.html', tables=[df.to_html(classes='table table-striped')],
                               titles=df.columns.values)

    return 'Oops, Try again something went wrong!'

The pytest functions:

import pytest
from application.main import app
from io import BytesIO


@pytest.fixture
def client():
    return app.test_client()


def test_form(client):
    resp = client.get('/')
    assert resp.status_code == 200


def test_barrPath_view_post(client):
    resp = client.get('/barrPath')
    assert resp.status_code == 405

index.html

{% extends "layout.html" %}
            {% block content %}
        <div class="inner">
            <form action="/barrPath" method="post" enctype="multipart/form-data",style="text-align:center">
                    <input type="file" name="data_file" />
                    <input type="submit" value="See your data"/>
                </form>
        </div>
            {% endblock %}
0 Answers
Related