Aug-19-2020, 12:53 PM
I am running some unit tests using pytest in PyCharm and am running into a, for me, weird problem.
Does anyone have any idea what is going on here?
Thanks in advance,
Stef
class BalanceSheet(): """Balance sheet""" __assets: Dict[str, float] = {} __liabilities: Dict[str, float] = {} def __init__(self, balance_sheet: BalanceSheet = None): if balance_sheet is not None: for name in balance_sheet.assets.keys(): self.book_asset(name, balance_sheet.asset(name)) for name in balance_sheet.liabilities.keys(): self.book_liability(name, balance_sheet.liability(name)) @property def assets(self) -> Dict[str, float]: return self.__assets @property def liabilities(self) -> Dict[str, float]: return self.__liabilities def book_asset(self, asset_name: str, amount: float): if asset_name in self.__assets: self.__assets[asset_name] += amount else: self.__assets[asset_name] = amount def book_liability(self, liability_name: str, amount: float): if liability_name in self.__liabilities: self.__liabilities[liability_name] += amount else: self.__liabilities[liability_name] = amount def asset(self, name: str) -> float: if name in self.assets: return self.assets[name] else: return 0.0 def liability(self, name: str) -> float: if name in self.liabilities: return self.liabilities[name] else: return 0.0 class BalanceSheetTimeline(BalanceSheet): __history: List[BalanceSheet] = [] def clear(self): super().clear() self.__history.clear() def save_state(self) -> bool: if self.validate(): self.__history.append(BalanceSheet(self)) return True else: return False def balance_history(self, time_delta: int) -> BalanceSheet: if time_delta == 0: return BalanceSheet(self) else: return self.__history[len(self.__history) - abs(time_delta)]And I'm running the following pytest on it:
def test_history(): balance: BalanceSheetTimeline = BalanceSheetTimeline() balance.book_asset(DEPOSITS, 100.00) balance.book_liability(EQUITY, 100.0) balance.save_state() history: BalanceSheet = balance.balance_history(-1) assert history.asset(DEPOSITS) == 100.0 assert history.liability(EQUITY) == 100.0Things go wrong with the first assert on history. For some reason, the DEPOSITS asset equals 200.0. I've been debugging the code and it seems to happen in the constructor which is called from save_state(). The BalanceSheet instance which gets created already contains the DEPOSITS en EQUITY entries before I start copying them over. I have no clue why since the object should be empty, with empty Dict's as far as I know.
Does anyone have any idea what is going on here?
Thanks in advance,
Stef