使用Pytest测试Python银行代码时无测试执行问题求助
Pytest无法执行银行代码测试,提示“无测试执行”
我写了一段银行相关的Python代码,主代码运行完全正常,但用Pytest跑测试时一直提示“无测试执行”。我是编程新手,现在要完成课程要求的TDD学习,没法延后,附上主代码和测试代码,求帮忙排查问题。
主代码(bank_program.py)
import datetime tday = datetime.date.today() balance = 1000.0 amount = float transaction_list = [] class Account(amount): def get_balance(self): print("\n This is your account balance: " + str(balance)) def deposit(self, amount): global balance amount = float(input("\n How much would you like to deposit? ")) if amount > 10000: print("\n Do you want to swim in the vualt? ") transaction_list.append("You deposited " + str(amount)) balance = balance + amount print("\n You're balance is now " + str(balance)) def withdrawl(self, amount): global balance amount = float(input("\n How much do you wanna take out? ")) while amount > balance: amount = float(input("\n You don't have enough funds. Enter a new value ")) transaction_list.append("\n You withdrew " + str(amount)) balance = balance - amount print("\n You're balance is now " + str(balance)) class Transaction(amount): def transaction(self): print("\n") print(" " + str(card_number) + " " + str(tday)) print("\n Recipt: HM21-1926\n") print("\n Account: Chequing. Primary\n") print("\n Here is your transaction history!\n") for i in transaction_list: print(i) print("\n Account Balance: " + str(balance)) print("\n Limited time offer: get a personal loan starting at Prime + 1.99%*") print("\n Offer valid until September 2, 2022.") print("\n Conditions apply & approval required. Ask us for details.\n") account = Account() transaction = Transaction() if __name__ == "__main__": mike_lane = Account() print(repr(mike_lane)) print(str(mike_lane))
测试代码(原版本)
import bank_program def test_deposit(): account = Account(100) assert balance.amount == 1100 def test_depos(): with pytest.raises(ValueError): assert amount = Account("ABC") def test_transactions(): account = Account(100) assert tday() >= now
问题排查与修复步骤
1. 直接导致“无测试执行”的测试代码问题
- 测试代码未导入
pytest,且引用的Account、balance、tday未从bank_program模块中导入,Pytest无法识别有效测试逻辑。 - 测试文件名需符合Pytest规则:必须以
test_开头(比如test_bank.py),否则Pytest不会扫描到该文件。
2. 主代码设计缺陷(影响测试可行性)
- 全局变量滥用:
balance、transaction_list是全局变量,所有账户共享同一状态,无法单独测试单个账户的行为。 - 不合理继承:
Account类继承float毫无意义,未利用类的封装特性。 - 依赖手动输入:
deposit、withdrawl方法直接调用input()获取输入,导致测试时需要手动交互,无法自动化执行。 - 未定义变量:
Transaction类中引用的card_number未定义,运行时会直接报错。
3. 修复后的可测试代码示例
修改后的主代码(bank_program.py)
import datetime class Account: def __init__(self, initial_balance=1000.0): self.balance = initial_balance self.transaction_list = [] def get_balance(self): return self.balance def deposit(self, amount): if not isinstance(amount, (int, float)) or amount <= 0: raise ValueError("存款金额必须是正数") if amount > 10000: print("\n Do you want to swim in the vault? ") self.transaction_list.append(f"You deposited {amount}") self.balance += amount return self.balance def withdrawal(self, amount): if not isinstance(amount, (int, float)) or amount <= 0: raise ValueError("取款金额必须是正数") if amount > self.balance: raise ValueError("余额不足") self.transaction_list.append(f"You withdrew {amount}") self.balance -= amount return self.balance class Transaction: def __init__(self, account, card_number): self.account = account self.card_number = card_number self.tday = datetime.date.today() def generate_receipt(self): receipt = [ f"\n {self.card_number} {self.tday}", "\n Receipt: HM21-1926\n", "\n Account: Chequing. Primary\n", "\n Here is your transaction history!\n" ] receipt.extend(self.account.transaction_list) receipt.append(f"\n Account Balance: {self.account.get_balance()}") receipt.extend([ "\n Limited time offer: get a personal loan starting at Prime + 1.99%*", "\n Offer valid until September 2, 2022.", "\n Conditions apply & approval required. Ask us for details.\n" ]) return "\n".join(receipt) if __name__ == "__main__": mike_lane = Account() print(mike_lane.get_balance()) mike_lane.deposit(500) print(mike_lane.get_balance())
可执行的测试代码(test_bank.py)
import pytest from bank_program import Account, Transaction import datetime def test_deposit(): account = Account(1000.0) account.deposit(100) assert account.get_balance() == 1100.0 def test_deposit_invalid_amount(): account = Account() with pytest.raises(ValueError): account.deposit(-500) with pytest.raises(ValueError): account.deposit("ABC") def test_withdrawal(): account = Account(1000.0) account.withdrawal(300) assert account.get_balance() == 700.0 def test_withdrawal_insufficient_funds(): account = Account(500.0) with pytest.raises(ValueError): account.withdrawal(1000) def test_transaction_receipt(): account = Account() account.deposit(200) transaction = Transaction(account, "1234-5678-9012-3456") receipt = transaction.generate_receipt() assert "You deposited 200" in receipt assert "Account Balance: 1200.0" in receipt assert str(datetime.date.today()) in receipt
4. 执行测试的正确步骤
- 确保测试文件名为
test_bank.py,主代码文件为bank_program.py,放在同一目录下。 - 安装Pytest:
pip install pytest - 运行测试:在终端执行
pytest,Pytest会自动扫描并执行所有测试用例。
内容的提问来源于stack exchange,提问作者HyperionSmith
相关产品推荐
相关产品推荐

