miguelgrinberg / flasky

Companion code to my O'Reilly book "Flask Web Development", second edition.
MIT License
8.52k stars 4.2k forks source link

Chapter 9: Problem with the user roles tests #523

Closed scottmc42 closed 3 years ago

scottmc42 commented 3 years ago

I'm not quite sure why this is happening. When I try running the test suite, I get a failure with test_user_role

FAIL: test_user_role (test_user_model.UserModelTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/me/python-projects/flasky/tests/test_user_model.py", line 109, in test_user_role
    self.assertTrue(u.can(Permission.FOLLOW))
AssertionError: False is not true

It also fails on COMMENT, and WRITE. Here is the test code:

    def test_user_role(self):
        u = User(email='john@example.com', password='cat')
        self.assertTrue(u.can(Permission.FOLLOW))
        self.assertTrue(u.can(Permission.COMMENT))
        self.assertTrue(u.can(Permission.WRITE))
        self.assertFalse(u.can(Permission.MODERATE))
        self.assertFalse(u.can(Permission.ADMIN))

Yet when I go into a flask shell and try the same commands, everything returns correctly:

>>> u = User(email='john@example.com', password='cat')
>>> u.can(Permission.FOLLOW)
True
>>> u.role.has_permission(Permission.COMMENT)
True
>>> u.can(Permission.ADMIN)
False

So why are the tests failing and saying all permissions are false, yet running the same commands manually would pass?

miguelgrinberg commented 3 years ago

My guess is that the roles are not properly set up in the test database, but they are correct in your development database. The database set up for the tests is done in the setUp() method of the test class. Check there to make sure you are adding the roles.

scottmc42 commented 3 years ago

Ah.. You are correct. I didn't notice that you added the Role.insert_roles() to the setup routine.

Thank you