# Mocks: Do's and Dont's - Julius Seporaitis

Source: https://djangotv.com/videos/django-london/2020/mocks-dos-and-donts-julius-seporaitis/
Date: 2021-04-13
Speakers: Speaker 1, Speaker 2, Speaker 3

## Summary

Julius Seporaitis argues that mocks should be avoided when real dependencies or well-tested fakes are practical, because mocks expose implementation details and make tests brittle when code changes. He recommends using mocks mainly to force dependencies into specific states while testing state-changing code, and explains pitfalls including missing interface checks, confusing use of `ANY`, and patching the wrong name. He also recommends `autospec`, importing modules and calling functions through the module reference, and considering fakes to reduce test maintenance.

## Transcript

### [00:00] Introduction

**Speaker 1:** [00:00] But so we can start. And first of all, thank you for a very interesting talk. Mine is gonna be much shorter. And one thing that I learned apart from expedition is that St. John's Day is celebrated what in one country that I know but more so I didn't know that Anyhow, but going into the talk now, a few abouts. And the mandatory blurb about me is that I work as head of engineering at a startup providing digital marketing recommendations. It operates mostly in the United States but has engineering team in Lithuania Where I am from. Before that,

[00:46] I worked at some better known companies. And if you like to read, I'm trying to come back to regular blogging. Finally, this is my first attempt at public tech talk circuit. So if anyone would like to give feedback, I would be very happy to listen. About the talk itself these slides were part of a bigger deck for internal knowledge sharing. The talk is named Mox, but the gist will be on how mocks relate to test scalability and code maintenance. Most of what I will talk about comes from experience, but there are some parts where I myself am

### [01:31] The Costs of Mocking

**Speaker 1:** [01:31] actually a recent ponder. In the end, I will share a few day-to-day pitfalls related to mocks that may not be obvious to anyone who is starting out. So I hope this talk will have some useful tidbits for varying ranges of experience. And so mocks. In terms of test maintenance, avoid mocks as is reasonably possible. Mocks are deceptively easy to use, but for the long-term maintenance, they will become a source of waste. When it feels like working with the tests takes longer than actually implementing the feature being tested. A good test should verify that

[02:17] given a set of Inputs expected output can be observed. In most cases it should not really care how the code under test implements it So the first problem with using mocks is they leak implementation details into the test. For example, to test that a function A calls some function B, it is very easy to replace function B with a mock. But imagine t 10 tests like that and change comes removing B and it will require abating those ten tests when in fact it actually should not The second problem is evident from the previous example. Using mocks

[03:03] focuses the test case mock on the behavior of the function contract but on the fact that mock is called or not. And if the mocked out function, the B in the previous examples changes, the test won't just won't catch it So what are the alternatives? And well using the real thing underneath the tests would give the most confidence that the thing works, but it is not necessarily always viable due to performance or complexity or some other reason. in which case writing a fake that is tested to have an API matching as closely as possible to the real

### [03:50] Real Dependencies, Fakes, and Stubs

**Speaker 1:** [03:50] service is probably going to save a lot of time for you Stubbs suffer largely from the same problems as mocks. They do very similar things and it is very hard to ensure that they behave as the real system or as a fate. But mocks must serve some purpose because otherwise why would there be a part of the standard library or have popular packages? So let's take a step back and think of what types of code can be under test. And here's one way to answer this at a very high level. state changing code that produces

[04:36] side effects and changes the state of the system. For example, send email, save a record. and non-state changing that most often just returns information like get user or get the file. I hope the idea is quite clear as it will become relevant in the next slide. So the answer to the question before when to use mocks. Well use mocks when you need to have some dependency return a value to get a state changing function into a specific state But only when real or fake dependencies are unavailable. And coming back to the terms from the previous slide, state-changing and non-state-changing functions

### [05:16] When to Use Mocks

**Speaker 1:** [05:25] It does not really make sense to test non-state changing functions using a mock. Consider this that if a function getUser returns user object has database query results mocked out. What does it test? It actually just tests that the mock and return statement were called. And hopefully I planted the seed in your mind about not using mocks, but you just made the trade-off and have to use them. So here are three most common pitfalls. One of the problem with mocks is they do not check the interface contract.

[06:12] This means in the test anything could be passed as a parameter and everyone would be none the wiser until something breaks in production. As you can see the test actually passes, whereas assume this is production Part breaks. That is because the mocked out function doesn't did not just pass parameters However, this issue is an easy fix by passing autospec through to the mock constructor. It will do a basic check if the inputs conform to the function contract in terms of whether positional arguments, required positional arguments are passed, whether no unknown keyword arguments were passed and similar.

### [06:25] Interface Contracts and Autospec

### [07:03] The Any Placeholder Pitfall

**Speaker 1:** [07:03] It will not check tag types though. Second Splitfall and an easy way to spend more time looking at the test output than necessary is by using mock. anyplaceholder so because it shows the difference between two asserted objects. When you test the real data and expected data, it actually compares string representations of those objects. So in this example, you can see that two Differences are reported where C and B and

### [07:48] Mocking the Right Name

**Speaker 1:** [07:48] N E and D. However, in reality, there is only one. C and B because any would match D. And the this example is quite innocent and trivial But anything more complex, very big hierarchical dictionary that you need to just skip parts of, and it may waste a lot of time talking from experience. And finally, the most frequent quote related to Python mocks is probably mock the right thing. It is also one of the easiest to get frustrated about And in here

