Hailiang Zhang
Hailiang Zhang

Reputation: 18930

How to mock up a class variable value in python unit test?

Say I have a class:

class A():
  def f(self):
    self._v = 1

Tried:

m=Mocker()
A.f._v = m.mock()
...

but didn't work. Not sure how...

Upvotes: 4

Views: 23270

Answers (3)

Vishal
Vishal

Reputation: 2173

I tried above solutions and it still does not solve my purpose which is exactly what is asked originally. The above approach would update the mocked attribute of my class to have a value of .

My requirement is to set the attribute value from the mocked value I provide in my unit test class.

I could finally resolved this with the help of following approach. Let me know if its not a correct way:

Actual Class:

class ActualClass(object):
    name=''

    def some_method(self):
        name=get_name_from_external_source()  #Say, returned name='ActualValue' 
        print name 

Unit Test Class:

from mock import PropertyMock
import unittest
class TestActualClass(unittest.TestCase):
    def test_some_method(self):
        actual_class=ActualClass()
        p=PropertyMock(return_value='Mocked_Name')
        type(actual_class).name=p
        actual_class.some_method()

When you run some_method in ActualClass through normal execution, the output:

ActualValue

When you run TestActualClass, the output:

Mocked_Name

This implies that class attributes are mocked with a mocked value using PropertyType and you can test the method with mocked value and without worrying about external source method call.

Upvotes: 3

Raymond Hettinger
Raymond Hettinger

Reputation: 226524

The class definition shows an instance variable to set it from outside this class, do something like this:

class A:
  def f(self):
    self._v = 1

a = A()
a._v = Mock()

If you actually wanted a real class variable, try this:

class A():
  _v = None
  def f(self):
    self.__class__._v = 1

A._v = Mock()

Upvotes: 4

reclosedev
reclosedev

Reputation: 9522

Did you mean Mock library?

from mock import Mock
real = ProductionClass()
real.method = Mock(return_value=3)
real.method(3, 4, 5, key='value')

edit:

You are trying to access A.f._v before mocking which is impossible. Not sure what are you trying to do, but this will work

>>>A.f = Mock()
>>>a = A()
>>>a.f._v
<Mock name='mock._v' id='42076240'>

Upvotes: 4

Related Questions