lundi 22 janvier 2018

Testing Django view: how can we know if catched exception was actually raised?

I want to test if exceptions in my views are raised when expected. The "issue" I am facing with is that I am using try and except statements in my view, so I actually catch those exceptions (in order to do some stuff when they are raised).

My question is the following: how can I test if one expected exception was raised, if it was catched in my except statement?

For instance:

myviews.py

class SomeView(LoginRequiredMixin, CreateView):
    model = models.MyModel
    template_name = "my_template.html"
    form_class = forms.MyForm       
    def form_valid(self, form):
        try:
             # normal stuff here
        except Exception1 as e:
             # some other stuff here
             print("Exception1 occured: ", e)
             messages.error(self.request, "Message1"
        except Exception2 as e:
             # some other stuff here
             print("Exception2 occured: ", e)
             messages.error(self.request, "Message2")
        except Exception as e:
             # some other stuff here
             print("Something unexpected occured! ", e)
             messages.error(self.request, "Message_unexpected")

mytests.py

def test_SomeView(self):

    # test: everything must works just fine
    form_data = some_valid_data
    response = self.client.post("some_url", form_data)
    self.assertEqual(response.status_code, 200)

    # test: Exception1 should be raised in SomeView
    form_data = some_NOT_valid_data # on purpose
    # below, I want to know that Exception1 was raised (then catched)
    # I know what I wrote does not work as expected, but I do not know what to do!
    # I precise I do not want to use form validation/error
    self.assertRaises(
        Exception1,
        lambda: self.client.post("some_url"), form_data)
    )

Many thanks for your help!

Aucun commentaire:

Enregistrer un commentaire