[08:33] there is an example service module and example test module. And as you can see, the first test function tries to mock the right thing, but it will not work. And the second example marks the function in the module in the service module where it is used and it does work but it prevents reusability of this mock and will most likely lead to a lot of copy-pasted but slightly adjusted code. And the reason this is happening is because at the top of the file, the service. py, The function getScore is imported into the

[09:19] module scope. And when run falls it For all intents and purposes, the get score function is part of the service module, not the project shared dotils. And I won't go into details about Python scope, but if I really recommend Reading the documentation on that and getting familiar with it, a lot of things will become clearer. So, how to fix this Thankfully the solution is quite easy, which means mock the right thing. And it means import module and call the function on the module. I hope you can see the difference here.

### [10:05] Questions and Discussion

**Speaker 1:** [10:05] And the way it the reason it works is because the function is called through a module reference. So instead of function being inside service, we take utils and we call the function on utils. And the example test that you can see here, it actually mocks the function inside the tiles and it actually works. And that is it. And Sorry for a slightly abrupt ending. One thing I would like to acknowledge is that I was actually a big fan of Mox until very recently and converted after reading this excellent recently published book from Google.

[10:51] So the talk somewhat disappointed you. I hope this free book recommendation will pay for it this time many times over. And apart from that, I look forward to your questions and feedback. Thank you.

**Speaker 2:** [11:06] Thank you very much, Hulas. So does anyone want to post a question in the Q<unk>A? Do you have a question, Marco?

**Speaker 3:** [11:21] No.

**Speaker 2:** [11:22] I think it was a very clear talk. I have well one other suggestive resource on that third problem you're talking about, about why your like mock doesn't work. There's actually a blog post that I always point people to by Ned Batchelder called Why Your Mock Doesn't Work. I'll post the link here.

**Speaker 1:** [11:43] Excellent then.

**Speaker 3:** [11:49] Okay while we are waiting for questions oh we have a couple of questions Okay, one suggests from Thomas, no question, but useful tips, thanks. Then Gregor, oh we

**Speaker 2:** [12:07] Tom Granton.

**Speaker 3:** [12:10] Okay, I think

**Speaker 2:** [12:15] I think these are just in the wrong chat box.

**Speaker 3:** [12:22] Oh, from Dump we have what is your preferred testing framework now?

**Speaker 1:** [12:27] PiTest. And in the mocks that I have used, I actually use standard library mock patch utility. However I sort of only recently skimmed back, went back and skimmed through my test box and relearned again, I would say, about Monkey Cache, and I actually find it very useful and very easy to use but like i said i changed my ways very recently and tried to avoid mods and tried to talk my team into using fakes And it did not require a lot of convincing as well.

[13:14] Everyone's seeing the benefits quite quickly

**Speaker 2:** [13:19] Could you give us a little bit more information on what inside this Google software engineering book convinced you?

**Speaker 1:** [13:30] I think the main insight that made me change my mind was that I actually noticed a couple of times where people would do one their intricable feature and then actually spend time changing went to tests and because we have quite high test coverage and I just didn't like it and on at the time I just didn't know how to solve this. And in this book there is a whole chapter dedicated to testing, unit testing, testing, and actually like large integration tests. And one of those chapters had very, very convincing

[14:18] arguments that basically So one way to avoid this requirement to go back and change all the test cases is to use fake. And remembering my experience in Wi-Pan, we had used face a lot. And as long as they match the real thing, we do not have to go. Through all the dust changing them.

**Speaker 2:** [14:49] Nice. We have a question from Adam Steele. Oh well, do you want to leave these questions, Mark? You start.

**Speaker 3:** [15:00] classic interview questions so like yeah take note if you are like looking for a job right now what are the main differences between mocks fakes and stops

**Speaker 1:** [15:11] So I don't know if you still think see the screen. But I anticipated this question. So I don't know if I have to read it to everyone, but if you can make a screenshot, I will maybe try and share this slide deck later as well. But this is the difference.

**Speaker 3:** [15:41] Okay, Yeah, another question from Agby. Can you give one of two problems that you experienced with mock?

**Speaker 1:** [15:50] So like I said, one problem was that our test coverage is quite high and we used Mox a lot, which meant that any small change to the implementation would require updating a bunch of a lot of tests essentially 10 sometimes 20 and this is just time wasted because not time waste time wasted and a noise because you make a change you implement a feature and you usually test it yourself And can't tell whether you covered

[16:36] a lot of edge cases or maybe it's good enough. And then We're having to go back and fix 10 or 20 tests just to make the tests work is just un unreasonable waste that should be removed. And the this morning I saw an excerpt from Ken Beck post. Ken Beck works at Facebook and is quite famous programmer and something from that excerpt really struck a chord with me. He said that Facebook if a test fails and the system still works, they just remove the test.

[17:22] Maybe I'm not that rabbitful, but it does give food for thought.

**Speaker 3:** [17:28] Well, yeah, on this subject, I don't have a question, just want to share my opinion. I think that the golden rule with Marks is to test external dependency. Like for me, the classic example of Mark is when you need to use an HTTP library to call an external endpoint. You can mock that because that's external to the system, but
