Unit Testing

Unit Testing with Python and Flask is a pretty straightforward activity where you basically have to put yourself in your user’s shoes and test each user story.
So, let’s say for example that you want to test the add user feature of your app, what you want to do is to create a POST request and send this request to the server. Once the server answers you want to verify that the property status of the response object (which will contain a dictionary) contains the string “successful” or whatever you decided.
In the next days I will provide more examples.
Hereby is the code example.
In order to run it you have to use these commands:

pytest -q filename.py

This command will look into the given target file and will search for a class that begins with Test, once it finds that it will run sequentially all of the functions.

import json
import urllib
from pprint import pprint
from urllib import request, parse

import pytest
import sys


class TestApp(object):
    TEST_URL = 'http://0.0.0.0:5001'

    def test_create_user(self):

        values = {
            "data": {
                "email": "cicciopizzo88@gmail.com",
                "password": "test",
                "first_name": "ciccio",
                "last_name": "pizzo",
                "role": "1",
                "address": {
                    "country": "Italy",
                    "address_line": "Test Address, 1998, WXDJI Neverland, Italy",
                    "coordinates": {
                        "lat": "41.0914808",
                        "long": "16.8672337"
                    }
                }
            }

        }

        headers = {
            "Content-Type": "application/json"
        }
        data = json.dumps(values).encode('utf8')
        url = TestApp.TEST_URL + '/api/user'
        req = urllib.request.Request(url, data=data, headers=headers)

        with urllib.request.urlopen(req) as response:
            the_page = response.read()
            the_page = json.loads(the_page)
            assert the_page['status'] == "success"

In order to play with this code I raccomend you to clone the repository http://www.github.com/Deviad/adhesive

Related Post