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: ...

Kubernetes1

  Challenge 1 Welcome to the Kubernetes challenge, your task is to follow the below steps and complete them successfully. Environment Setup Check whether docker & minikube are properly installed and configured. Start Minikube and execute this command to sync host docker with minikube docker minikube -p minikube docker-env and eval $(minikube docker-env) Step-1 Create a pod object using kubectl run command with google's sample image: gcr.io/google-samples/kubernetes-bootcamp:v1 and expose it on port 8080, name the pod as firstapp. Check if the pod creation is successful by running the command: kubectl get pod firstapp Step-2 Expose the application to the local VM by creating a Service object of type NodePort. Check if the service is created by running the command: kubectl get svc firstapp Step-3 Create another deployment using a 'YAML' file, create a deployment.yaml file that contains information of the number of replicas and the images to be ...

Docker + Kubernetes + Ansible

  Docker + Kubernetes + Ansible ----------------------------------------------------------------------------------------------------------------------------- Web Application Deployment using Kubernetes and Ansible A Flask application named "application.py" is given in the path Run the given setup.sh file given in the path to install the required dependencies be the challenge. 1. Start Minikube and sync host Docker with Minikube Docker. Note: If you get any errors while starting Minikube, please do try again by running the command to start Minikube. 2. Create a Dockerfile in the path and dockerize the given 'Flask' application as 'webapp-img' using 'python:alpine3.7' as its base image. 3. Create a 'deployment.yml' file in the path to create a Kubernetes deployment object named "web-deployment" with 3 replicas which uses the 'webapp-img' and runs a container named "webapp-container". Add Label "app=webapp" an...