Skip to main content

Test a FLASK Application

 TEST a FLASK Application


Lets Write a Flask Application with multiple endpoints

app.py

from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/', methods = ['GET'])
def hello():
    message = 'Welcome to Flask Application!'
    return jsonify({'message' : message})


@app.route('/add/task', methods = ['POST'])
def add_task():
    data = request.get_json()

    for d in data:
        title = d.get('title')
        priority = d.get('priority')
        assignto = d.get('assignto')

        if(len(title) == 0 or len(priority) == 0 or len(assignto) == 0):
            message = 'Please fill all the required fields'
            return jsonify({'message' : message}), 400
       
    message = 'Task added successfully'
    return jsonify({'message' : message}), 201

@app.route('/update/task/<int:taskcount>', methods = ['PUT'])
def update_task(taskcount : int):
    data = request.get_json()

    for d in data:
        title = d.get('title')
        priority = d.get('priority')
        assignto = d.get('assignto')

        if(len(title) == 0 or len(priority) == 0 or len(assignto) == 0):
            message = 'Please fill all the required fields'
            return jsonify({'message' : message}), 400
       
        if(taskcount != 1):
            message = 'The taskID you entered does not exist'
            return jsonify({'message' : message}), 404
       
    message = 'Task updated successfully'
    return jsonify({'message' : message}), 200

@app.route('/filter/task/<string:status>', methods = ['GET'])
def filter_task(status : str):

    if(status != 'Backlog'):
        message = 'The status you entered does not exist'
        return jsonify({'message' : message}), 404
   
    response = [{"assignto": "Mark", "id": 2, "priority": "Low", "status": "Backlog", "title": "Resolve Tickets"},
                {"assignto": "David", "id": 3, "priority": "Medium", "status": "Backlog", "title": "DevOps Session"}]
    return jsonify(response), 200


@app.route('/delete/task/<int:taskid>', methods = ['DELETE'])
def delete_task(taskid : int):        
    if(taskid != 1):
        message = 'The task id you entered does not exist'
        return jsonify({'message' : message}), 404
       
    message = 'Deleted successfully'
    return jsonify({'message' : message}), 204

@app.route('/list/task', methods = ['GET'])
def list_task():
    response = [{"assignto": "Mark", "id": 2, "priority": "Low", "status": "Backlog", "title": "Resolve Tickets"},
                {"assignto": "David", "id": 3, "priority": "Medium", "status": "Backlog", "title": "DevOps Session"}]
    return jsonify(response), 200


if __name__ == "__main__":
    app.run()


Now to test this we need to write pytests, lets explore that

test_app.py

import pytest
import json
from app import app


