#100DaysOfCode in Python Transcripts
Chapter: Days 10-12: Testing your code with pytest
Lecture: Hello test world - unittest vs pytest
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Right, before diving into writing tests for that program, let's just quickly look at how to write a test with pytest in the first place,
0:08
and how to run it from the command line. And first of all I want to contrast it with unittest, which is in the standard library.
0:17
So here at left you have a super simple program, it's almost ridiculous. But it's Hello name, takes a name and just returns the hello name string.
0:28
And look at the amount of code you have to write in unittest to get a test for that running. Because it's class-based,
0:35
so you have to subclass another class, write a function, and use a self.assert notation so let's show that next.
0:54
Alright, so import unittest, import the program, make a class, inherit from unittest test case, write a method, which needs to start with test
1:04
to be recognized as a valid test, use self.assert equal notation, call the function, and check for hard coded output.
1:14
If the files run as a main script, call the main method on unittest. Right, and it works. And it fills if I change the return, and that's good,
1:27
and notice that pytest can run unittest code, so pytest can be run from the command line, without any switches,
1:37
if you'll look for files that start with test, and run the methods or functions in there that start with test. So that means that I can even
1:47
leave out this main block and it should still work. Right, but here comes the first benefit of pytest is that you can write
1:56
test code in a much shorter way. I don't need unittest, I don't need the class, I can just define functions. They do need to start with test,
2:04
and instead of the self.assert equal, I can just use the classic assert. And this should work. It does not. Self is still in the program
2:17
because it was still in the function. Same output. Make it fail, and here is the second advantage of pytest. The output is much nicer.
2:37
unittest was definitely not bad, but pytest, especially if you go into more complex operations and errors, it's a great debugging tool.
2:48
So look at that. Instead of what was it? Oh that doesn't count one two three, well it was still short because this is an easy program,
2:57
but you can already see that this is way cleaner. So that's the simplest of pytest programs and I just wanted to show you
3:11
how it differs from unittest and how you can run it from the command line. Just the basic steps to get you up and running.