简体   繁体   中英

How do you patch mock an import from a class that is being imported to a module you are testing?

The module I am attempting to test (with pytest and pytest-mock) is like so:

x.py

from a import ClassA

def a_func():
  class_a = ClassA()
  ...

module a.py:

import b

class ClassA:
  ...

test:

def test_my_code(mocker):
  import x
  mock_of_b = mocker.patch.object(x.a, 'b')
  ...

or plain unittest:

import x

class MyTests(unittest.TestCase):

  @patch('x.a.b')
  def test_my_code(self, mock_of_b):
  ...

I understand that xab isn't going to work because a isn't actually imported - ClassA is but I'm not understanding how can I accomplish patching b in module a when importing ClassA directly. x.ClassA.b won't work - is there some kind of param to access an imported classes module? I could grab __module__ but that's just the string.

Maybe you are making some mistakes. Take a look at a simple setup of a module + mock + function environment.

person.py

class Person:
    def __init__(self, name):
        self.name = name
    def get_name(self):
        return self.name

function.py

from person import Person

def show_person(name):
    person = Person(name)
    return "The person name is {}".format(person.get_name())

test.py

from unittest import TestCase, mock
from function import show_person

class TestPerson(TestCase):
    def test_person(self):
        with mock.patch('function.Person.get_name', return_value="bpreisler") as mock_person:
            self.assertEqual(show_person("John"), "The person name is bpreisler")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM