dimanche 10 février 2019

flask/python creating multiple TestCase classes returns 404

While running python's unittest in my Flask application, I am returned a 404 status code when using multiple TestCase classes.

I've tried flask_testing and have gotten similar issues. I opted for unittest because of its greater popularity and availability to find documentation online.

test_global.py

from server import create_app

class Global(unittest.TestCase):

    def setUp(self):
        self.app = create_app(testing=True)
        self.client = self.app.test_client()
        self.client.testing = True

    # tests different cookie redirect
    def test_different_cookie_redirect(self):
        self.client.set_cookie('127.0.0.1', 'lang', 'en')
        response = self.client.get('/fr')

        # this passes
        self.assertEqual(response.status_code, 302)

The above works as intended. If the cookie is different, the page should redirect. The problem happens when I want to add another class.

class Index(unittest.TestCase):

    def setUp(self):
        self.app = create_app(testing=True)
        self.client = self.app.test_client()
        self.client.testing = True

    # tests same cookie redirect
    def test_same_cookie_redirect(self):
        self.client.set_cookie('127.0.0.1',  'lang', 'fr')
        response = self.client.get('/fr')

        # this returns a 404 and fails the test
        self.assertEqual(response.status_code, 200)

This is the error

Traceback (most recent call last):
  File "/test_global.py", line 55, in test_same_cookie_redirect
    self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

If I remove the Global class, the Index test then works and returns a status_code of 200. Why can't both work at the same time?

The reason I opted to have multiple classes is to be able to split my code in different files and run python -m unittest discover to handle them all.

Aucun commentaire:

Enregistrer un commentaire