Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching Flask abort status code in tests?

Tags:

python

flask

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)
like image 723
Saša Kalaba Avatar asked Jul 13 '16 14:07

Saša Kalaba


2 Answers

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. :(

like image 196
Saša Kalaba Avatar answered Oct 21 '22 02:10

Saša Kalaba


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).

like image 39
syntonym Avatar answered Oct 21 '22 02:10

syntonym