mardi 3 mai 2016

How to mock a property inside a class in Python

This is my first file called user.py

from account import Account    
class User:
   def __init__(self, id):
       self.id = id
       self._account = None

   @property
   def account(self):
       if not self._account:
          self._account = Account(self.id)

       return self._account

   @property
   def has_discount(self)
       return self.account.discount_id > 0

I have a second file called account.py

class Account:
    def __init__(self, user_id):
        # some process to load DB data
        self.account = load_account(user_id)
        # do something after this to initialize account properties like discount, etc

    @property
    def discount_id(self):
       return self.discount_id

My goal is to test user.py. One of the things I want to do is to mock the Account object in user.py for the 'has_discount' property decorator. I want to test different scenarios where has_discount will return either 0 or any other number.

How do I do this using patch where I can mock the Account object in the User class to return custom values so I can try different tests?

Aucun commentaire:

Enregistrer un commentaire