0

I'm trying to figure out the python import system aliases the dependencies of a module imported using the 'from' keyword.

In particular, my use-case is writing unittest.mock.patch statements for mocking attributes of an object that is imported using "from", and that object uses something imported from another module. However, more broadly I just want to understand how the import system works.

My question may make more sense with an example:

Assume we have some class A in some module a, that uses a class from module b

a.py:

from b import B

class A:
    def __init__(self):
        B.use_some_static_method()

        # OR

        self.b_instance = B()

Then, for example, in some test code we want to mock B when testing our A object. How would I write a patch statement?

test_a.py:

from a import A


def test_a(mocker):
    # Mock with pytest-mock's mocker
    mock_b = mocker.patch('<some path>')

    a = A()
    a.do_something_with_B()

What path would I put in place of ? I realize that I could simply use import a instead, and then mock a.B, but I'm more interested in understanding the import system and how this works and why it works that way.

Iinferno1
  • 49
  • 1
  • 6
  • Do the answers [here](https://stackoverflow.com/questions/710551/use-import-module-or-from-module-import) answer your questions? – MyNameIsCaleb Apr 27 '19 at 00:05
  • You would do `mocker.patch('a.B')`. See [Where to patch](https://docs.python.org/3/library/unittest.mock.html#where-to-patch) for more info. – hoefling Apr 27 '19 at 08:52
  • @hoefling I originally thought that's what I would do, but it didn't seem to work when I tried that. If I understand correctly it's because my test imports A as `from a import A`, so the A is actually `__main__.A`. That's the root of my question, which B is being referenced by `__main__.A`? It also didn't seem to work when I tried `mocker.patch('__main__.B')` – Iinferno1 Apr 27 '19 at 16:47
  • @GiraffeMan91 not particularly, no. I'm aware of how the `from ... import ...` statement works, my question is more about the details of how the two imports alias the dependencies of the imported modules. – Iinferno1 Apr 27 '19 at 16:53
  • @Iinferno1 if it doesn't work, add a [mcve] to the question. `from a import A` is just a syntactic sugar for `import a; A = a.A`, so mocking `a.B` should be the correct approach. `__main__` module name should not occur when running tests with `pytest`. – hoefling Apr 28 '19 at 10:35

0 Answers0