4

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...

3
  • 2
    Not sure how... to what? Commented Dec 17, 2011 at 19:34
  • The above code shows uses an instance variable, not a class variable. Commented Dec 17, 2011 at 20:03
  • agreed with @RaymondHettinger this question doesn't make sense. If you're asking about a class variable then it should be defined at the class level, not inside an instance method Commented Mar 6, 2019 at 2:25

3 Answers 3

4

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'>
Sign up to request clarification or add additional context in comments.

Comments

4

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()

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.