Python TDD assert 语句没有像我想象的那样工作

Python TDD assert statements not working like i thought

我只是对为什么会这样感到困惑。当我 运行 我的断言时,似乎每个测试都没有创建自己的对象。所以当我到达最后一个断言语句时,测试失败,因为另一个断言仍在列表中。任何帮助都会非常感谢 我的 Class 代码:

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)

我的 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

您的测试失败是因为您的代码有误 - 也就是说,它们失败是因为您以能够检测错误的方式正确编写了测试,并且他们在您的代码中检测到了错误。

是的,每个测试函数都会创建一个新的 Account 实例,您可以在测试函数本身中清楚地看到这一点。但是,每个 Account 实例都没有自己独特的 Transaction 实例,因为您将其设为 class 属性而不是实例属性。

要修复 Account class 中的错误,您应该初始化

        self.transaction = Transaction(self.balance)

__init__ 方法中,这样每个 Account 实例都有一个对不同 Transaction 实例的引用。