Building Data-Driven Web Apps with Pyramid and SQLAlchemy Transcripts
Chapter: Testing web apps
Lecture: Fixing the 404 package error
0:00 So we've made it pretty far through this app. We've built the whole web app without running into this error I'm about to show you.
0:08 So, when we were looking at the testing I said oh, I think there is a bug if we come request a package that doesn't exist. So, we can go request photo3
0:16 and it gives us all the details about it. But what if we request photo300? What's going to happen then? Boom, None type has no releases.
0:25 We're not checking that, right? So let's first, before we fix this write a test that says we get proper 404 handling
0:32 and then let's fix it. How do we do that? Well, it's going to look similar to this. But when I put that as 404 and we're going to say we're asking for
0:44 doesn't really matter, but let's say SQLAlchemy missing we don't need any of this test data because we're going to return None, okay?
0:53 We'll call this function and there's going to be nothing to assert, for now. Let's just run the test again.
1:03 None type has no releases, okay, this is the bug. What we want to do, is check and make sure that this actually raises an exception.
1:12 Let's first fix the error in our view model. So let's go over here, now we're going to say if self.package and their releases.
1:24 That looks good to me, I think that'll fix the bug that tiny little bit right there, should fix it.
1:29 Let's try again. Boom. Perfect. So it did make it work and we got this exception, right there. However, it failed our test
1:40 because our test did not expect it. So let's go back to our test, and tell it expect an error right here.
1:47 So we'll come down here and say with self.assertRaises and we give it the exception type, and of those.
1:58 We're going to import that up there, HTTP exceptions like that, and then we're going to run this code here.
2:08 We don't really care what the model is, we just want to say if we pass it here None instead of crashing
2:16 we're going to get an HTTPNotFound error, as an exception. Let's do it. Boom. Passes. So, there you go. We actually found a bug in our little app
2:26 and we fixed it, and now we have a test for it to make sure it's never coming back. Because, if it ever comes back
2:33 this test right here will fail again. Beautifully. By the way, if you're not familiar with this assertRaises
2:39 if, for some reason, this doesn't execute that error if for some reason it passes that block without an error, that itself fails the test.
2:48 Let's just see that real quick. Boom. Failure. We did not get HTTPNotFound, right that's sort of a double negative, but it says
2:58 you told us there should have been an error there was no error, therefore this test fails because you were testing for an error case
3:05 that didn't happen. Now it's back. Perfect.