Jeremy Satterfield
Coding, Brewing and Tulsa Life

Viewing posts tagged python

Unit Testing Recursion in Python

Today I finally figured out the solution to a problem I've been trying to solve for a while. It's kind of hacky and maybe a bad idea, but now I know it's possible. The problem has always been that I'd like to test that a function recurses, but not needing it to actually have the recursion execute within to test. Just a unit test to assert that recursion is happening. After a little thought about how Python stores references I came up with this.

Keeping MRO In Mind When Mocking Inherited Methods

So I just spent a couple of hours banging my head on a ridiculous PyMox mocking issue and though I'd share. Here is an example of the existing code.

Mocking a property in Python

Anytime I see someone turning an instance method into a property on a Python object, I always have to step back and rethink whether it's really the right thing to do. While properties certain have valid use cases, I often see them overused and misused. This can result in code that is harder to refactor should you decide you actually do want to accept arguments as well as less straight forward to separate in unit tests.

Class-based Celery Tasks

Recently, I've had to write several complicated Celery tasks. Unfortunately, when doing a complicated process standard task functions can become unwieldy to write, read and unit test. After looking into how Celery tasks actually work, I was able to find a more manageable way of writing these complex tasks.

Mocking Python's built-in open function

A while back I was working on my podcast client and ran into an issue downloading large files. The root problem was that all of Django's FileField backends store the file (or file-like object) to memory then saves it to disk, and the cubieboard system I was using had limitied memry resources, resulting in "out of memory" errors. After much searching and hacking I finally settled on just storing the file to disk myself using requests streaming argument. This allowed me to download the file in chunks and save directly to disk and then tell the Django field where I placed it, as you can see here.