ten small Python programs
Steve Howell
showell30 at yahoo.com
Sun May 27 14:08:38 EDT 2007
--- Steven Bethard <steven.bethard at gmail.com> wrote:
> I think I would rewrite the current unit-testing
> example to use the
> standard library unittest module::
>
> # Let's write reusable code, and unit test it.
> def add_money(amounts):
> # do arithmetic in pennies so as not to
> accumulate float errors
> pennies = sum([round(int(amount * 100)) for
> amount in amounts])
> return float(pennies / 100.0)
> import unittest
> class TestAddMoney(unittest.TestCase):
> def test_float_errors(self):
> self.failUnlessEqual(add_money([0.13,
> 0.02]), 0.15)
> self.failUnlessEqual(add_money([100.01,
> 99.99]), 200)
> self.failUnlessEqual(add_money([0,
> -13.00, 13.00]), 0)
> if __name__ == '__main__':
> unittest.main()
>
> I believe I've still kept it to 13 lines.
>
I approve this change, although in a sense, it's
harder for a Python newbie, because it introduces
inheritance a little earlier than I would have liked.
FWIW I'm in the minority (I think) of people that
prefer roll-your-own testing, but I don't want to
argue that, because I think it mostly comes down to
personal preference.
I'll only defend my position by posting this link,
which suggests that roll-your-own even has validity in
an educational setting:
http://www.elkner.net/jeff/testFirst/index.html
> P.S. The "right" way to add money is using the
> decimal module, but I
> couldn't think of a better example.
Agreed. Maybe somebody else will come up with
something more creative, but I'm happy enough with our
current version.
____________________________________________________________________________________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more.
http://mobile.yahoo.com/go?refer=1GNXIC
More information about the Python-list
mailing list