Running unit tests on the Flaskr training micro-blog in Flask

I cloned a flaskr application from Github and try to follow Testing flask applications . After Bonus: testing the application , I added the test subdirectory to the top-level flaskr , so my directory tree looks like this:

 . β”œβ”€β”€ build β”‚  β”œβ”€β”€ bdist.linux-x86_64 β”‚  └── lib.linux-x86_64-2.7 β”‚  └── flaskr β”‚  β”œβ”€β”€ flaskr.py β”‚  β”œβ”€β”€ __init__.py β”‚  β”œβ”€β”€ schema.sql β”‚  β”œβ”€β”€ static β”‚  β”‚  └── style.css β”‚  └── templates β”‚  β”œβ”€β”€ layout.html β”‚  β”œβ”€β”€ login.html β”‚  └── show_entries.html β”œβ”€β”€ dist β”‚  └── flaskr-0.0.0-py2.7.egg β”œβ”€β”€ flaskr β”‚  β”œβ”€β”€ flaskr.db β”‚  β”œβ”€β”€ flaskr.py β”‚  β”œβ”€β”€ flaskr.pyc β”‚  β”œβ”€β”€ __init__.py β”‚  β”œβ”€β”€ __init__.pyc β”‚  β”œβ”€β”€ schema.sql β”‚  β”œβ”€β”€ static β”‚  β”‚  └── style.css β”‚  └── templates β”‚  β”œβ”€β”€ layout.html β”‚  β”œβ”€β”€ login.html β”‚  └── show_entries.html β”œβ”€β”€ flaskr.egg-info β”‚  β”œβ”€β”€ dependency_links.txt β”‚  β”œβ”€β”€ PKG-INFO β”‚  β”œβ”€β”€ requires.txt β”‚  β”œβ”€β”€ SOURCES.txt β”‚  └── top_level.txt β”œβ”€β”€ MANIFEST.in β”œβ”€β”€ README β”œβ”€β”€ setup.cfg β”œβ”€β”€ setup.py β”œβ”€β”€ test β”‚  └── test_flaskr.py └── tests └── test_flaskr.py 

Note that there are also "built-in" tests in the tests directory; however, I write tests in test_flaskr.py in the tests directory. So far I have tried only one test:

 import os import flaskr import unittest import tempfile class FlaskrTestCase(unittest.TestCase): def setUp(self): self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp() flaskr.app.config['TESTING'] = True self.app = flaskr.app.test_client() with flaskr.app.app_context(): flaskr.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(flaskr.app.config['DATABASE']) def test_empty_db(self): rv = self.app.get('/') assert b'No entries here so far' in rv.data if __name__ == '__main__': unittest.main() 

However, if I try to run this, I get the following error:

 Traceback (most recent call last): File "/home/kurt/dev/scratch/flask/examples/flaskr/test/test_flaskr.py", line 13, in setUp flaskr.init_db() AttributeError: 'module' object has no attribute 'init_db' 

I do not understand this error. My flaskr.py is the same as https://github.com/pallets/flask/blob/master/examples/flaskr/flaskr/flaskr.py and has an init_db function. How can I run unit test?

+6
source share
1 answer

When you import the flaskr package into your script, you can access the variables, functions, etc. declared and defined in flaskr/__init__.py

init_db not defined in flask/__init__.py , the code provided expects init_db be defined in flask/__init__.py .

There are two ways to fix the problem:

  • Replace flaskr.init_db() with flaskr.flaskr.init_db()

  • Modify the import statement in test_flaskr.py as follows:

    Change import flaskr to from flaskr import flaskr

+11
source

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


All Articles