Pages

Tuesday, October 23, 2012

Unit testing - python

Unit testing in python

You'll have more information from this site.

There were some choices for unit test external libraries, but now unittest is a part of
import random
import unittest

from Hello import *

class TestHello(unittest.TestCase):
    def setUp(self):
        self.hello = Hello()

    def test_add(self):
        self.assertEqual(self.hello.add(2,12), 14)

    def test_add2(self):
        self.assertEqual(self.hello.add(2,3), 5)


class TestHello2(unittest.TestCase):
    def setUp(self):
        self.hello = Hello()

    def test_add(self):
        self.assertEqual(self.hello.subtract(2,12), -10)

    def test_add2(self):
        self.assertEqual(self.hello.subtract(2,13), -11)

if __name__ == '__main__':
    unittest.main()
In order to execute the code, you just need to run the unit test code.
python UNIT_TEST_CODE.PY

Things to consider

Normally, unit testing starts with a TestCase per class under the test. And for multiple TestCases, one can bundle the tests into TestSuite as you do in java.

However, with python (it seems like that) the unittest.main() searches into classes that inherit from unittest.TestCase to execute all the tests.

You see that in this example, 4 tests are executed automatically.
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

Unit testing using pycharm

PyCharm is a python development environment implemented in Java programming language from Jet Brains. You will find a Python plugin for IntellJ, but they are two different products.

PyCharm doesn't have automatic unit test generator, but it seems like that the company doesn't have a plan to support it.

PyCharm is smart enough that when you click the run button, it's for executing unit test.

Doctest

Doctest provides easy way to test. This example shows the usage of it.
"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result

if __name__ == "__main__":
    import doctest
    doctest.testmod()
The format is just use >>> to indicate the code to execute, and write down the expected result including the error message.

When you want to execute it as a command line, nothing will happen as a default. You can use -v option to see the testing result.
smcho@prosseek Desktop> python example.py -v
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok
Trying:
    factorial(30.1)
Expecting:
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
ok
2 items passed all tests:
   1 tests in __main__
   2 tests in __main__.factorial
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

Reference

  1. doctest

google services test : picasa

I needed to use LaTeX script in blogpost, and this site teaches me how to do that, but I need to use google services such as picasa and google/sites for it. So, I tried.

Show pictures from picasa in blogspot

Picasa allows me to upload pictures from my mac to cloud. I'm trying to show the pictures from picasa, however, just href'ing doesn't seem to work. File uploaded to picasa from my mac. https://lh6.googleusercontent.com/-AfYyCt4YI-c/UIbCRY1mA7I/AAAAAAAAAEg/JlgYadGokhg/w561-h421-p-k/IMG_0542.jpg What I needed was to use insert image, and instead of uploading pictures, I can like the page from the picasa. My concern is if this link is temporary or not.

You can change the picture size by modifying width and height.

The real solution

This site gave me a hint that the site I need to check is https://picasaweb.google.com/, not http://picasa.google.com/. Now, I can embed the slide show. Or, just one picture.
10/23/12

Setup sequence for UNIX/LINUX using bash

Refer to this post.

Start up sequence for emacs

For the good old days, MS-DOS has autoexec.bat, and UNIX/Linux system has .bashrc scripts or others. Then, what's the startup sequence for emacs? What files can be modified in order to do what I want to do with emacs when startup? You can refer to this article.

Monday, October 22, 2012

Python programming - Kaizen way

When programming with Python, I always feel that I have 3 stages.

Stage 1 - python as a script

In this stage, I normally don't know what I don't know. So, I just use python's method to get the functionality I need. Python is superb: it has almost every library I need, it has every container I need, and it means I can code pretty fast.

Stage 2 - python as a procedural language

When I pass the stage one, I can see the methods(functions) that I need to make as I see the duplications clearly. with def, I extract duplicate code into a method.

Stage 3 - python as an OOP language

In this stage, I can see what module/class I need to make. I extract methods into a python class, and I can easily separate the client and python object.

Things to consider

With this three stage python programming model, I need to answer those questions.
  1. What refactoring tools do I need to get the kaizen work effectively?
  2. When do I need to start making testing code?
  3. What method/technique do I need to be more effective? logging the procedure?

Three packages for file utilities in python

os.path

Python provides useful features for checking files and creating files/directories. The small issue is that the packages one need to use the features are not one, but three. For file checking, one can use os.path.exists() method. This can be used for file and directory existence checking.
# Directory check
os.path.exists(DIRECTORY)
# File check 
os.path.exists(FILEPATH)
os.path has more interesting utilities as you can find in this site. The return value of os.path.split is a tuple with 2 elements, and you can get the same result with os.path.dirname and os.path.basename. You should remember python uses basename with is a little bit hard to conjecture. Using os.path.split(), you can extract the directory name and file name.
# Directory
os.path.split(FILE_PATH)[0]
os.path.dirname(FILE_PATH)
# File
os.path.split(FILE_PATH)[1]
os.path.basename(FILE_PATH)
You have another kind of split, which is splitext. It gives you a tuple of root + ext. For example, you'll get ('hello','.txt') from 'hello.txt'.
# Directory
os.path.splitext(FILE_NAME)[0]
os.path.splitext(FILE_NAME)[1]
os.path.abspath() is also useful method that returns absolute path from relative path.
os.path.abspath(RELATIVE_PATH)

os

However for creating directory, one can use os.makedirs() method.
# Directory check
os.makedirs(DIRECTORY)

shutil

Finally, one can use shell utils (shutil) for copying files. You have two choices: copyfile() for specifying source file to dest file, and copy() method for source file to dest file or directory. You can refer to this site for shutil.
shutil.copyfile(FROM_FILE, TO_FILE)
shutil.copy(FROM_FILE, TO_FILE)
shutil.copy(FROM_FILE, TO_DIRECTORY)

Not so OO like features in Python

Python is built on Object Oriented paradigm. However, some of the python's features are not so Object Oriented to confuse OO users. For example, when converting string to intger, python doesn't provide something like "32".to_i(). Compared to Ruby that everything is an object, it looks like less OO way.
# Ruby
x = "102".to_i
# Python
x = int("102"))
Likewise, when you want to get the length, you should call the len() method explicitly.
# Ruby
x = "hello".length
# Python
x = len("hello") 
Sometimes it's annoying.