¡Mi solución, al Reto de la clase!

import unittest, os
from unittest.mock import patch
from src.exceptions import InsufficientFundsError, WithdrawalTimeRestrictionError
from src.bank_account import BankAccount
from sys import path
path.append(".")
from src.bank_account import BankAccount
class BankAccountTests(unittest.TestCase):
def setUp(self) -> None:
self.account = BankAccount(initial_balance=1000, log_file="transaction_log.txt")
def tearDown(self) -> None:
if os.path.exists(self.account.log_file):
os.remove(self.account.log_file)
def _count_lines(self, filename):
with open(filename, 'r') as f:
return len(f.readlines())
def test_deposit(self):
new_balance = self.account.deposit(500)
self.assertEqual(new_balance, 1500, "The balance sheet is not equal")
def test_withdraw(self):
new_balance = self.account.withdraw(200)
self.assertEqual(new_balance, 800, "The balance sheet is not equal")
def test_withdraw_with_deposit(self):
account = BankAccount()
account.deposit(200)
account.withdraw(50)
assert account.balance == 150
def test_get_balance(self):
self.assertEqual(self.account.get_balance(), 1000)
def test_withdraw_insufficient_funds(self):
account = BankAccount()
account.deposit(50)
with self.assertRaises(ValueError):
account.withdraw(100)
# ✅ Transferencia exitosa
def test_transfer_successful(self):
target = BankAccount(initial_balance=200)
self.account.transfer(300, target)
assert self.account.get_balance() == 700
assert target.get_balance() == 500
# ❌ Transferencia fallida por fondos insuficientes
def test_transfer_insufficient_funds(self):
target = BankAccount(initial_balance=100)
with self.assertRaises(ValueError):
self.account.transfer(2000, target)
def test_transaction_log(self):
self.account.deposit(500)
self.assertTrue(os.path.exists('transaction_log.txt'))
def test_count_transactions(self):
assert self._count_lines(self.account.log_file) == 1 # Creación de la cuenta
self.account.deposit(500)
assert self._count_lines(self.account.log_file) == 2
def test_transfer_insufficient_funds_logs_failure(self):
target = BankAccount(initial_balance=100)
try:
self.account.transfer(2000, target)
except ValueError:
pass # Se espera la excepción
with open(self.account.log_file, 'r') as f:
log_content = f.read()
assert "No balance available" in log_content
def test_deposit_various_amounts(self):
for amount, expected in [(100, 1100), (0, None), (-50, None)]:
with self.subTest(amount=amount):
if amount <= 0:
with self.assertRaises(ValueError):
self.account.deposit(amount)
else:
self.assertEqual(self.account.deposit(amount), expected)
def test_transfer_with_currency_conversion(self):
usd = BankAccount(initial_balance=100, currency='USD')
cop = BankAccount(initial_balance=0, currency='COP')
usd.transfer(50, cop)
self.assertLess(usd.get_balance(), 100)
self.assertGreater(cop.get_balance(), 0)
def test_transfer_back_and_forth(self):
a = BankAccount(initial_balance=500)
b = BankAccount(initial_balance=0)
a.transfer(200, b)
b.transfer(100, a)
self.assertEqual(a.get_balance(), 400)
self.assertEqual(b.get_balance(), 100)
def test_log_sequence(self):
self.account.deposit(100)
self.account.withdraw(50)
with open(self.account.log_file, 'r') as f:
lines = f.readlines()
self.assertIn("Deposited: 100", lines[1])
self.assertIn("Withdrew: 50", lines[2])
@patch("src.bank_account.datetime")
def test_withdraw_during_business_hour(self, mock_datetime):
mock_datetime.now.return_value.hour = 8 # 8 AM
new_balance = self.account.withdraw(100)
self.assertEqual(new_balance, 900)
@patch("src.bank_account.datetime")
def test_withdraw_disallow_before_business_hour(self, mock_datetime):
mock_datetime.now.return_value.hour = 7 # 7 AM
with self.assertRaises(WithdrawalTimeRestrictionError):
self.account.withdraw(100)
@patch("src.bank_account.datetime")
def test_withdraw_disallow_after_business_hour(self, mock_datetime):
mock_datetime.now.return_value.hour = 18 # 18 PM
with self.assertRaises(WithdrawalTimeRestrictionError):
self.account.withdraw(100)
@patch("src.bank_account.datetime")
def test_withdraw_disallowed_on_sunday(self, mock_datetime):
mock_datetime.now.return_value.weekday.return_value = 6 # Domingo
mock_datetime.now.return_value.hour = 10 # Dentro del horario permitido
with self.assertRaises(WithdrawalTimeRestrictionError) as context:
self.account.withdraw(100)
self.assertIn("weekends", str(context.exception))
@patch("src.bank_account.datetime")
def test_withdraw_allowed_on_monday(self, mock_datetime):
mock_datetime.now.return_value.weekday.return_value = 0 # Lunes
mock_datetime.now.return_value.hour = 10 # Dentro del horario permitido
new_balance = self.account.withdraw(100)
self.assertEqual(new_balance, 900)

