James Reid James Reid - 3 months ago 7
Python Question

How to assign a value to a property in django

i have a new property in my model however I'd like to assign a test value in it for my test script.

this is my code:

models.py

mycode = models.UUIDField(null=True)

@property
def haveCode(self):
if self.mycode == uuid.UUID('{00000000-0000-0000-0000-000000000000}'):
return False
else
return True


and this is the test script that i am working on. I wanted to have a test value for haveCode:

test = Test()
test.mycode = uuid.UUID('{00000000-0000-0000-0000-000000000000}')
test.save()

checkTest = Test()

#this is only to pass the test
#delete this when start coding
checkTest.haveCode = True

assertEqual(test.haveCode, True)


however I got an error in
checkTest.haveCode = True
since this is just a property and not an attribute.

how to assign
True
to it? I appreciate your help

Answer

You can 'mock' that property using the mock library

from mock import patch, PropertyMock

@patch.object(Test, 'haveCode', new_callable=PropertyMock)
def myTest(test_haveCode_mock):
    test_haveCode_mock.return_value = True
    checkTest = Test()
    assertEqual(checkTest.haveCode, True)
    patch.stopall()  # when you want to release all mocks
Comments