J
J
Jekson2019-04-02 15:26:07
Python
Jekson, 2019-04-02 15:26:07

How to test Flask applications with unittest?

I decided to deal with writing tests for flask applications. Experienced advice needed.
Here is such a simple test that should check if the main page is available.

import unittest
import os
from app import app

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

    def test_main_page(self):
        response = self.app.get('/', content_type='html/text')
        self.assertEqual(response.status_code, 200)

Why am I getting OK even if the server is not running locally. In theory, I need this test, for example, if Nginx fell off on the prod and a 502 error hangs.
And the second question is about testing interaction with the database. I have postgresql, should I test an existing database, or create a new one each time and delete it after the test?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LODIII, 2019-04-02
@LODIII

me to test an existing database

you will not always be able to bring it to its original state, how critical it is.
For example, auto-increment keys, etc.

K
kdvoryashin, 2019-04-03
@kdvoryashin

It is never necessary to test anything on an existing base, this is a bad practice.
During the test, a test database is created, setUp()the method is just for this.
It seems that in new versions of flask they switched to pytest instead of unittest, but the principle is the same in general.
I recommend reading the documentation ( translation ) in more detail, there are very good examples on your question.
As for checking if the main page is available. It's a little bit about unit testing. When you're trying to check if nginx has crashed, it's more about monitoring.
Tests should always be isolated from the production environment. When you run a test, it runs your application separately for the duration of the test.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question