Alex Rivera | Logout

Python, unit-testing and mocking imports

Asked 2008-10-07T13:34:42.690
15

I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests?

As an example: The file with the functions I want to test, imports ten other files which is part of our software and not python core libs.

I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.

EDIT

Thanks for all the answers.

I didn't really know what I wanted to do from the start but now I think I know.

Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path

Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.

Edit
Report

1 Answer

0

In your comment above, you say you want to convince python that certain modules have already been imported. This still seems like a strange goal, but if that's really what you want to do, in principle you can sneak around behind the import mechanism's back, and change sys.modules. Not sure how this'd work for package imports, but should be fine for absolute imports.

answered 2008-10-07T15:30:34.720

Your Answer