It’s just a fact of life, as code grows eventually you will need to start adding mocks to your test suite. What started as a cute little two class project is now talking to external services and you cannot test it comfortably anymore.
That’s why Python ships with unittest.mock, a powerful part of the standard library for stubbing dependencies and mocking side effects.
However, unittest.mock is not particularly intuitive.
I’ve found myself many times wondering why my go-to recipe does not work for a particular case, so I’ve put together this cheatsheet to help myself and others get mocks working quickly.
This is the second part of a two part series on coroutine patterns in asyncio, to fully benefit from this article please read the first installment: Asyncio Coroutine Patterns: Beyond await
In the first part of this series we concluded that asyncio is awesome, coroutines are awesome and our code is awesome. But sometimes the outside world is not as awesome and we have to deal with it.
Now, for this second part of the series, I’ll run over the options asyncio gives us to handle errors when using these patterns and cancelling tasks so as to make our asynchronous systems robust and performant.
If you are really new to asyncio I recommend having a read through my very first article on the subject, Asyncio for the Working Python Developer, before diving into this series.
I will be continuing with the examples using the Hacker News API and also be using the async/await syntax introduced Python 3.5+ and all example code is available in the Github repo for this series.
Asyncio, the concurrent Python programmer’s dream, write borderline synchronous code and let Python work out the rest, it’s
import antigravityall over again…
Except it isn’t quite there yet, concurrent programming is hard and while coroutines allow us to avoid callback hell it can only get you so far, you still need to think about creating tasks, retrieving results and graceful handling of errors. Sad face.
Good news is all of that is possible in asyncio. Bad news is it’s not always immediately obvious what wrong and how to fix it. Here are a few patterns I’ve noticed while working with asyncio.
I remember distinctly the moment where I thought, “Wow, that’s slow, I bet if could parallelise these calls it would just fly!” and then, about three days later, I looked at my code and just didn’t recognize it, it was an unreadable mash up of calls to threading and process library functions.
Then I found asyncio, and everything changed.
Hey, Django dev, come here for a sec!
I heard you’re on Rails now, looking for some quick answers?
Yeah, I’m your man, got them right here.
You are seasoned Django developer.
You are master of the models. Ruler of the views. King of the templates.
But fate has brought you to Rails now, and you feel clumsy, slow, googling every step of the way. You’re asking yourself how do I Django in Rails?