Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm curious how you structure your Python to be well testable. I have to admit, my own use of Python has been limited to scripts and (a long time ago) a game engine, not large codebases. So unit testing for those hardly came up.

It seems there's a couple of dependency injection frameworks but they're clones of what's found in Java, right down to the type names. One of them even calls injectable objects beans! (Rhazes)



Same as you do it in any language: you compose instead of inheriting, you avoid shared state, you generally think about how this thing you're implementing can be tested even as you are implementing it. Test-driven development tends to constrain your interfaces too early but you can get a lot of the same benefits with, let's call it, test-mindful development. That works in any language.


Most of my Python is web. Individual components, same as always - approach with a set API and not too many dependencies, and allow injection via some route if so. I also test web endpoints. One thing I really like is isolating tests that require data -- rather than mocking the database, for example, I'll create an in-memory SQLite DB used while running tests. That way I can test the full stack: a web API, see its results, and check what was changed in the database at the same time, all isolated from the 'real' stack.


I learned to write well testable code when I learned go. It pushes you to pass interfaces instead of direct implementations. There's also no inheritance, just composition. While there's no 1 to 1 translation to Python the concepts are still useful. It can be easier in Python thanks to duck typing.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: