Saša Kalaba
Saša Kalaba

Reputation: 4411

Catching Flask abort status code in tests?

I have an abort() in my flask class based view. I can assert that an abort has been called, but I cannot access the 406 code in my context manager.

views.py

from flask.views import View
from flask import abort

class MyView(View):

    def validate_request(self):
        if self.accept_header not in self.allowed_types:
            abort(406)

tests.py

from werkzeug.exceptions import HTTPException

def test_validate_request(self):
    # Ensure that an invalid accept header type will return a 406

    self.view.accept_header = 'foo/bar'
    with self.assertRaises(HTTPException) as http_error:
        self.view.validate_request()
        self.assertEqual(http_error.???, 406)

Upvotes: 9

Views: 3789

Answers (2)

Saša Kalaba
Saša Kalaba

Reputation: 4411

Ok so I'm an idiot. Can't believe I didn't notice this before. There is an exception object inside the http_error. In my tests I was calling the http_error before calling validate_request, so I missed it. Here is the correct answer:

from werkzeug.exceptions import HTTPException

def test_validate_request(self):
    # Ensure that an invalid accept header type will return a 406

    self.view.accept_header = 'foo/bar'
    with self.assertRaises(HTTPException) as http_error:
        self.view.validate_request()
        self.assertEqual(http_error.exception.code, 406)

P.S. Kids, never code when you're dead tired. :(

Upvotes: 9

syntonym
syntonym

Reputation: 7384

In the werkzeug library http errors codes are saved in HTTPException.None. You can see this yourself in the sourcecode (or for a not None code see e.g. the BadRequest exception).

Upvotes: 1

Related Questions