Unit Testing of the Flask Application Class

I am new to Python, so I apologize in advance if this is a lot for something basic.

I have a situation similar to How to set up a Flask application with SQLAlchemy for testing? For me, the big difference is that, unlike most other Flask examples that I see on the Internet, most of the code that I have for my application is in the class. For some reason, this leads to the malfunctioning of my unit testing. Below is the basic setup of my application and tests:

Application:

from Flask import Flask app = Flask(__name__) class MyApplication(): def __init__(self, param1, param2): app.add_url("/path/<methodParam>", "method1", self.method1, methods=["POST"]) # Initialize the app def getApplication(self): options = # application configuration options middleware = ApplicationMiddleware(app, options) return middleware def method1(self, methodParam): # Does useful stuff that should be tested # More methods, etc. 

Application Tests:

 import unittest from apppackage import MyApplication class ApplicationTestCase(unittest.TestCase): def setUp(self): self.tearDown() param1 = # Param values param2 = # Param values # Other local setup self.app = MyApplication(param1, param2).app.test_client() def tearDown(self): # Clean up tests def test_method1(self): methodParam = # Param value response = self.app.post("path/methodParam") assert(reponse.status_code == 200) 

When I run my tests through

nosetests - with-coverage -cover-package apppackage. / test / test _application.py

I get the following error:

param2) .app.test_client () AttributeError: MyApplication instance has no 'app' attribute

I tried moving the application inside the class declaration, but it is of no use, and it is not like every other unit testing tool I have seen. Why can't my unit tests find the "app" attribute?

+6
source share
1 answer

Your unit test cannot find the app attribute because MyApplication does not have it. There is an app attribute in the module where MyApplication is defined. But these are two separate places.

Perhaps try the following:

 class MyApplication(object): def __init__(self, param1, param2): self.app = Flask(__name__) self.app.add_url("/path/<methodParam>", "method1", self.method1, methods=["POST"]) # Initialize the app 

In addition, you also have a getApplication method with which you are actually not doing anything, but I assume that you are using it for something. Perhaps you really want this in your test ...

 def setUp(self): self.tearDown() param1 = # Param values param2 = # Param values # Other local setup self.app = MyApplication(param1, param2).getApplication().test_client() 
+2
source

Source: https://habr.com/ru/post/918519/


All Articles