So… I was watching the classes of Python for Zumbies (Brazilian Portuguese course) and I came across some code to do. There are some ways to see my code working:
- Try by myself;
- Ask for someone else to try to use it, and the best of all;
- Writing automated test code 🙌;
So the best way to learn was writing automated test code;
First, of course, I am going to create the test.
After looking up for information I found out this to
import unittest from fib import fib class FibTestCase(unittest.TestCase): def test_fib1(self): self.assertEqual(fib(1), 1) def test_fib0(self): self.assertEqual(fib(0), 0) def test_fib6(self): self.assertEqual(fib(6), 8) def test_fib6_again(self): self.assertTrue(fib(6) == 8) unittest.main()
If you call it you receive this error:
$ python fib_test.py Traceback (most recent call last): File "fib_test.py", line 2, in <module> from fib import fib ImportError: No module named 'fib'
So far so good, I did not write the code, let’s create it, file
def fib(n): if n < 2: return(n) a = fib(n-1) b = fib(n-2) return(a+b)
If we call it we have:
$ python fib_test.py .... ---------------------------------------------------------------------- Ran 4 tests in 0.000s OK
While learning about object orientation I got the following example.
First the test:
import unittest from television import Television class TelevisionTestCase(unittest.TestCase): def setUp(self): self.tv = Television('Room') def test_a_new_tv_is_off(self): self.assertFalse(self.tv.on) def test_i_can_change_the_status(self): self.tv.on = True self.assertTrue(self.tv.on) def test_i_can_change_the_channel(self): self.tv.plus_channel selft.assertEqual(self.tv.channel, 2) unittest.main()
Now the class:
class Television: def __init__(self, local): self.on = False self.channel = 1 self.local = local
This example of
Television I used TDD, aka, red/green/refactor.
There is a method missing in
Television, if you are studying python take it as an exercise 😉.
Posts in this series
- Learning Python using automated test (This post)
- How to create helper methods to RSpec, Feb 26 2018;
- Usefull Gems for testing a Ruby and Ruby on Rails app, Mar 13 2018;