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