import requests
from datetime import datetime
from src.exceptions import InsufficientFundsError, WithdrawalTimeRestrictionError
class BankAccount:
def __init__(self, initial_balance=0, currency='USD', log_file=None):
self.balance = initial_balance
self.currency = currency
self.log_file = log_file
self._log_transaction(f"Account created with {self.balance} {self.currency}")
def _log_transaction(self, message):
if self.log_file:
with open(self.log_file, 'a') as f:
f.write(f"{message} \n")
def deposit(self, amount):
if amount > 0:
self.balance += amount
self._log_transaction(f"Deposited: {amount} {self.currency}. New balance: {self.balance}")
else:
raise ValueError("Deposit amount must be positive")
return self.balance
def withdraw(self, amount):
now = datetime.now()
if now.weekday() >= 5: # 5 = sábado, 6 = domingo
raise WithdrawalTimeRestrictionError("Withdrawals are not allowed on weekends")
if now.hour < 8 or now.hour > 17:
raise WithdrawalTimeRestrictionError("Withdrawals are only allowed between 8 AM and 5 PM")
if amount > self.balance:
raise InsufficientFundsError(
f"Withdrawal of {amount} {self.currency} exceeds available balance of {self.balance} {self.currency}"
)
# if amount > self.balance:
# raise ValueError("Insufficient funds")
elif amount <= 0:
raise ValueError("Withdrawal amount must be positive")
else:
self.balance -= amount
self._log_transaction(f"Withdrew: {amount} {self.currency}. New balance: {self.balance}")
return self.balance
def get_balance(self):
self._log_transaction(f"Check balance. Current balance: {self.balance} {self.currency}")
return self.balance
def transfer(self, amount, target_account):
if amount <= 0:
raise ValueError("Transfer amount must be positive")
if amount > self.balance:
self._log_transaction("Transfer failed: No balance available")
raise ValueError("Insufficient funds for transfer")
# Si las monedas son diferentes, convertir
if self.currency != target_account.currency:
rate = self.get_exchange_rate(self.currency, target_account.currency)
converted_amount = amount * rate
self._log_transaction(f"Converted {amount} {self.currency} to {converted_amount:.2f} {target_account.currency}")
else:
converted_amount = amount
self.balance -= amount
target_account.deposit(converted_amount)
self._log_transaction(f"Transferred: {amount} {self.currency} to {target_account.currency}. New balance: {self.balance}")
return self.balance
def get_exchange_rate(self, from_currency, to_currency):
response = requests.get(f"http://localhost:5000/rate?from={from_currency}&to={to_currency}")
if response.status_code == 200:
return response.json().get("rate", 1.0)
else:
raise ConnectionError("Exchange rate API not available")

