Singleton and Unit Tests

9 Oct

Singletons [1] are considered a cancer for many people, however, while python modules can act very well as singletons they can’t be extended, and then we use a singleton class.

I have using singletons classes in two projects, first is django-breadcrumbs, that use singletons to store breadcrumbs and than present it in templates. Another project, is our systems at PDG that use a singleton to store request, so we can use request at any place (ex: Django Models save).

Than last weekend while fixing some bugs for django-breadcrumbs, I found myself writing unit tests and.. “hell, how I destroy that singleton!?”. After a bit of research about singletons and nice tips on this Stack Overflow question [2] I wrote a simple singleton for my breadcrumbs and singleton unit tests. That will be useful for many many people:

Now you can use it in your tests like:

That’s it, have fun 🙂

[1] – Singletons at Wikipedia
[2] – “Python Singletons – How do you get rid of (__del__) them in your testbench?” at Stack Overflow

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)

No comments yet

Leave a Reply