[Tutor] Unit testing in Python (3.3.0) for beginners
Amit Saha
amitsaha.in at gmail.com
Tue Dec 10 06:26:00 CET 2013
On Sun, Dec 8, 2013 at 8:22 PM, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hey there,
>
> I struggle to understand what unit testing specifically means in
> practice and how to actually write unit tests for my code (my gut is
> telling me that it's a fairly important concept to understand).
>
> Over the last few days I learned how to write and work with classes, I
> learned quite a lot about functions, nested loops and I currently walk
> through every program in the Python.org wiki "Simple Programs"
> https://wiki.python.org/moin/SimplePrograms ... and here's the unit
> test program they provide:
>
> import unittest
> def median(pool):
> copy = sorted(pool)
> size = len(copy)
> if size % 2 == 1:
> return copy[(size - 1) / 2]
> else:
> return (copy[size/2 - 1] + copy[size/2]) / 2
> class TestMedian(unittest.TestCase):
> def testMedian(self):
> self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
> if __name__ == '__main__':
> unittest.main()
>
> Also, I went through the "Beginning Test-Driven Development in Python"
> http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/
> but I have to admit I still don't fully understand how unit tests work
> in practice and how to write my own unit tests.
>
> As it turned out over the last few weeks, the best modus operandi for
> me as an absolute beginner is to grab a small program, take it apart
> in the first place, understand how each component works through trial
> & error, then put all those pieces together and then I kind of get the
> big picture. Once I "get it" I practice as much as possible to
> memorize what I just learned and *then* I start readying as many
> blogs, tutorials etc. as possible to deepen my understanding (I
> frankly find most tutorials & blogs too complex and confusing from a
> beginner's viewpoint, and I learn faster by taking code apart and
> learning through trial & error in the first place). So, what I am
> specifically searching for is a very simple code sample which I can
> take apart and iterate through each component, and I was wondering if
> you are aware of resources that might be helpful?
>
> My understanding of unit testing is that I have to embed my code into
> a test and then I have to define conditions under which my code is
> supposed to fail and pass. Is that assumption correct?
>
> I am a bit lost & confused here .. any help & hing is highly appreciated!
Here is an article I came across today that you may find useful:
http://www.jeffknupp.com/blog/2013/12/09/improve-your-python-understanding-unit-testing/
Best, Amit.
--
http://echorand.me
More information about the Tutor
mailing list