James Reid James Reid - 5 months ago 11
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:


mycode = models.UUIDField(null=True)

def haveCode(self):
if self.mycode == uuid.UUID('{00000000-0000-0000-0000-000000000000}'):
return False
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}')

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
to it? I appreciate your help


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