I've used Flask just a few times: once for an internal api, and now as a handler for requests coming from Twilio. One thing that is a problem, however, is writing unit tests that share a MySQL database with a separate Django application. After a lot of trial and error I managed to come up with a solution to using Django tests for your flask application. Flask has its own way of testing, but it was missing too many things for me to be able to use it i.e. completely geared towards using sqlite. In the end the advantages over writing an actual Django app are small, but Flask being smaller and easier to manage than Django, I'm happy with the result. Here is basic solution to upgrading your unit tests with Flask:
from django.core.management import setup_environ
from django.test import TestCase
from your_project import settings
setup_environ(settings)
#NOTE: you may need to add to sys.path to make sure your django project is on your path
from django.core.management import setup_environ
from django.test import TestCase
from your_project import settings
setup_environ(settings)
#NOTE: you may need to add to sys.path to make sure your django project is on your path
class FlaskAppTest(TestCase):
fixtures = ['your_fixtures.json',]
def setUp(self):
self.app = file_with_flask_app.app.test_client()
def test_as_usual(self);
response = self.app.post('/your_flask_url/', data={'your': 'post_parameters',},
headers={'header1': 'header1_value'})
self.assertEqual(response.status_code, 200)
....
def setUp(self):
self.app = file_with_flask_app.app.test_client()
def test_as_usual(self);
response = self.app.post('/your_flask_url/', data={'your': 'post_parameters',},
headers={'header1': 'header1_value'})
self.assertEqual(response.status_code, 200)
....
2 comments:
"Flask has its own way of testing, but it was missing too many things for me to be able to use it i.e. completely geared towards using sqlite."
You have looked at Flask-Testing, haven't you ? Where does it mention only sqlite ?
Hey, thanks for the comment, it was fair. Please don't misunderstand what I meant by saying they only mentioned sqlite. Also, I love Flask and I look to use it every chance I get. What I meant by they only mention sqlite was from here where it uses init_db in the demo app in the unit test setup. Flaskr, as well as what I saw in MiniTwit, use a init_db function that uses an sqlite db.
What I just noticed now looking up flask testing to try and find the page I just mentioned, was an addon for Flask called Flask Testing (duh). I'll check it out and maybe use it for next time :D
Post a Comment