daydreamer
daydreamer

Reputation: 91999

python: How can I test for @unittest.expectedFailure for a specific type of error?

consider this test function

    @unittest.expectedFailure
    def test_add_existing_user(self):
        user = User('test_add_existing_user', 'welcome')
        db.session.add(user)
        db.session.commit()
        self.assertEquals(1, len(User.query.all()))

        db.session.add(User(user.email, 'welcome'))
        db.session.commit()

This test will fail with IntegrityError because user email column has unique=True

This test work fine, but what I need to check if the error my test encountered is IntegrityError, Is there a way to test/validate the error that was raised?

Because Error might occur much before the last statement is executed and then we would have a false positive in our test

Upvotes: 1

Views: 858

Answers (1)

garnertb
garnertb

Reputation: 9584

You can use self.assertRaises to make sure a specific error is raised.

def test_add_existing_user(self):
    """
    Checks that unique constraints return an IntegrityError.
    """
    user = User('test_add_existing_user', 'welcome')
    db.session.add(user)
    db.session.commit()
    self.assertEquals(1, len(User.query.all()))

    db.session.add(User(user.email, 'welcome'))
    self.assertRaises(IntegrityError, db.session.commit)

Upvotes: 3

Related Questions