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 to temporary disabled this action in your tests.
0:11 Let's say you have an online shop, and you need to make sure that when the user buys something,
0:16 you charge their credit card before you send them their order. But you can't charge a random credit card each time you run your tests.
0:25 So instead you can temporarily replace a piece of code responsible for charging a credit card This is called Monkey Patching.
0:33 We replaced the charge method of the stripe object with a mock method that always returns
0:39 a dictionary with status == success that way when we call charge customer later
0:45 In this test, we no longer call the charge method from stripe object because that would normally charge credit card. We call our mocked method,
0:55 and all it does is to return a dictionary with status == success. Then we can continue testing the rest of our code to make sure that an order
1:05 is processed correctly. Notice here that we're passing monkeypatch as an argument to our test,
1:09 thats because monkeypatch is a fixture that comes with pytest.


Talk Python's Mastodon Michael Kennedy's Mastodon