I am just confused about why this is happening. When I run my assert it seems that each test is not creating its own object. so when i get to the last assert statement the test fails because the other assert are still in the list. Any help would be great thank you My Class code:
from datetime import date
class Transaction():
"""
Transaction
"""
balance = 0.0
timestamp = date.today()
def __init__(self, amount, dt=None):
self.balance = amount
self.transactions = []
if dt is None:
self.timestamp = date.today()
else:
self.timestamp = dt
def __repr__(self):
return '{self.__class__.__name__}({self.balance:,.2f}, {self.timestamp})'.format(self=self)
def __str__(self):
return f'{self.timestamp}: ${self.balance:,.2f}'
class Account():
"""
Account Class
"""
balance = 0.0
transaction = Transaction(balance)
def __init__(self):
self.balance = 0.0
def deposit(self, amount):
self.balance += +amount
self.transaction.transactions.append(+amount)
def withdraw(self, amount):
self.balance -= amount
self.transaction.transactions.append(-amount)
def get_balance(self):
if len(self.transaction.transactions) < 1:
return 0
return sum(self.transaction.transactions)
My Code for pytest:
def test_append_transaction():
account = Account()
account.deposit(200)
assert account.transaction.transactions == [200]
def test_deposit():
user = Account()
user.deposit(300)
assert user.balance == +300.00
def test_append_withdraw():
account = Account()
account.withdraw(50)
assert account.transaction.transactions == [-50]
def test_withdraw():
account = Account()
account.withdraw(50)
assert account.balance == -50.0
Your tests are failing because your code is wrong - i.e. they are failing because you've written your tests correctly, in a way which is able to detect bugs, and they detected a bug in your code.
Yes, each test function does create a new Account
instance, as you can clearly see in the test functions themselves. However, each Account
instance does not have its own distinct Transaction
instance, because you made this a class attribute instead of an instance attribute.
To fix the bug in your Account
class, you should initialise
self.transaction = Transaction(self.balance)
in the __init__
method, so that each Account
instance has a reference to a distinct Transaction
instance.