Latest / Talk Python To Me / #287: Testing without dependencies, mocking in Python
Transcript
- 0:00We know our tests should be relatively independent from other parts of the system.
- 0:03For example, running a test shouldn't generally call a credit card processing API and talk to a database
- 0:09when our goal is just to test the argument validation.
- 0:12And yet, your method that you want to test, it does all three of those things and more.
- 0:17What do you do?
- 0:18Some languages use elaborate dependency passing mechanisms and frameworks
- 0:23that go under the banner of inversion of control and dependency injection.
- 0:27In Python, we do sometimes have that, but it's much more common to just temporarily redefine
- 0:33what those two functions do using patching and mocking.
- 0:36On this episode, we welcome back Annalena Popkas to talk us through the whole spectrum of
- 0:42test doubles, dummies, mocks, and more.
- 0:44This is Talk Python To Me, episode 287, recorded August 24th, 2020.
- 0:50Welcome to Talk Python To Me, a weekly podcast on Python, the language, the libraries, the
- 1:08ecosystem, and the personalities.
- 1:09This is your host, Michael Kennedy.
- 1:11Follow me on Twitter, where I'm @mkennedy.
- 1:13Keep up with the show and listen to past episodes at talkpython.fm.
- 1:17And follow the show on Twitter via at talkpython.
- 1:20This episode is brought to you by Linode and monday.com.
- 1:23Please check out what they're offering during their segments.
- 1:25It really helps support the show.
- 1:28Do you want to learn Python, but you can't bear to subscribe to yet another service?
- 1:32At Talk Python Training, we hate subscriptions too.
- 1:36That's why our course bundle gives you full access to the entire library of courses for
- 1:40one fair price.
- 1:41That's right.
- 1:42With the course bundle, you save 70% off the full price of our courses, and you own them
- 1:47all forever.
- 1:48That includes courses published at the time of the purchase, as well as courses released
- 1:53within about a year of the bundle.
- 1:54So stop subscribing and start learning at talkpython.fm/everything.
- 2:00Anna Lena, welcome back to Talk Python To Me.
- 2:03Thanks.
- 2:04It's great to be back.
- 2:05Yeah, it's super to have you back.
- 2:06Last time we spoke about 100 days of code and Harry Potter and things like that, if I recall
- 2:13correctly.
- 2:13Is that right?
- 2:14Yes, that's correct.
- 2:16Yeah, that was really fun.
- 2:17And that was right at the height of the 100 days of code when everyone was really using
- 2:21that to learn to code.
- 2:22And so you had this unusual, but I think really engaging way of taking code and making it not
- 2:27just silly technical stuff, but making it this fun Harry Potter adventure world.
- 2:31Yeah, I still love that approach.
- 2:33So I always try to find something I'm passionate about and then trying to use it to learn.
- 2:39Yeah, excellent.
- 2:40So now we're going to come back and talk about writing code that we're more likely to be
- 2:46sure that works, testing code and using mocking and all that.
- 2:49But when we spoke last time, you were a, was it an internship at Microsoft?
- 2:55What kind of?
- 2:56It's something in between.
- 2:57It was called an AI residency at Microsoft Research in Cambridge in the UK.
- 3:02So it's like an intensive one year program where you learn a lot about how to apply machine
- 3:07learning, how to become a great research engineer.
- 3:09So cool.
- 3:10It's like, yeah, it's more than an internship, like a really long extended internship.
- 3:16I'm sure that was a really fun project experience.
- 3:19Oh yeah, it was amazing.
- 3:21Also the place Microsoft Research in Cambridge is just great.
- 3:25I really loved it there.
- 3:26Yeah, I can imagine.
- 3:28And how about now?
- 3:30What are you up to now?
- 3:31Yeah, so I finished the residency and I moved back to Germany and joined a German company
- 3:35called InnoVex.
- 3:36I also like it here a lot.
- 3:38And I'm working as a machine learning engineer, similar to what I did at Microsoft Research,
- 3:43but not so research heavy.
- 3:46So I'm doing more production code or production work.
- 3:50And I'm currently working in a pure data engineering project.
- 3:53So I've been learning a lot more about the work that comes before actually applying the machine
- 3:57learning algorithms, which is also very interesting.
- 4:00Yeah.
- 4:00So I would guess that involves a lot of pandas, a lot of cleaning up data, like getting stuff
- 4:04in the right format.
- 4:05Yes.
- 4:07Yeah.
- 4:07And then we give the data to the data scientists, which can just use the clean data to do their
- 4:12nice machine learning stuff.
- 4:14Yeah, you make them look good.
- 4:16You're like, oh, here, you just feed this over and it works great.
- 4:18Like it didn't start out that way.
- 4:21What kind of problems are you trying to solve or answer?
- 4:23It really depends on what the customer wants.
- 4:26So it can go from supply chain management and apply machine learning there to right now in
- 4:32the cloud, where we just create kind of a data lake in the Google cloud, where we have different
- 4:38data sources that have to be processed and brought together and all the other stuff.
- 4:44So there's just a lot going on.
- 4:46It's a very huge project with several teams working on it.
- 4:49Wow.
- 4:49Yeah.
- 4:50It sounds really fun.
- 4:51And it sounds like one of these big data projects that people talk about a lot, but not
- 4:55that many people actually do.
- 4:56Yeah.
- 4:57And it's also very interesting for me to see this other side.
- 5:00I've been working on machine learning for most of my computer science life.
- 5:04So seeing something different is also always very nice.
- 5:08Yeah, absolutely.
- 5:09And you also have some project going on in your spare time, yeah?
- 5:12Yes, exactly.
- 5:13So Kai Macht Schule.
- 5:15Yeah, it's I think like it's a German project.
- 5:19I'm doing voluntary work there.
- 5:21It's called Kai Macht Schule.
- 5:22That's like, I think you could translate it as AI goes to school.
- 5:27Yeah, where we teach AI and machine learning skills to kids in German schools.
- 5:31So we do classes usually on site, but now online due to the COVID crisis.
- 5:37And yeah, it was somewhat similar to what you talked about in the last episode or some recent
- 5:43episode with Nick Winter on Code Combat.
- 5:45Yeah, Code Combat is really a fun thing for kids as well.
- 5:49I think that's super neat what they're doing.
- 5:51I want to try it as well, even if I know how to write code in Python.
- 5:55It sounded so much fun.
- 5:56Yeah, it's really neat.
- 5:58I really enjoyed just kind of poking around with it and seeing it's, again, kind of like
- 6:03your Harry Potter world.
- 6:04It's a very different way to present programming to kids where you still type.
- 6:08It doesn't feel like the burden of being exactly right.
- 6:11You can kind of type it wrong and it'll mostly correct it for you.
- 6:15So it's pretty interesting.
- 6:16So with this project, you're teaching kids AI and machine learning.
- 6:21What does that even look like?
- 6:22What kind of stuff are you teaching them?
- 6:24What do they get when they're building little libraries and so on?
- 6:27Yeah.
- 6:27So we try different approaches.
- 6:29We always have a bit of theory.
- 6:31So what is AI?
- 6:33How does it work?
- 6:34We also have a part on the ethics behind AI, which I think is really important.
- 6:39And there's also some practical exercises with Jupyter Notebooks.
- 6:43Before we used an approach was where you have these blocks of programming parts, which you
- 6:49can stick together, like the for loops and so on.
- 6:52But we didn't like that so much.
- 6:54So right now we are using Jupyter Notebooks.
- 6:57And I think it's amazing since right now there's one, it's called KI Camp.
- 7:01It's like a four-day course.
- 7:02And the youngest one is in fifth grade.
- 7:06So it's like 11 or 12.
- 7:08And the oldest one is just about to graduate.
- 7:10And it's so nice to see these kids fascinated by this topic.
- 7:14Yeah.
- 7:15It's definitely going to give them a leg up, learn these types of things early and know
- 7:19about them and just to learn about Jupyter and computational thinking at all.
- 7:23Yeah.
- 7:23And Germany is also really not so good with the computer science work in school.
- 7:28I think in the US you are much better with teaching kids how to code in school already.
- 7:34For German kids, it's really hard to get to know AI or to find somewhat a way to get familiar
- 7:41with the topic without going out there and looking for yourself what's out on the internet.
- 7:48Yeah.
- 7:48There's the small percentage of kids who will do that.
- 7:51They'll go find it themselves.
- 7:51But the majority don't even know they would be interested until they get exposed to it.
- 7:56Exactly.
- 7:56Yeah.
- 7:57It was the same for me.
- 7:58So that's why I'm really passionate about this project.
- 8:01Yeah.
- 8:01Awesome.
- 8:02And you've definitely taken it quite far what you're doing these days.
- 8:04That's definitely the pinnacle.
- 8:06It's great.
- 8:06All right.
- 8:07Well, let's focus on our main topic for a little while on mocking.
- 8:12So how'd you get interested in it?
- 8:14How'd you get started?
- 8:14Yeah.
- 8:15So I stumbled upon this topic a few months back when I started working in this data engineering
- 8:20project I was just talking about.
- 8:21And we have lots of production code there.
- 8:24And I never heard of mocking before.
- 8:26So it was the first time I used it.
- 8:28And since then, I've been using it in almost all of the tests I write.
- 8:32It's a very controversial topic.
- 8:34So I watched quite a few PyCon talks on it and read quite a few blog posts.
- 8:39And yeah, it's just a big but very interesting thing to talk about.
- 8:45Yeah.
- 8:45So I think one of the controversies has to do with you can write your code in certain ways
- 8:50so it's more easy to test or it's harder to test.
- 8:53And some people see mocking as kind of covering over the bad code you've written or something
- 9:00to that effect, right?
- 9:01Hopefully that sort of summarizes it.
- 9:03Yeah, exactly.
- 9:04And I completely understand that.
- 9:06So you shouldn't use mocking to fix your badly written code.
- 9:10So you, of course, you should first think about, is my code good?
- 9:14Do I want to refactor it?
- 9:16Are there changes I can make to make it easier to test?
- 9:20But sometimes it can be a really good tool.
- 9:23I think it's a great tool.
- 9:24I think when it's used in the right ways and right places, it's just what you need.
- 9:28Yes, I agree.
- 9:29Yeah.
- 9:29I mean, Python is so much about the sort of practicality beats purity.
- 9:34You know, it's part of the Zen of Python and all that.
- 9:36And it's just, let's just do what we need to do to make stuff work.
- 9:41And I think one of the examples where this is really different from other languages is in
- 9:45Python, we don't have things like protected variables.
- 9:49We don't have as often like concrete interfaces.
- 9:53We don't have type enforcement, right?
- 9:55Like the thing you passed here must be this interface.
- 9:58And if it's not, we're going to raise an exception.
- 10:00We have type hints, but that's like an editor or like tool helper.
- 10:04It doesn't mean that runtime it's not going to work or it won't compile or whatever.
- 10:08Yeah.
- 10:08Right.
- 10:09And so I feel like mocking and patching is like, it's sort of, it's more embraced in this
- 10:15world where it's like, look, if we just do this little thing, we can avoid all this complexity
- 10:19and all of these design patterns and all of this stuff that technically would be maybe a
- 10:24more official, pure computer sciencey way.
- 10:27But if you look at the stuff that gets built from it, it gets really hard to deal with it
- 10:31and ugly.
- 10:31Yeah.
- 10:32Yeah.
- 10:33I agree.
- 10:33Yeah.
- 10:34I remember I worked on this one project and it was originally written, I think in Java
- 10:39and then converted to C#.
- 10:40And it used, I think every design pattern that you could possibly name.
- 10:44And it used every single thing that used some sort of dependency.
- 10:49It had an interface for that dependency.
- 10:51It would pass that in into the constructor.
- 10:53And then when it created objects, it would pass that further down.
- 10:56And what you ended up with was the entire code that you wrote was all this abstract stuff.
- 11:01And you would look at it like, well, I see all the functions, but I just don't even know
- 11:06where I would go to find out what actually does this.
- 11:09It's just, it was so insanely complicated.
- 11:12So I've seen that far in and I've seen the world where people just go, you know, okay, we're
- 11:17not going to set up all those structures, but we're just going to do a patch like deep down
- 11:21inside of some function call.
- 11:23And if I had to pick one of those two worlds, I would definitely live in the world where
- 11:27we just keep things simple as it's, it was not fun to work on that project in that way.
- 11:31It sounds terrible.
- 11:33Yeah.
- 11:33Yeah.
- 11:34It was like a, probably a six month project.
- 11:36I'm just like, I'm constantly frustrated on this project.
- 11:38So let's, I guess, start at the beginning.
- 11:42Like what is mocking?
- 11:44There's a lot of folks who listen, who come from a sort of scientific background where they
- 11:48haven't done official computer science or they're self-taught.
- 11:51Maybe, maybe this idea is new to them.
- 11:52What is, what's mocking?
- 11:53Yeah.
- 11:54So a mock simulates the existence and behavior of a real object.
- 11:58I guess we can go over a few examples, but if you use mocking, you as a developer can
- 12:04improve the quality of your tests and also test code in a controlled environment.
- 12:08And it's especially useful if you have external dependencies, like if you want to write to a
- 12:13database or do stuff like that.
- 12:15And there's a nice Python library, which is included in unit test, which is called unit
- 12:21test.mock, which can be used for mocking.
- 12:23I think there are also some more specialized libraries out there.
- 12:27I think there's one, especially for mocking date time, but I've never used it.
- 12:32So I'm only using unit test.mock.
- 12:34Yes.
- 12:35I think the one out there called that is called freeze gun.
- 12:38Yes, exactly.
- 12:40Yeah.
- 12:40That's it.
- 12:40Yes.
- 12:41A freeze gun.
- 12:42And that one basically, you know, like you said, allows you to control the date time module.
- 12:48So there's obvious dependencies that you would think of.
- 12:52Like if I have a traditional web application, maybe it calls some API, like my online courses
- 12:58thing.
- 12:58It's going to call Stripe.
- 13:00It's probably going to call MailChimp APIs, does some other stuff.
- 13:03It's going to talk to a database.
- 13:05So when you think about dependencies, you think, okay, database, maybe the file system,
- 13:09external APIs, and those are all things you can mock and you probably want to.
- 13:13But when I first got into this world, one of the things that really surprised me was how
- 13:18hard it is to work with time.
- 13:20If I want to say, I would like to call this thing before, like, let's just say it's e-commerce.
- 13:26Like I want to make sure that this discount code is not expired now.
- 13:29So it gives me the discount, but in a week it will be expired.
- 13:32You know, like that's really hard to deal with.
- 13:34Right.
- 13:35Yeah.
- 13:35I think that's a very good place to use mocking for like, it's a great example for that,
- 13:40where it can be really useful.
- 13:41Yeah.
- 13:42And the alternative, I talked about this dystopian world that I lived in for a while.
- 13:46The alternative would be, you would have to create a fake class that read, like that you
- 13:52used to get what now is, right?
- 13:55Instead of just saying datetime.now, you have to create a class like time provider now, and
- 14:01then everybody has to agree to not use datetime.now, but they'll have to share
- 14:05this other thing that you're going to pass around.
- 14:07And that's just, that's just crazy.
- 14:08Right.
- 14:08Like it makes no sense.
- 14:10Yeah.
- 14:10It's unnecessarily complicated.
- 14:11Yeah.
- 14:12It's just so complicated.
- 14:14And so you can, if you just mock out what now means.
- 14:18That's it.
- 14:18Yeah.
- 14:18Then you're good.
- 14:19It's fixed.
- 14:20Right.
- 14:20So yeah, it's pretty cool.
- 14:22And Freezegun is one of the libraries.
- 14:23I'm sure there's a bunch out there, but that's a cool one for doing this kind of stuff with
- 14:27specifically with time.
- 14:30This portion of Talk Python To Me is brought to you by Linode.
- 14:33Whether you're working on a personal project or managing your enterprise's infrastructure,
- 14:37Linode has the pricing, support, and scale that you need to take your project to the next
- 14:41level.
- 14:42With 11 data centers worldwide, including their newest data center in Sydney, Australia, enterprise
- 14:47grade hardware, S3 compatible storage, and the next generation network, Linode delivers the
- 14:54performance that you expect at a price that you don't.
- 14:56Get started on Linode today with a $20 credit and you get access to native SSD storage, a 40
- 15:02gigabit network, industry leading processors, their revamped cloud manager at cloud.linode.com,
- 15:08root access to your server, along with their newest API and a Python CLI.
- 15:12Just visit talkpython.fm/Linode when creating a new Linode account and you'll automatically
- 15:18get $20 credit for your next project.
- 15:20Oh, and one last thing.
- 15:22They're hiring.
- 15:22Go to linode.com slash careers to find out more.
- 15:26Let them know that we sent you.
- 15:27So you talked about replacing dependencies.
- 15:31I guess give us some more examples.
- 15:34Time is one that maybe doesn't first come up, but what are some of the type of dependencies
- 15:37you all were working with?
- 15:39So I've been working a lot with the Google Cloud client.
- 15:42So where you want to write or either you want to communicate with the Google Cloud with
- 15:46different services there, or you want to write to the storage and you need to someone, you
- 15:52have a client and you want to communicate with the Google Cloud.
- 15:55And that's the part where we mostly use mocking.
- 15:59So to somewhat make sure that we test that the file is written, or at least that we have
- 16:05the correct paths, the correct function call, but we don't actually want to write the file
- 16:10to the Google Cloud every time or remove it.
- 16:13Right.
- 16:14You know, cloud computing, I think it has a really interesting challenge around testing.
- 16:20It just, in a lot of ways, right?
- 16:22Like you don't, if you're going to work with the API, you obviously have to not talk to the
- 16:26real API.
- 16:26You don't really want to create a virtual machine or a Kubernetes node or whatever, but you do
- 16:31want to test that that code's going to work.
- 16:33But at the same time, a lot of times the tests depend on something meaningful coming back.
- 16:37Yeah.
- 16:38Right.
- 16:38There's so much going on in the cloud side that I think it's pretty tricky.
- 16:43Do you guys do anything special there?
- 16:44Like I know in AWS, there's like a fake local AWS type thing you can run.
- 16:49And I know I've talked about it a while ago and I forgot what it's called, but do you guys
- 16:53do anything like that?
- 16:54Not at the moment.
- 16:55I think someone is working on finding ways to improve this since we are using mocking
- 17:00quite a lot, but it's a really complicated and complex thing since we have a huge code base
- 17:06already and you would have to change all the code again.
- 17:08So doing kind of refactoring at this point is always a big deal.
- 17:14But right now we are just...
- 17:16Yeah, it might not even be worth it.
- 17:17Yeah.
- 17:17Yeah.
- 17:18Yeah, exactly.
- 17:19Yeah.
- 17:19And I think there's also something to be said for that, right?
- 17:22Like sometimes it's like we could create a mock or fake or we'll talk about the different
- 17:27terminologies here in a minute.
- 17:28Yeah.
- 17:29But sometimes it's like, you know what?
- 17:31I'm just going to let it ride to the file system.
- 17:33It's not the end of the world.
- 17:34We're going to keep going.
- 17:35One of the really tricky ones I think has to do with data access, right?
- 17:41I'm going to go talk to the database and get this and then I need to get this other thing
- 17:44that's related to that.
- 17:45And I think it's a constant challenge to figure out how much of that you replace and how much
- 17:50of it you just test against the database or test against a file or something.
- 17:54Yeah.
- 17:54It's sometimes difficult to find the right way.
- 17:56Also, if you are working in a team and other like different people have different opinions
- 18:01and like different things, but there's also a middle ground somewhere.
- 18:05Yeah, for sure.
- 18:06Yeah.
- 18:06I could see one person on the team is all about like we have to do it the right way where there's
- 18:11no external dependencies.
- 18:12And the other person's like, we also have to get stuff done.
- 18:14You know, I also have to.
- 18:16I can't spend all my time recreating all of these systems that you're trying to talk
- 18:20to in ways that are sufficiently accurate so that when you call them, the test data comes
- 18:25back, but it's as accurate or realistic enough that you're really getting a meaningful test.
- 18:30So it's tricky.
- 18:31So you have a example class speaking of Harry Potter and all that.
- 18:36Yes.
- 18:37That we're going to use.
- 18:38We're going to kind of build up some ideas.
- 18:40And it's always hard to talk about code in audio format.
- 18:42So we'll keep it simple.
- 18:44But maybe just give us a quick introduction.
- 18:46Yeah.
- 18:47So we have very simple spell class, which where you have just the constructor in the beginning.
- 18:53And a spell has, of course, a name.
- 18:54It has an incantation and a description.
- 18:57So for example, I think there's Accio in Harry Potter, where it moves an object towards the
- 19:05person who is casting the spell.
- 19:08And a description could be what I just said.
- 19:11And then you have the incantation.
- 19:12Yeah, moves object towards person.
- 19:14Yeah, exactly.
- 19:14Exactly.
- 19:15So that would be an example.
- 19:16Okay, cool.
- 19:17All right.
- 19:18So we'll build up on this as we go through these different ideas here.
- 19:21And we've been talking about mocking as if it's all kind of the same.
- 19:26But if you dig into it, there's actually like a spectrum of ways in which you can do mocking.
- 19:32One of those might be, I just, when I call this function, I want it to not write to the
- 19:38log on the file system.
- 19:39And it might be enough that it just doesn't do that.
- 19:41You don't care what it does.
- 19:43It just doesn't do that.
- 19:44On the other hand, there's like very advanced, tricky usage.
- 19:48Like when I call this function, I want to make sure that it checks whether the person is an admin.
- 19:54If I say yes, I want to do one thing.
- 19:56But I want to make sure that it actually always, always calls this function to make sure that it
- 20:00checked for them, even though you couldn't observe that as a side effect.
- 20:04I want to make sure that it's like calling this once and this twice or in this order.
- 20:08Like there's a lot of tricky things.
- 20:10And those feel like very different things.
- 20:12So in the mocking world, there's different names for these things, right?
- 20:16Yes.
- 20:16And there's also disagreement, I guess, about the terminology and also the definitions of
- 20:22these different kinds of mocking behaviors that you can distinguish.
- 20:25Yeah.
- 20:26And it may or may not be useful.
- 20:28Like people can decide how much they care about being very precise about calling it one thing
- 20:33or the other.
- 20:34But yeah, let's talk about it in the fine grained view, just so people get the full exposure
- 20:40and they can decide to ignore the differences if they want, right?
- 20:43Yes, I think that's a good idea.
- 20:45So yeah, I think the overall name or the name for these kinds of mocking behaviors is called
- 20:52test doubles.
- 20:52So there are the fine grained view objects, which are not real, can be either dummies,
- 20:59fakes, stubs, mocks, or spies.
- 21:02And all of these are so-called test doubles.
- 21:05Yeah.
- 21:05And as I just said, these definitions are also controversial.
- 21:09And there are sometimes so different sources describe them slightly differently.
- 21:14But I think it's still possible to get an idea of what they are about.
- 21:19Yeah.
- 21:19Yeah, absolutely.
- 21:20So let's start, I guess, at the simple side of things.
- 21:24I feel like this whole concept has a little bit of a I'm making fun of you thing.
- 21:29So mocking to like insult somebody.
- 21:31And then you've got dummies, you've got fakes.
- 21:34So let's start with the dummies.
- 21:37Yeah, I think the dummies are the easiest to understand.
- 21:40I agree.
- 21:41Yeah.
- 21:41And a dummy is just an object which is passed around, but never actually used.
- 21:46So a dummy is not intended to be used in your tests.
- 21:49And it does not have any effect on the behavior of the test.
- 21:52And an example would be when you have attributes that you need to instantiate a class,
- 21:58but you don't really care about what they are.
- 22:01For example, for the spell class, if you need a spell instance in your tests,
- 22:06but you don't care about the description,
- 22:08then you could just pause in an empty string or write whatever you want to in that string.
- 22:14And that would be then a dummy.
- 22:15Right.
- 22:15If you don't supply it, it's going to crash.
- 22:17Yes.
- 22:18But you don't actually ever use it or care about it.
- 22:21You just have to make it get out of the way and keep working.
- 22:23Yes.
- 22:24Yeah.
- 22:24Okay.
- 22:25So that's dummies.
- 22:27Next up is fakes.
- 22:28Yes.
- 22:29So a fake implements a fake version of a class or method.
- 22:32It has a working implementation, but it takes some kind of shortcut such that it's not suitable
- 22:38for production.
- 22:39And that could be in a memory database.
- 22:42So usually in production, you would have a database that you write your files to.
- 22:47But during testing, you could have some in-memory database that you only use during your tests.
- 22:53Yeah.
- 22:53That makes a lot of sense.
- 22:54And that's definitely one of the tricky things, I think, is databases.
- 22:58The other one that would be really tricky would be, say, an API call.
- 23:03Like, for example, one of the things I have to do in my code is I have to figure out where
- 23:08is this person located physically so that I can pick the right video server to deliver
- 23:14the fastest video to them.
- 23:16And so there's a call to go to the API that tells me where they are based on their IP address,
- 23:21like what country basically they're in.
- 23:23So I can work out what one to send, right?
- 23:26Every time I run a test, I don't want to call that API, right?
- 23:30Yeah.
- 23:30And I don't really...
- 23:31That's also a good example.
- 23:33Yeah.
- 23:33And I mean, probably the test doesn't actually care where it said they were.
- 23:36But it's, you know, it's going to have to have some kind of behavior because it's going
- 23:40to have to return a value so the program works.
- 23:42Like, so maybe I could come up with a mock or a fake specifically that says whenever they
- 23:48ask where they are, they're always in Kansas City.
- 23:51It doesn't matter where they really are.
- 23:52Just tell them it's in Kansas City so that something can happen where the thing keeps working,
- 23:57right?
- 23:57Yes.
- 23:58That's also somewhat a good introduction of the next one, Stubs.
- 24:02Stubs returns.
- 24:04It has some pre-programmed behavior.
- 24:07Most of the times they simply return fixed values or canned data.
- 24:11Like you just said, for example, always return Kansas City.
- 24:14And yeah, let's look at the spell class again.
- 24:18Maybe the spell class could have a method get similar spells, which searches some database
- 24:24and then you would get similar spells back.
- 24:27And this is, of course, quite complex since finding these similar spells will probably be very difficult.
- 24:33And you would.
- 24:34Right.
- 24:34Maybe the real version is running machine learning or some sort of crazy system.
- 24:40And you don't want that to happen all the time, right?
- 24:42Yes.
- 24:43Since it would probably slow down your whole testing.
- 24:45And then you could just replace the real implementation with a stop that returns hard-coded values and would only take a fraction of the time to complete.
- 24:55Yeah.
- 24:55Yeah.
- 24:56That seems like a really good example there.
- 24:58So I don't know.
- 24:59I do have a hard time knowing exactly.
- 25:01Okay.
- 25:02I've got this idea of which one does it fit into.
- 25:04It's almost like a spectrum saying that color is purple and that color is red.
- 25:10What is the color that's purple but sort of towards red?
- 25:13You know what I mean?
- 25:14Yeah.
- 25:15Yeah.
- 25:16Cool.
- 25:17All right.
- 25:17So making our way across this rainbow, I guess, we have mocks.
- 25:21Yeah.
- 25:22So mocks are closely related to stops.
- 25:24And there's this huge stack overflow post on the differences between mocks and stops.
- 25:29And there you can also get a bit of an idea of the controversy surrounding this topic.
- 25:35But yeah.
- 25:36Yeah.
- 25:36And I'll put that link in the show notes so people can find it.
- 25:38Yeah.
- 25:39That's a good idea.
- 25:40So a mock does not have predetermined behavior, which stops have.
- 25:44Instead, it has to be configured.
- 25:46So an important difference between mocks and stops is that a mock records which calls have
- 25:52been executed.
- 25:53So it can be used to verify not only the result.
- 25:56That's something that a stop can do too.
- 25:59But a mock can verify how the result was achieved so that the correct methods have been invoked
- 26:05on the mock object.
- 26:06Yeah.
- 26:06And this is where it starts to get complicated, I think.
- 26:10One of the ideas of just programming in general functions and classes, but also testing is
- 26:16you shouldn't depend upon the internal implementation of a thing when you're testing it or calling
- 26:24it from the outside.
- 26:25So if I have a thing that says register a new user, maybe I want to just check if I give
- 26:30it valid information, it gives me a new user.
- 26:32If I give it like a malformed email, it'll give me an exception, right?
- 26:36Like that would be totally straightforward.
- 26:38But all of a sudden with the this level of mocking, you're like, well, I want to make sure that it checks that the user is not already existing, that this other thing is happening.
- 26:48And then you're getting more and more tied to the internal details of what that piece is doing, which is fine, maybe.
- 26:55But then you change your code.
- 26:56And all of a sudden, all your tests break.
- 26:58You're like, well, now we got to go rewrite these tests because we don't have this thing that we were
- 27:01checking that got called inside and it gets this sort of they kind of get glued together a little bit more, which I think can make maintenance hard.
- 27:10Yeah.
- 27:10Yeah.
- 27:11We had that problem, too.
- 27:12So, yeah, that's something you have to think about, too.
- 27:15But at the same time, there's good uses for this.
- 27:18Like I came up with that admin example, because one of the things that scares me a lot is you've got some protected part of an API or an application or something.
- 27:27And somebody forgets to check whether someone is permitted to go in there.
- 27:32That's really bad if that ever gets discovered.
- 27:34You know what I mean?
- 27:35Like, oh, did we forget to check in the show me all the users and their private information part?
- 27:40We forget to check if you're logged in.
- 27:42Whoops.
- 27:43You know, that kind of stuff could totally happen.
- 27:45And with this, you could say you are going to have a test for every one of these admin pieces that says you checked whether or not they were an admin.
- 27:52Right.
- 27:53That function was called no matter what.
- 27:55Right.
- 27:55Yeah.
- 27:56Yeah.
- 27:56This portion of Talk Python To Me is sponsored by Monday.com.
- 28:02Monday.com is an online platform that powers over 100,000 teams daily work.
- 28:07It's an easy to use, flexible and visual teamwork platform beautifully designed to manage any team, organization or online process.
- 28:15Now, for most of us, we missed our chance to build the first apps ever in the mobile app stores.
- 28:20It was a once in a lifetime opportunity, but it's one that's coming around again.
- 28:25Monday.com is launching their marketplace and running a contest for the best new apps featured right from the get-go.
- 28:31Want to be one of the first in the Monday.com apps marketplace?
- 28:35Start building today.
- 28:36They're even giving away $184,000 in prizes, including three Teslas, 10 MacBooks and more.
- 28:43Build your idea for an app and get in front of hundreds of thousands of users on day one.
- 28:47Start building today by visiting Monday.com slash Python or just click the link in your podcast player's show notes.
- 28:56And so, these mocks, I think that's the thing you could do, right?
- 28:58You could say, like, expect that this was, what is it, assert called once or something like that, right?
- 29:03Yes, there are different kinds of assert calls there.
- 29:05Okay.
- 29:06We can talk about this later as well.
- 29:07So, there is assert called once.
- 29:09You can assert that was called with certain arguments, that it was called not called, that it was called, like, independent of the number of times.
- 29:18So, there are kind of different things you can do.
- 29:21And that can be very helpful.
- 29:22Right.
- 29:23I forgot about that.
- 29:24You have the reverse as well.
- 29:25You can say, I want to make sure in this situation, it never, ever calls this other function.
- 29:29Yeah.
- 29:30Right.
- 29:31Right.
- 29:31Yeah, that's true.
- 29:32That would be another good type of test.
- 29:34Okay.
- 29:34So, that's mocks.
- 29:36And then we have spies, which is next level stuff.
- 29:39Yeah.
- 29:40Yeah.
- 29:40I find them really hard to grasp.
- 29:42So, I haven't used spies yet myself.
- 29:45But from what I read, it's that spies are used to wrap real objects.
- 29:50And by default, they route all the method calls to the original object.
- 29:54So, they somewhat intercept and record all calls that are made to the real object.
- 30:01Yeah.
- 30:01Okay.
- 30:02So, this sounds like you might want to do those verification things that I was talking about, but not actually change the implementation.
- 30:09Just let it do what it's going to do.
- 30:11But you can kind of record that all the stuff was interacted with in certain ways or something like that.
- 30:17Yeah.
- 30:18It's kind of, it's a bit similar to a mock in that sense that you can assert that certain things are called, but it does not replace the original object.
- 30:27That's what mocks are doing.
- 30:29Yeah.
- 30:29One of the tricky things with a lot of these, and the more you use them, the more you have to deal with it is, well, they're going to call this function.
- 30:37So, what are you going to return from them, right?
- 30:39So, if they're going to ask, is admin, well, you have to say, if they call, is admin, return true or return false, right?
- 30:46And so, you have to sort of, at the beginning of your test, you have to configure the mock to say, they're going to try to do these four things to you.
- 30:54Here's the answer.
- 30:55Here's the return value.
- 30:56Throw an exception if they try that or something along those lines.
- 31:00Exactly.
- 31:00Yeah.
- 31:01That said, I think it's, you know, there's certain types of errors you want to test for that are really tricky, right?
- 31:07Like, I want to see a SQL operational error.
- 31:10Like, hmm, how am I going to make it do that without talking to the real database?
- 31:16Well, you could come up with a mock that just says, if they call connect, throw this exception right away, right?
- 31:21Like, that would be a good example, I guess.
- 31:23Definitely.
- 31:24Okay.
- 31:24So, we have this spectrum of mocks, the dummies, the spies, the fakes, and so on.
- 31:30When should we use them?
- 31:31So, you can use a mock.
- 31:33Like, I'm not talking about a mock, not all of the other things, but I guess it depends on whether you want to all call them mocks or not.
- 31:42But, yeah, you would use mocking whenever you don't actually want to call an object.
- 31:46For example, when you have the spell class and you want to, or you have a function in that class that saves some version of the spell, for example, as a JSON file,
- 31:56and you have a function remove, which deletes that file again.
- 32:00Then when you test those methods, you don't actually want to write the file to disk every time the test runs.
- 32:07And the same holds for functions that remove objects.
- 32:11But that's just one example of many things that you, where you could use mocks when you don't actually want to do the operation that you're testing.
- 32:21Yeah.
- 32:21Basically, when any behavior of the system is in the way of you testing it, either that's you just don't want to call an API, or you just don't want to write to the file system, or something like that, right?
- 32:32Yeah.
- 32:33Yeah.
- 32:33I guess the other one is, if you need to reach down inside the system and make it do something unexpected.
- 32:39Like I said, if you want the connect call to throw a SQL exception, it's hard from the outside, potentially, to set it up in that way.
- 32:47But with a mock, you can just say, if they call this function, throw this exception, see how the system deals with it, right?
- 32:52Yeah, that's also a very good use case.
- 32:54Yeah, I think testing errors, a lot of people don't test for errors.
- 32:58I feel like they're like, okay, well, this is what it's supposed to do, so let's test that.
- 33:01And I think testing for the opposite is almost as important.
- 33:05Yeah, definitely.
- 33:06I agree.
- 33:06Yeah, yeah, yeah.
- 33:07Cool.
- 33:09So when I look at mocking, there's actually multiple ways to do mocks, and I honestly don't know when I should be using them.
- 33:16Yeah, so there are three core functionalities in the unit test.mock library.
- 33:20One is the class mock, one is the class magic mock, and then there is the patch function.
- 33:26And those have different properties, but maybe we can just go through them one by one.
- 33:32I think that's the easiest.
- 33:34Yeah, yeah.
- 33:35Well, if you think, okay, I'm going to mock something, you probably would start with the mock class, right?
- 33:38That's where you think you would start.
- 33:40Yeah, I think that's the best start.
- 33:41So you can use the mock class to mock any object, where the mock object, so the class instance, just simulates the object it replaces.
- 33:52And I love this, since it's also kind of magic, since the mock, to achieve this, to really simulate the object, it creates attributes on the fly.
- 34:01So when you, let's say you import the unit test.mock library, and you create an instance of the mock class, and then you can just call some attribute on it.
- 34:11Let's call it fancy attribute.
- 34:12And it was just create a child mock and return it to you.
- 34:17So it would create this fancy attribute on the fly.
- 34:20The same holds for any kind of method, and you can call methods with different kinds of inputs, so you can just do whatever you want to do.
- 34:29And I really like that.
- 34:30I find that really fascinating.
- 34:32Yeah, it's quite interesting.
- 34:33And you don't have to do too much to set it up.
- 34:35You don't have to anticipate everything that's going to happen to it.
- 34:38You just create one, and if people think there's a function there, hey, guess what?
- 34:43All of a sudden, there's a function there.
- 34:45The only part where it gets tricky is where you have to make sure the function returns something so you don't get like, you know, none attribute doesn't have whatever type of errors.
- 34:53Yeah.
- 34:54Yeah.
- 34:54It's really powerful, the mock class, but that also sometimes makes it dangerous to use, since you can really just call in everything on it.
- 35:04And yeah, there's also some problems with it, but I guess we can talk about that separately.
- 35:10Yeah, absolutely.
- 35:11One of the challenges, I think, is, let's say you've got some kind of database class, and you're going to make calls on it.
- 35:19It would be easy to create a mock and say, here's the mock database.
- 35:22You call stuff on it.
- 35:24It's just going to kind of go along with that.
- 35:26The challenge is, how do you provide that through, right?
- 35:29You know, I was talking about that crazy system that everything is passing every dependency everywhere abstractly, right?
- 35:36In this world, you've got to find a way to get the mock down inside the system so that it'll use it in the right place.
- 35:42Yeah.
- 35:43And you have to configure it exactly like you want it to behave.
- 35:46Right.
- 35:47Right.
- 35:47If they call this with these parameters, return this value, right?
- 35:51Yeah, since that's also something I stumbled across in the beginning.
- 35:55So let's say you create a mock object that mocks the JSON library.
- 35:59So you would just have JSON equals mock, where mock is the class.
- 36:04And then you could just call JSON.dumps and give it any kind of argument you want to.
- 36:10But it's not the actual JSON.dumps method.
- 36:14So it has nothing to do with that implementation.
- 36:16And you could just give it any kind of input variables.
- 36:22And that's a bit confusing, I think, at the beginning.
- 36:24You have to understand that when you create a mock object and you haven't configured it yet,
- 36:29it has nothing to do with original function or class you're replacing.
- 36:34That's right.
- 36:35And the dumps, that one's fine, right?
- 36:38There's no problem.
- 36:38You usually don't care in a test what happens.
- 36:41But the reverse, the load, when it loads something, you've got to get something back to work with afterwards, right?
- 36:47Exactly.
- 36:47Yeah, that's tricky.
- 36:48The other thing, though, that you can do with these mocks is you can set a side effect.
- 36:52Yes.
- 36:53Which I think is actually cool.
- 36:54Yeah, you can set all kinds of things.
- 36:56So you can set a return value.
- 36:58We talked about that earlier.
- 36:59But also the exceptions.
- 37:01So when you, for example, want that a certain exception is thrown when you call the mock object, then you can just set a side effect.
- 37:10That's a property of the mock class.
- 37:12And then you can set it to any kind of exception you want.
- 37:16Yeah, that's a really good way to test.
- 37:18If this error happens at this function call, what are we going to do?
- 37:22Yeah, it's great.
- 37:22So we've got, that's the standard mock.
- 37:25And when you call one of these functions, like you said, let's say JSON load us, it'll give you back something, probably, which is another mock.
- 37:34But if you print it out, it'll just say that it's a mock of that.
- 37:38And it has, you know, just be kind of useless, right?
- 37:41Yeah.
- 37:41So the next level up would be to bring in some magic.
- 37:45Yeah.
- 37:45So there is the second class called magic mock, which is actually subclass of the mock class.
- 37:52But it contains all the magic methods pre-created and ready to use.
- 37:57So, for example, if you want to compute the length of an object, then the magic mock could be very useful.
- 38:03Since the dunder len, how do you call that in English?
- 38:08Dunder len, I guess?
- 38:09Len?
- 38:10Yeah.
- 38:10Let's call it dunder len.
- 38:12It's already pre-implemented and ready to use.
- 38:16Yeah.
- 38:16Yeah, exactly.
- 38:17So all the so-called magic methods, dunder stir, dunder len, dunder repper, all those things are there, right?
- 38:24Yes.
- 38:24And usually I use the mock class if I don't need magic methods.
- 38:29And otherwise I use the magic mock.
- 38:32But when you look, for example, a step further and you look at the patch method, that actually returns a magic mock.
- 38:38So you're also fine using the magic mock, but it's then sometimes implementing things that you actually don't need.
- 38:44Right, right.
- 38:45Maybe that makes it a little bit slower.
- 38:47I don't know.
- 38:47I haven't tried, but possibly.
- 38:48Yeah, that might be the case.
- 38:50I also haven't tried it yet.
- 38:52All right.
- 38:53So the one that I end up using directly most often, it's got to be the patch.
- 38:59Unit test.mock.patch, right?
- 39:01This one is the, I'm not going to pass a bunch of things around, but just reach down inside this thing.
- 39:06I know it's going to try to call this function or create one of these things.
- 39:09Just make that at whatever level it's going to be down there.
- 39:12Just make that work.
- 39:13You know, make that go away or make it return this value instead and so on.
- 39:17Yeah, I also mostly use the patch method and I like it because you can be very specific about what you want to actually patch.
- 39:23So it's very easy to see from the patch statement where you're going in the code to change its behavior.
- 39:32And I think I like this being most precise or as precise as possible with the mocking or the patching.
- 39:40Yeah, and I feel like it doesn't force you into these design patterns like I described.
- 39:46Like just explode in complexity and say, well, if you're going to have a dependency that you want to replace, you have to pass the dependencies around so you can pass the mock versions of them.
- 39:54And that's fine when there's one, but then one thing requires two more, which requires four.
- 39:59And it just explodes into like all this stuff, right?
- 40:02And so with patch, you don't have to have the structure of every single possible dependencies passed everywhere it goes.
- 40:09You can just say, if you see this function called or this object created deep down inside, do this instead.
- 40:16Yeah.
- 40:16So that's also actually what the patch function is doing.
- 40:19So it looks up, you give it a path and it looks up the object in this given module and replaces that object with a magic mock.
- 40:27So it's by default a new magic mock, but you can also configure this so you can create some class or then configure the patch statement such that it returns not a magic mock, but an instance of the class that you hand it.
- 40:42Oh, interesting.
- 40:43So you can say, I'm going to get like a little test double like sort of thing that I'm going to create.
- 40:48And if I call this function, it has this little fake implementation or something and just say use that?
- 40:53Yes.
- 40:54So you don't have to use the magic mock.
- 40:56Okay.
- 40:57Yeah, that's pretty cool.
- 40:58Actually, I didn't realize I could do that.
- 40:59There's different ways you can use it.
- 41:01It could be a decorator, context manager, other stuff, right?
- 41:04Yeah.
- 41:04So the syntax in general is that you have patch and then in brackets and as a string, you have package.module.target.
- 41:13And there's a really nice example from one of the PyCon talks from Lisa Roach, I think.
- 41:19It's called demystifying the patch function.
- 41:21I really like that talk.
- 41:22We can also link it in the show notes.
- 41:24Yeah.
- 41:24And yeah, so let's say you have an example file, which is called just example.py.
- 41:30And you have one import statement from db, import dbwrite.
- 41:34So you want to write to some database.
- 41:36And then you have a single function, which is called foo or whatever you want to call it.
- 41:41And it just calls dbwrite and returns the return value that you get from dbwrite.
- 41:47I like this example because it's so simple, but it actually uncovers some tricky bits.
- 41:52Yeah, it brings the point across very well.
- 41:55And it's so easy to understand since you don't actually have to care about how dbwrite is implemented,
- 42:00but you know it writes to database and that's something that you don't want to do in the test.
- 42:04Yeah, exactly.
- 42:05Yeah.
- 42:06So we, in this case, we would want to patch or mock the dbwrite call.
- 42:12And you can do that with a decorator.
- 42:14You can do that with context manager or with manual starting and stopping.
- 42:18And which one you use would depend on the scope.
- 42:22So how the scope looks like that you want the object to be patched in.
- 42:27Yeah.
- 42:28So it seems like there's a couple of ways that are pretty straightforward, kind of comparable.
- 42:32You could do a decorator and say on your test function, put the decorator, say patch this,
- 42:37this object or this function call.
- 42:39Or you could do a context manager inside your test function.
- 42:41And I guess it really depends on how many things are you patching, how complicated is it to set up some of the stuff and so on.
- 42:49But they seem pretty comparable, those two.
- 42:51And the other is I could turn it on and turn it off.
- 42:54But this is a system-wide change of what that function means.
- 42:58And so if for some reason the test fails and you don't have a try finally to turn it off or something like that, it's going to be bad because it'll permanently change what that function means, which maybe you only wanted it for a few.
- 43:09Yeah.
- 43:10But I guess the scenario I see that you might want to do it is like test set up and test tear down.
- 43:14Like for this whole class, we're going to just set it up and no one has to worry about it.
- 43:18You just write all the tests.
- 43:19So maybe that's the turn it on, turn it off scenario.
- 43:22Yeah, I think that was also the scenario where I've seen it.
- 43:26Since then it can be useful.
- 43:28Otherwise, you would always have to apply the patch decorator again or use it to context manager in each test.
- 43:34And that looks very messy.
- 43:35And if you can just do it centrally in a single place, that's, I think, the nicest solution.
- 43:41Yeah, and it can get super complicated about setting these things up because first you're going to call this and it needs to return that value.
- 43:47But if it gets called with other value, then return the, like there's a lot of stuff that can get done on these.
- 43:52And it's, you know, maybe simple for one.
- 43:54But if you have three or four of them, all of a sudden, like there's a lot of setup to do a little test.
- 43:59Yeah.
- 43:59And it can also become messy to have all these patch statements stacked on top of each other.
- 44:05I think two or three are maybe fine, but then it becomes really messy.
- 44:10Yeah.
- 44:11Yeah, absolutely.
- 44:12So I guess I'm starting to come around to the idea of having it just set up in the test setup or maybe a test fixture in pytest or something like that.
- 44:21Yeah, that's also a nice way.
- 44:22Yeah.
- 44:23Another thing that I think is interesting about this example is it seems so simple, but you have to be a little bit aware of how those functions are being used internally.
- 44:33Right.
- 44:33So the import statement in the example that you talked about says from DB import DB write.
- 44:39And you have to explicitly say in a string the full like namespace style name of the thing that it's going to patch.
- 44:46So in this example, you would say example dot DB write.
- 44:50And if you get it wrong, it crashes.
- 44:52Right.
- 44:52Yeah, I think that's what most people find confusing in the beginning.
- 44:57But I think it's great because you start to understand what it means if you import something and what is happening in the program.
- 45:06And I found it very helpful to just inspect then the module and what kind of attributes it has.
- 45:15So it is important to know that you have to patch where the object is looked up.
- 45:20And this might not be the place where it is defined.
- 45:22So if we have this DB write example where you have the from DB import DB write statement in the file example dot pi, then you are importing the DB write function from the DB module.
- 45:37So the consequence is that the example module now knows about the DB write method, but it does not know about DB.
- 45:45So if you patch it, but I think it's nice that you can see that actually.
- 45:51So if you open an IPython shell and you import this example module, then you can call directory.
- 45:58So dear, dir.
- 45:59Yeah.
- 46:00How do you pronounce that?
- 46:01I would say dir, but I could be wrong.
- 46:04Yeah.
- 46:04Dir.
- 46:04Okay.
- 46:05I will trust you on that.
- 46:07So you would call dir example, and then you would see a list of the attributes for this example module.
- 46:13And there you will see DB write and foo, but you won't see DB.
- 46:17So therefore, to mock the call to the DB write function in the test, you would have to patch example dot DB write.
- 46:26Right.
- 46:27And it's tricky because conceptually, what you think you're patching is the DB write thing out of the DB module.
- 46:36So my first thought was, well, that should probably be just DB dot write, but that doesn't work in this case.
- 46:42Yeah.
- 46:42But what's interesting is if they had said import DB, and then in the implementation of foo, they said DB dot DB write, then it would work.
- 46:51And actually, this example where you say example dot DB write, patch that, it would crash and say, well, that thing doesn't have this function, so we can't patch it.
- 46:59And so you have to be a little bit aware of how these are written.
- 47:03And like you said, where they're defined, it does take a little bit of awareness.
- 47:06So I think you can look with dir, which is great.
- 47:09You just also have to just be a little bit aware of what's going on there.
- 47:12Yeah, I think once you wrap your head around it, then it's easy.
- 47:16Once you understand the basic idea and you have used it a few times, then it would become natural or much easier to understand which patch statement you have to use.
- 47:27Yeah, I think we can look at another example where you would not import from DB import DB write, but you would just import the DB module.
- 47:36And then the foo function would call DB dot DB write instead of just DB write.
- 47:42And now the example module knows about DB, but not DB write.
- 47:48So again, if you would call dir on example, you would get DB and foo in the namespace, but you would not have DB write.
- 47:57So now when you patch it, you would either have to use example dot DB dot DB write or just DB dot DB write.
- 48:05And yeah, it can be a bit confusing, but I think that's also the hardest thing to understand.
- 48:13And once you get that, then you have the most important idea.
- 48:17Right.
- 48:17Once you understand it, it's not too bad, I think.
- 48:20But it does.
- 48:20You do have to put some ideas together to figure out what to put there.
- 48:24Yeah.
- 48:25One of the challenges, I think, of the more that you kind of reach inside of things and you make these changes, like we're saying here, your testing can become a little bit harder to maintain.
- 48:36So, for example, suppose we have the first scenario where they had the from DB import DB write.
- 48:40Everything was fine.
- 48:41And then somebody decides we're going to refactor the code to be more explicit and use the namespaces.
- 48:47And then they go change the example pi to use the different types of imports and rewrite the functions to say DB dot DB write versus just the function call.
- 48:55All of a sudden, your test doesn't work anymore.
- 48:57You're like, what is going on here?
- 48:59And that's just the nature of this mocking stuff.
- 49:01Like, as you reach inside to make these changes, you're now somewhat dependent on the structure of the inside.
- 49:08Yeah.
- 49:08Yeah.
- 49:09You always have to keep that in mind when you adapt the code.
- 49:11Yeah.
- 49:12So, I guess maybe try to do as little as possible.
- 49:15I mean, sometimes you have to do it to not talk to Google Cloud or not to charge the credit card for real.
- 49:21But, you know, don't if you can avoid it, do so maybe.
- 49:25I don't know, because it's just one more dependency, right?
- 49:27Yes.
- 49:28Well, what about using mock versus patch?
- 49:31So, I don't think there are any clear rules.
- 49:34At least I have not come across any clear rules.
- 49:37I guess that's similar to the whole topic that it's somewhat controversial.
- 49:43But personally, I mostly use patch, just as you just said.
- 49:47I like it since it's so specific, and I rarely use mock.
- 49:51And I don't think I ever use magic mock specifically.
- 49:54So, I use mock if we have this dependency injection we talked about in the very beginning.
- 50:00For example, if you have a client, and I use clients to interact with Google Cloud,
- 50:07and then I can just, instead of passing in the client, I can just pass in a mock object.
- 50:13But in all the other cases, I use the patch function.
- 50:18Yeah, I would totally, 100% agree with that.
- 50:21And I think in Python, this place where you pass in all of your dependencies,
- 50:27it's less common than other languages.
- 50:29So, I think that naturally makes patch a little more common.
- 50:32Yeah, that might be the reason.
- 50:34Yeah, which is generally a good thing.
- 50:36Also, I think some other languages, it's very hard for them to do this idea of patching.
- 50:41So, they have to pass all their stuff around.
- 50:43So, we've talked a little bit about some of the challenges.
- 50:48And like, if the import statement's like this, you got to mirror that in the way that you write your patch statement.
- 50:53And if it changes, that changes.
- 50:55But there's also some other common problems and some things to keep in mind.
- 50:59You want to run us through those?
- 51:01Yeah, sure.
- 51:01So, we saw that we can configure mock objects.
- 51:04So, we can set the return value, side effects like exceptions and so on.
- 51:09And the fact that the mock objects create attributes and methods on the fly makes them very sensitive to mistakes.
- 51:16So, a typical example is that you misspell something.
- 51:20So, for example, you can call assert called once on a patch or mocked object.
- 51:28And you could just have a spelling mistake there.
- 51:31For example, you could have assert called once with a single S instead of assert called once.
- 51:36But the test will just pass.
- 51:38It won't raise an assertion error because you just created a new method on the mock object that is called assert called once instead of calling the actual function.
- 51:48Yeah, and this is really tricky because the successful behavior is exactly the same as just calling a function that doesn't exist.
- 51:55It's just do nothing.
- 51:56It's fine.
- 51:57But the verification won't happen, right?
- 52:00Because only the verification will happen if you actually call the right one.
- 52:03Yeah.
- 52:04I think also a typical problem is that a mock object does not know the interface of your class.
- 52:10That's also what I tried to explain earlier, that you have to understand that the mock object actually has nothing to do with the class that it replaces.
- 52:19But you have to configure it to behave like your class.
- 52:23So, let's say going back to the spell class, when we called dir on the mocked object, then you can see all the kinds of attributes.
- 52:34So, maybe like if you have IPython open again and you would import the spell class, you would import the patch function from unit test.mock.
- 52:43And then you can just look at the attributes of a mocked spell instance by calling with patch and then spell class.spell as mocked spell.
- 52:52That would just be the name of this mocked object.
- 52:55And then you could print the call of dir on the mocked spell object.
- 53:00And then you would see all these different things that you can use.
- 53:03Assert any call, assert call once, assert call once with, and so on.
- 53:08But you would actually...
- 53:09Yeah, but none of them have anything to do with spell.
- 53:11Yes.
- 53:14So, you wouldn't see all the methods that are included in the spell class, like save, remove, or cast.
- 53:21Of course, you have to cast a spell.
- 53:23Be able to cast a spell.
- 53:24And that can be quite tricky, since it can lead to behavior that you don't want.
- 53:31So, the magic mocked object that's returned by the patch call, which is completely unrelated to the spell class.
- 53:38Yeah.
- 53:39And that's really tricky.
- 53:40So, I've seen spec equals true in various testing things.
- 53:44And I didn't, until just now, really put together what that actually did.
- 53:48So, you can sort of fix that sometimes.
- 53:51Yes.
- 53:52So, some of the problems can be solved, at least those with the spelling mistakes,
- 53:56and also that you want your class to somewhat look like the...
- 54:00Or you want your mock to look somewhat like the class that it's replacing.
- 54:05You can use the spec equals true attribute in the patch call.
- 54:09And this will cause the magic mock to look like the object that is being patched.
- 54:14So, it would cause this misspelled assert call once to raise an exception.
- 54:19And also, you can only call methods with the correct arguments.
- 54:24And you can only call methods that actually exist in the class.
- 54:28Yeah, exactly.
- 54:29So, one of the problems with these mocks could be, inside a function,
- 54:33you're calling something on what you think is the real spell or the data access layer or whatever.
- 54:40And you're calling a function that doesn't exist or you misspelled it.
- 54:43And all of your tests pass because the mock is like, fine.
- 54:48We'll just...
- 54:50You called a function that didn't exist, just like all the others.
- 54:52So, we're just going to return a mock object there.
- 54:55But in production, when it really goes to run and it gets a real thing that has no method there,
- 55:00it's going to crash.
- 55:01So, with the spec equals true, you can be a little more restrictive and catch some of those errors as well, maybe.
- 55:07Yeah.
- 55:08What I find in the beginning when I saw spec equals true, I thought, oh, this is great.
- 55:12Then I just have exactly the thing I'm patching.
- 55:16But it turns out, yeah, almost, that all the attributes you create in the constructor,
- 55:22so in the __init__() call, are not contained in the mocked class in the end.
- 55:27So, that's due to the internal workings of spec and auto spec.
- 55:31And I think there's also spec set.
- 55:34I'm not sure how it works.
- 55:35But when you use that in the end, your mock object does not know about any of this dynamically created attributes.
- 55:44Yeah, really, the only way it would know is either if it disassembled the constructor,
- 55:49which would be kind of weird, or if it actually called the constructor.
- 55:53And those constructors could have side effects like creating files or trying to open a database or whatever, right?
- 55:58So, it can't really do those.
- 56:00So, it can't see them.
- 56:02I guess if you really wanted it to work exactly in that way,
- 56:05you could put all the field definitions as type level, as class level stuff,
- 56:11and then just set them, right?
- 56:13That's not as common in Python.
- 56:14Sometimes it is, sometimes it isn't.
- 56:16But that would be the way to fix it, I guess.
- 56:18Yeah.
- 56:19So, yeah, spec and spec set, like auto spec, spec set, spec,
- 56:23they can be used to solve some of these problems.
- 56:26But you should be aware that they also create problems
- 56:29that you might not be aware of in the beginning.
- 56:32And also, I think it will slow down testing.
- 56:36I have not noticed that really, that it slows them down a lot.
- 56:40But I guess it depends on how much you actually use this functionality.
- 56:43Yeah, yeah, for sure.
- 56:44How much are you doing computationally in your test versus just a whole bunch of creation of mocks to just call one little function?
- 56:51Yeah.
- 56:51I also like besides spec and auto spec and all these other things,
- 56:55there is so much more that you can do with patching and mocking.
- 57:00And it's a huge topic.
- 57:02I guess you can have a whole another podcast about how to prevent mocking or how not to get into mock hell.
- 57:10There's also PyCon talk on this.
- 57:11It's just, yeah, it's a huge topic.
- 57:14Yeah, I can definitely see being a mock hell.
- 57:17I've been on both sides of it.
- 57:18And I think Python has a pretty good middle ground with the ability to patch stuff and not completely rewrite your code to deal with it.
- 57:25Yeah, it's pretty nice.
- 57:27Yeah, I also like using it.
- 57:28Yeah, cool.
- 57:29All right.
- 57:30Well, maybe you want to do a quick wrap up, just summarize all that before we wrap things up?
- 57:35Yes, sure.
- 57:35So I guess we learned that mocking is controversial.
- 57:39And that it should be used with care, not to just fix your badly written code.
- 57:44There are a few ways in which you can design your code such that you don't need patching all the time,
- 57:51like the dependency injection we talked about, where you pass in a mock to client, as an example.
- 57:58Yeah.
- 57:59Oh, yeah.
- 57:59And we talked about these different naming conventions that you should not get confused by them.
- 58:03And maybe if you think it's unnecessarily complicated, then just don't use them.
- 58:09That's also fine.
- 58:10There are people on both sides of the spectrum.
- 58:12Yeah, I've always found that the distinction, trying to be very precise about, oh, no, this is a mock and this is a fake and this is a stub.
- 58:20It doesn't necessarily help you, but it just makes things a little bit messy.
- 58:24Like, you know what you're trying to do?
- 58:26To me, the big distinction is, are you just trying to stop something from being called and maybe just return a value or create a side effect versus are you trying to understand what functions have been called?
- 58:38Like, I want to make sure they always, always call, you know, check for admin or something like that.
- 58:43Right.
- 58:43Like, that to me is a big distinction.
- 58:44Are you trying to observe the behavior or just the outcome?
- 58:47Yeah, I agree.
- 58:48It's also because there are no clear cut definitions.
- 58:51It's all a bit blurry.
- 58:53And the definitions are, in some cases, similar.
- 58:56So, it can be really hard to tear them apart and understand what each one is about.
- 59:02Yeah.
- 59:03So, we also talked about the library, the mocking library, unit test.mock, and the three core functionalities, mock, magic, mock, and patch.
- 59:10And mocking can be or seem confusing in the beginning.
- 59:14But once you understand the basics, for example, that you have to patch where something is used, which might not be where it's defined, then it can be really helpful, especially with production code.
- 59:26And I see that every day.
- 59:27Yeah.
- 59:27Awesome.
- 59:28Well, this is definitely a very powerful tool in the testing tool set.
- 59:33And it can make testing possible where it was impossible or much easier where it was previously really, really hard.
- 59:39So, hopefully, this helps people write more testable code and test more of their code.
- 59:44Yeah.
- 59:44And maybe at least motivate them to look into what mocking is and maybe see that they can use it as well.
- 59:52Absolutely.
- 59:53All right.
- 59:53Before we call the show, you're going to write some Python code, mock out some libraries,
- 59:57what editor do you use?
- 59:58I still use Vim.
- 1:00:00Like, I think I will use it the rest of my life.
- 1:00:03It's hard to get away from it.
- 1:00:05All of my colleagues use PyCharm now, or most of them.
- 1:00:08But yeah, I will still continue using Vim.
- 1:00:11Awesome.
- 1:00:12And the notable PyPI package or library?
- 1:00:14Yeah, I guess I have to say unit test.mock.
- 1:00:17But one thing I really like is that I was always using the IPython debugger for debugging.
- 1:00:24But a few, like a month back, I switched to PDB++.
- 1:00:29Yeah.
- 1:00:30We can also link that in the show notes if people don't know it yet.
- 1:00:33And what I really like it.
- 1:00:34So, it's very easy to install.
- 1:00:36It just wraps around the standard PDB debugger.
- 1:00:40And it has a few nice features.
- 1:00:42I mostly love the sticky command.
- 1:00:44And when you...
- 1:00:46So, you enter the debugger and you type sticky.
- 1:00:48And then you will...
- 1:00:50While you're debugging, you will see the code command stick to the top of the screen.
- 1:00:56And you can really see where you are in your code, stepping through the lines one by one.
- 1:01:00And I find that very helpful when debugging.
- 1:01:03Yeah, that's cool.
- 1:01:04It's like a little bit of a blend between a GUI debugger and a command line style debugger.
- 1:01:10Yeah.
- 1:01:11Yeah, yeah.
- 1:01:11Very good.
- 1:01:12I don't think I've heard of that one.
- 1:01:13That's excellent.
- 1:01:13Thanks.
- 1:01:14All right.
- 1:01:14Final call to action.
- 1:01:15People trying to write some tests.
- 1:01:17They want to get out there.
- 1:01:17They want to use mocking.
- 1:01:18What do they do?
- 1:01:19I think a good start is the documentation.
- 1:01:21I think it's a very comprehensive one.
- 1:01:25There's also a real Python...
- 1:01:28How do you call it?
- 1:01:28Blog post on the topic.
- 1:01:30Yeah.
- 1:01:30I think those two places are good to start.
- 1:01:34I just...
- 1:01:35In general, I like the Python documentation.
- 1:01:36I always...
- 1:01:37In most cases, it's just the best source.
- 1:01:40Yeah.
- 1:01:40Awesome.
- 1:01:41All right.
- 1:01:42Well, thanks again for being on the show and diving into the nuances and all the different
- 1:01:46names in the mocking world.
- 1:01:48It's been fun.
- 1:01:48Yeah.
- 1:01:49Thanks for having me.
- 1:01:50It was fun.
- 1:01:50Yeah.
- 1:01:50It's great to have you back.
- 1:01:51Bye.
- 1:01:52Bye.
- 1:01:53This has been another episode of Talk Python To Me.
- 1:01:56Our guest in this episode was Annalena Popkes.
- 1:01:59And it's been brought to you by Linode and Monday.com.
- 1:02:02Start your next Python project on Linode's state-of-the-art cloud service.
- 1:02:07Just visit talkpython.fm/Linode.
- 1:02:09L-I-N-O-D-E.
- 1:02:11You'll automatically get a $20 credit when you create a new account.
- 1:02:14Build your idea for an app and get it in front of hundreds of thousands of users on day one.
- 1:02:19Start building today at the Monday.com marketplace by visiting Monday.com slash Python.
- 1:02:25Want to level up your Python?
- 1:02:27If you're just getting started, try my Python Jumpstart by Building 10 Apps course.
- 1:02:32Or if you're looking for something more advanced, check out our new async course that digs into
- 1:02:37all the different types of async programming you can do in Python.
- 1:02:40And of course, if you're interested in more than one of these, be sure to check out our
- 1:02:44Everything Bundle.
- 1:02:45It's like a subscription that never expires.
- 1:02:47Be sure to subscribe to the show.
- 1:02:49Open your favorite podcatcher and search for Python.
- 1:02:51We should be right at the top.
- 1:02:52You can also find the iTunes feed at /itunes, the Google Play feed at /play,
- 1:02:57and the direct RSS feed at /rss on talkpython.fm.
- 1:03:01This is your host, Michael Kennedy.
- 1:03:03Thanks so much for listening.
- 1:03:05I really appreciate it.
- 1:03:06Now get out there and write some Python code.
- 1:03:08I'll see you next time.