Modern Python Projects Transcripts
Chapter: Testing code
Lecture: Mocking and monkeypatching

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Another common scenario is that you have a function that performs some action and you want
0:05 to temporary disabled this action in your tests.
0:10 Let's say you have an online shop,
0:12 and you need to make sure that when the user buys something,
0:15 you charge their credit card before you send them their order.
0:19 But you can't charge a random credit card each time you run your tests.
0:24 So instead you can temporarily replace a piece of code responsible for charging a credit card
0:29 This is called Monkey Patching.
0:32 We replaced the charge method of the stripe object with a mock method that always returns
0:38 a dictionary with status == success that way when we call charge customer later
0:44 In this test, we no longer call the charge method from stripe object because that
0:49 would normally charge credit card. We call our mocked method,
0:54 and all it does is to return a dictionary with status == success.
1:00 Then we can continue testing the rest of our code to make sure that an order
1:04 is processed correctly. Notice here that we're passing monkeypatch as an argument to our test,
1:08 thats because monkeypatch is a fixture that comes with pytest.