Without more information, my guess is that your problem is that foo
cannot be found when you're running your tests for bar
(e.g. a ValueError: Attempted relative import in non-package
). If that's the case, then your problem is likely due to your project's file/dir organization (see this SO post for a solution).
Alternatively, perhaps your problem is that you don't have the foo
package located within bar
as a submodule. Or maybe you don't have foo
pip installed globally. If this is the case, then you need to set up a virtual environment (the built-in venv library is one way) where foo
is pip installed. You mentioned that foo
isn't on PyPi, but if you've got it on GitHub you can easily add it to a requirements.txt
to have it pulled and installed within your virtual environment.
If those solutions don't answer your question, then maybe you're in fact asking about how you can control the behavior of foo
when bar
is under test? If so, then you should look into mocking and/or patching, which are ways you can create an 'fake' object within your test suite to imitate and substitute for another object within your program. In your case, you want to patch foo
so that your test(s) for bar
don't depend on how foo
behaves. Isolating bar
like this is integral to the concept of unit testing.
Assuming you're using unittest
, there's the excellent unittest.mock
module. unittest.mock
provides a class called Mock
that you can use to imitate real objects in your codebase. The library also provides a function called patch()
that replaces the real objects in your code with Mock
instances. You can use patch()
as either a decorator or a context manager, giving you control over the scope in which the object will be mocked. Once the designated scope exits, patch()
will clean up your code by replacing the mocked objects with their original counterparts. I've found this article to be handy when getting started with Mock
and patch()
.
Hopefully I somehow answered your question. If not, let me know and I can update!