class Test_API:
    app.testing = True
    client = app.test_client()

    def test_home(self):
        '''
        In this method you should send the request to "/" URl
        assert the response status code it should contain "200"
        assert the JSOM response it should contain {"message": "Welcome to kanban Board Flask application hosted on Docker"}
        '''

        url = '/'
        response = self.client.get('/')
        assert response.status_code == 200

        data = json.loads(response.data)
        assert data['message'] == 'Welcome to Flask Application!'

    def test_add_task_without_title(self):
        '''
        In this method you should send the request to "/add/task" URL with the following data payload
        {"title": "", "priority": "Urgent", "assignto": "Mark"}
        assert the response status code it should contain "400"
        assert the JSON response it shold contain {"message": "Please fill all the required fields"}
        '''

        url = '/add/task'
        data = [{"title": "", "priority": "Urgent", "assignto": "Mark"}]
        response = self.client.post(url, json=data)
        assert response.status_code == 400
        data = json.loads(response.data)
        assert data['message'] == 'Please fill all the required fields'

    def test_add_task_without_priority(self):
        '''
        In this method you should send the request to "/add/task" URL with the following data payload
        {"title": "Fix Bug", "priority": "", "assignto": "Mark"}
        assert the response status code it should contain "400"
        assert the JSON response it shold contain {"message": "Please fill all the required fields"}
        '''

        url = '/add/task'
        data = [{"title": "Fix Bug", "priority": "", "assignto": "Mark"}]
        response = self.client.post(url, json=data)
        assert response.status_code == 400
        data = json.loads(response.data)
        assert data['message'] == 'Please fill all the required fields'
   
    def test_add_task_without_assignto(self):
        '''
        In this method you should send the request to "/add/task" URL with the following data payload
        {"title": "Fix Bug", "priority": "Urgent", "assignto": ""}
        assert the response status code it should contain "400"
        assert the JSON response it shold contain {"message": "Please fill all the required fields"}
        '''

        url = '/add/task'
        data = [{"title": "Fix Bug", "priority": "Urgent", "assignto": ""}]
        response = self.client.post(url, json=data)
        assert response.status_code == 400
        data = json.loads(response.data)
        assert data['message'] == 'Please fill all the required fields'

    def test_add_task(self):
        '''
        In this method you should send the request to "/add/task" URL with the following data payload
        {"title": "Fix Bug", "priority": "Urgent", "assignto": "Mark"}
        {"title": "Resolve Ticket", "priority": "Low", "assignto": "John"}
        {"title": "Devops Session", "priority": "Medium", "assignto": "David"}
        assert the response status code it should contain "201"
        assert the JSON response it shold contain {"message": "Task added successfully"}
        '''

        url = '/add/task'
        data = [
            {"title": "Fix Bug", "priority": "Urgent", "assignto": "Mark"},
            {"title": "Resolve Ticket", "priority": "Low", "assignto": "John"},
            {"title": "Devops Session", "priority": "Medium", "assignto": "David"}]
        response = self.client.post(url, json=data)
        assert response.status_code == 201
        data = json.loads(response.data)
        assert data['message'] == 'Task added successfully'

    def test_update_task_without_title(self):
        '''
        In this method you should send the request to "/update/task/1" URL with the following data payload
        {"title": "", "priority": "Urgent", "assignto": "Mark"}
        assert the response status code it should contain "400"
        assert the JSON response it shold contain {"message": "Please fill all the required fields"}
        '''

        url = '/update/task/1'
        data = [{"title": "", "priority": "Urgent", "assignto": "Mark"}]
        response = self.client.put(url, json=data)
        assert response.status_code == 400
        data = json.loads(response.data)
        assert data['message'] == 'Please fill all the required fields'

    def test_update_task_without_priority(self):
        '''
        In this method you should send the request to "/update/task/1" URL with the following data payload
        {"title": "Fix Bug", "priority": "", "assignto": "Mark"}
        assert the response status code it should contain "400"
        assert the JSON response it shold contain {"message": "Please fill all the required fields"}
        '''

        url = '/update/task/1'
        data = [{"title": "Fix Bug", "priority": "", "assignto": "Mark"}]
        response = self.client.put(url, json=data)
        assert response.status_code == 400
        data = json.loads(response.data)
        assert data['message'] == 'Please fill all the required fields'

    def test_update_task_without_assignto(self):
        '''
        In this method you should send the request to "/update/task/1" URL with the following data payload
        {"title": "Fix Bug", "priority": "Urgent", "assignto": ""}
        assert the response status code it should contain "400"
        assert the JSON response it shold contain {"message": "Please fill all the required fields"}
        '''

        url = '/update/task/1'
        data = [{"title": "Fix Bug", "priority": "Urgent", "assignto": ""}]
        response = self.client.put(url, json=data)
        assert response.status_code == 400
        data = json.loads(response.data)
        assert data['message'] == 'Please fill all the required fields'


    def test_update_task(self):
        '''
        In this method you should send the request to "/update/task/5" URL with the following data payload
        {"title": "Fix Bug", "priority": "Urgent", "assignto": "Mark"}
        assert the response status code it should contain "404"
        assert the JSON response it shold contain {"message": "The taskID you entered does not exist"}

        Send the request to "/update/task/1" URL with the following data payload
        {"title": "Fix Bug", "priority": "Urgent", "assignto": "Mark"}
        assert the response status code it should contain "200"
        assert the JSON response it shold contain {"message": "Task updated successfully"}
        '''

        url = '/update/task/5'
        data = [{"title": "Fix Bug", "priority": "Urgent", "assignto": "Mark"}]
        response = self.client.put(url, json=data)
        assert response.status_code == 404
        data = json.loads(response.data)
        assert data['message'] == 'The taskID you entered does not exist'

        url = '/update/task/1'
        data = [{"title": "Fix Bug", "priority": "Urgent", "assignto": "Mark"}]
        response = self.client.put(url, json=data)
        assert response.status_code == 200
        data = json.loads(response.data)
        assert data['message'] == 'Task updated successfully'
   
    def test_filter_task(self):
        '''
        In this method you should send the request to "/filter/task/Done" URL
        assert the response status code it should contain "404"
        assert the JSON response it shold contain {"message": "The status you entered does not exist"}

        Send the request to "/filter/task/Backlog" URL with the following data payload
        assert the response status code it should contain "200"
        assert the JSON response it shold contain
        [{"assignto": "Mark", "id": 2, "priority": "Low", "status": "Backlog", "title": "Resolve Tickets"},
        {"assignto": "David", "id": 3, "priority": "Medium", "status": "Backlog", "title": "DevOps Session"}]
        '''

        url = '/filter/task/Done'
        response = self.client.get(url)
        assert response.status_code == 404
        data = json.loads(response.data)
        assert data['message'] == 'The status you entered does not exist'

        url = '/filter/task/Backlog'
        response = self.client.get(url)
        assert response.status_code == 200
        data = json.loads(response.data)
       
        assert data == [{"assignto": "Mark", "id": 2, "priority": "Low", "status": "Backlog", "title": "Resolve Tickets"},
        {"assignto": "David", "id": 3, "priority": "Medium", "status": "Backlog", "title": "DevOps Session"}]
   

    def test_delete_task(self):
        '''
        In this method you should send the request to "/delete/task/5" URL
        assert the response status code it should contain "404"
        assert the JSON response it shold contain {"message": "The task id you entered does not exist"}

        Send the request to "/delete/task/1" URL
        assert the response status code it should contain "204"
        '''
        url = '/delete/task/5'
        response = self.client.delete(url)
        assert response.status_code == 404
        data = json.loads(response.data)
        assert data["message"] == 'The task id you entered does not exist'

        url = '/delete/task/1'
        response = self.client.delete(url)
        assert response.status_code == 204

    def test_list_task(self):
        '''
        Send the request to "/list/task" URL with the following data payload
        assert the response status code it should contain "200"
        assert the JSON response it shold contain
        [{"assignto": "Mark", "id": 2, "priority": "Low", "status": "Backlog", "title": "Resolve Tickets"},
        {"assignto": "David", "id": 3, "priority": "Medium", "status": "Backlog", "title": "DevOps Session"}]
        '''
        url = '/list/task'
        response = self.client.get(url)
        assert response.status_code == 200
        data = json.loads(response.data)
        assert data == [{"assignto": "Mark", "id": 2, "priority": "Low", "status": "Backlog", "title": "Resolve Tickets"},
        {"assignto": "David", "id": 3, "priority": "Medium", "status": "Backlog", "title": "DevOps Session"}]


