py3 relative issues of import and mock

Billion, Preface

  Core herein problem: In the case of import python3 relative path, the mock corresponding module, cause other modules within the module corresponding to an error introduced.

I. Description of the problem

Test case structure:

 

 

a.py:

# -*- coding: utf-8 -*-

import jiliguala

def afunc():
    print("this func a")

b.py:

# -*- coding: utf-8 -*-

from . import a
def bfunc():
    a.afunc()
    print("this func b")

core.py:

# -*- coding: utf-8 -*-

import unittest
import unittest.mock as mock

def test_post(x):
    print("do test http: ", x)

@mock.patch.dict("sys.modules", {
    "test.a": mock.Mock(),
})
class TestCore(unittest.TestCase):
    @mock.patch("a.afunc")
    def test1(self, test_post):
        import test.b as b
        b.bfunc()
        test_post.side_effect = test_post
        b.bfunc()

    @mock.patch("c.cpost")
    def test2(self, test_post):
        import test.c as c
        c.cfunc()
        test_post.side_effect = test_post
        c.cHttp()

  Brief, a non-py file service (with some inexplicable module), b depends on a, so I tested the code needs to be a b in isolation.

  In the core code by the decorator manner, a module isolation (from. Import a such an approach is in the form of test.a sys.modules), and then rewrite the code a.afunc.

  Well, look at the code logic, seemingly no problem.

result:

   I put a whole module mock, how could import a module inside?

  Write an empty test class, see if there are mock

 

result:

 

  Successful mock go ......

  I guess the problem: it is estimated that the wording of the magic I have a problem.

  Yes! If the module directly to mock the magic words, that there is no problem, but if indeed there is such a module, the module uses a lot of other py command line can not be invoked if, such an approach is a little better.

Second, the storage system path way

Three, the mock methods, introducing a manner corresponding to the path

Mainly described, but the mock sys.modules which added the value of the corresponding dictionary, together with the examples Mock

Fourth, the root cause of the problem

V. Solution

The difference between DLC, py2 and py3 import of

Why py3 describes the bag module does not support the direct import

Guess you like

Origin www.cnblogs.com/end-emptiness/p/12013742.html