1

I have a python file which defines some endpoints using flask each doing some computation and return a JSON (POST method). I want to do unit testing on this in order to do this I want to be able to access the app I created in one python file in another file so I can test my endpoints.

I see a lot of this on the internet :

from source.api import app
from unittest import TestCase

class TestIntegrations(TestCase):
    def setUp(self):
        self.app = app.test_client()

    def test_thing(self):
        response = self.app.get('/')
        assert <make your assertion here>

It doesn't explain how I can define and access my app in another file. This might be a stupid question but I really don't see how.

My app is defined as follows:

from flasgger import Swagger 
from flask import Flask, jsonify, request 
from flask_cors import CORS 
import os

def init_deserializer_restful_api():

# Initiate the Flask app
app = Flask(__name__)
Swagger(app)
CORS(app)

# Handler for deserializer
@app.route("/deserialize", methods=['POST'])
def handle_deserialization_request():
    pass

I have many other end points in this fashion. Should i just do:

import my_file_name

Thanks!!

Espoir Murhabazi
  • 5,973
  • 5
  • 42
  • 73
LoveMeow
  • 3,858
  • 9
  • 44
  • 66

1 Answers1

3

Check out this question: What does if __name__ == "__main__": do?

As long as you have that in your python program, you can both treat it as a module and you can call it directly.

JakeJ
  • 2,361
  • 5
  • 23
  • 35
  • That is, you can import it into other scripts or you can issue "python " from the command line to call it. – JakeJ Feb 05 '18 at 14:44
  • I can't remember enough about Flask right now off the top of my head to be that familiar with what you are referring to, but the above piece of code should be very useful to you / is THE thing to use when making your code work for both module usage and calling from the command line. – JakeJ Feb 05 '18 at 14:49