Diskussion:Kurs Python richtig lernen/Unit Testing

Aus Geoinformation HSR
Wechseln zu: Navigation, Suche

Aufgabe 1

from src.bank import BankAccount
from nose.tools import raises


def test_deposit_on_empty_account():
    b = BankAccount()
    b.deposit(100)
    assert b.balance == 100
    
def test_deposit_with_initial_balance():
    b = BankAccount(10)
    b.deposit(100)
    assert b.balance == 110

@raises(ValueError)
def test_withdraw_with_too_high_amount():
    b = BankAccount(10)
    b.withdraw(100)

def test_withdraw_ok():
    b = BankAccount(110)
    b.withdraw(100)
    assert b.balance == 10

Aufgabe 2

from src.rational import *
from nose.tools import raises

    
def test_gcd():
    assert gcd(4, 4) == 4
    assert gcd(4, 2) == 2
    assert gcd(3, 6) == 3
    assert gcd(12, 9) == 3
    
@raises(ValueError)
def test_zero_denominator_raises_error():
    Rational(3, 0)
    
def test_add():
    r1 = Rational(7, 3)
    r2 = Rational(6, 3)
    assert Rational(13, 3) == r1 + r2

def test_sub():
    r1 = Rational(12, 3)
    r2 = Rational(6, 3)
    assert Rational(2, 1) == r1 - r2
    
def test_mul():
    r1 = Rational(2, 3)
    r2 = Rational(4, 3)
    assert Rational(8, 9) == r1 * r2
    
def test_div():
    r1 = Rational(2, 3)
    r2 = Rational(4, 3)
    assert Rational(1, 2) == r1 / r2

def test_str():
    assert "2/3" == str(Rational(2, 3))
    
def test_eq():
    r = Rational(2, 3)
    assert r == r
    assert Rational(4, 6) == r
    
def test_neq():
    assert Rational(3, 4) != Rational(2, 3)

def test_float():
    assert 0.75 == float(Rational(3, 4))