Django: Getting Started Transcripts
Chapter: Custom Django Commands
Lecture: Testing management commands

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The management module includes a function for programmatically calling a Django command. This makes testing fairly straightforward.
0:09 Remember when I said don't use print well If you used standard out as I suggested,
0:14 you can take advantage of some output capture when you're testing and with errors you can
0:19 use the assert raises mechanism to check that command errors get raised at the appropriate time Let's go look at some test code,
0:29 I've taken the liberty of writing some test code ahead of time. Let me just open it up. This first method is a helper, call command on line 14
0:41 is a function allowing you to programmatically invoke a Django command. It takes the name of a command to run along with the arguments and options that
0:50 would have been on the command line. One of the supported options that is built in is the ability to provide a buffer
0:57 for standard out and or standard error. On line 12, I'm creating such a buffer,
1:04 it gets added to the options dictionary and then after the command is invoked, the contents in the buffer are returned from my run command helper.
1:13 So when I use the run command method it will invoke a command and return what output the command caused allowing me to assert on the response.
1:23 Line 17-23 are some setup code putting an author and some books in the test database. Lines 25 through 28 test the author command.
1:37 It uses the run command helper and checks that the author's last name shows up in the output.
1:46 Lines 30 through 44, test the book command by passing in different arguments to run command I'm setting the contents of options,
1:54 mimicking command line invocation. Using all equals true is testing the --all argument and it's done in the same way as the author test above.
2:06 Call the run command and then validate the output. Similarly here but instead of passing in all equals true. I'm passing in a book
2:15 ID as an argument to get a single book out And then finally you'll recall that passing in no arguments raises a command error.
2:24 So line 43 creates a context block that expects that exception. If it happens as expected, then the test will pass. All good and a bucket of chicken.


Talk Python's Mastodon Michael Kennedy's Mastodon