No al cierre de webs
TreeWeb::Artículos::Python::Basic unit testing with Python
Permalink: http://www.treeweb.es/u/1295/ 16/10/2015

Basic unit testing with Python

First of all, we will create our virtual env:
$ virtualenv .myproject New python executable in .myproject/bin/python Installing setuptools, pip, wheel...done.
Then, we have to activate it:
$ source .myproject/bin/activate (.myproject)$
As you can see, the prompt has changed.

The next step is to create a code file and a testing one. For example, this can be our code file named `program1.py`:
#-*- coding: utf-8 -*- u""" Program1 """ def SayHello(name=None): words = "Hello" if name is not None: words += " %s" % name return words def SayGoodbye(): return "GoodBye"
And this can be the testing file named `program1_test.py`:
#-*- coding: utf-8 -*- u""" Program1 test """ import unittest import program1 class TestProgram1(unittest.TestCase): def test_say_hello(self): words = program1.SayHello() self.assertEqual('Hello', words) def test_say_hello_john(self): name = 'John' words = program1.SayHello(name) self.assertEqual('Hello John', words) def test_say_goodbye(self): words = program1.SayGoodbye() self.assertEqual('GoodBye', words) if __name__ == '__main__': unittest.main()

Running the tests

It is simple, just execute the `program1_test.py` with python:
(.myproject)$ python program1_test.py ... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK
An easy way to save time is to execute the test every second:
(.myproject)$ watch -n 1 python program1_test.py