to run the the pytest use:

python -m pytest






Comments

Popular posts from this blog

Kubernetes2

  Challenge 2 ConfigMaps: Step-1: To create a ConfigMap named 'fresco-config' with the key-value pair SERVER_URL= https://www.fresco.me , use the following command: kubectl create configmap fresco-config --from-literal=SERVER_URL=https://www.fresco.me To verify if the ConfigMap is created, use the following command: kubectl get configmap fresco-config Step-2: To create an nginx pod with the environmental variable SERVER_URL_ENV using the ConfigMap created earlier, use the following YAML template: apiVersion: v1 kind: Pod metadata: name: fresco-nginx-pod spec: containers: - name: fresco-nginx-container image: nginx env: - name: SERVER_URL_ENV valueFrom: configMapKeyRef: name: fresco-config key: SERVER_URL Deploy the above file you can name it deployment.yaml and use the command: kubectl apply -f deployment.yaml To test your configuration by executing the following command: ...

Mini-Projects for Docker, Docker Swarm

 Mini-Projects for Docker Challenge 1 Welcome to the Docker challenge, your task is to follow the below steps and complete them successfully. Step 1: Pull latest nginx image Step 2: Create a new bridge 'bridge_sample' Step 3: Run a couple of images (Cont1 and Cont2) and connect these to the new bridge created. Now try to ping from cont1 to cont2 to verify connectivity. Step 4: Stop containers Step 5: Remove network, containers, and images using docker commands Note: Execute "history -w" in the terminal before submitting the scenario. Before moving to Answers try to solve yourself... Let's get started... Step 1: Pull latest nginx image docker pull nginx:latest Step 2: Create a new bridge 'bridge_sample' docker network create bridge_sample Step 3: Run containers and connect them to the new bridge docker run -d --name Cont1 --network bridge_sample nginx:latest docker run -d --name Cont2 --netw...

Hands-on with Docker and Docker-Compose

  Hands-on with Docker & Docker-Compose (1) Create a "Dockerfile" inside the path "-/Desktop/Project/docker-docker-compose working-with-multiple-services/app", with base image "python:3.7" to dockerize the given Flask application "app.py" (2) Create another "Dockerfile" inside the path "-/Desktop/Project/docker-docker-compose-working-with-multiple-services/db", with base image "postgres" and configure the environment variables postgres user "abc", postgres password "abc@123", postgres db "postgres". (3) Create one more "Dockerfile" inside the path "-/Desktop/Project/docker-docker-compose-working-with-multiple-services/cache", with base image as "redis". (4) Create a "docker-compose.yml" file inside the path "-/Desktop/Project/docker-docker-compose-working-with-multiple-services" with the below specifications,      (4.1) Create three s...