Interesting Post About Django ( Why Django is the best framework for Python Developers ):

Please refer the below link for this complete article.

http://www.evontech.com/what-we-are-saying/entry/why-django-is-the-best-framework-for-python-developers.html

 

Advertisements

A Simple Calculator App By Using Tkinter (Python GUI Module) :

from Tkinter import *

root = Tk()
root.title(“Calculator”)
#So that it becomes of fixed size
root.resizable(0, 0)
#So that it remains on top of the screen
root.wm_attributes(“-topmost”, 1)

#Label
Label1 = Label(root, text = “Calculator app”)
Label1.grid(row=0, columnspan=8)

#Variables
equa = “”
equation = StringVar()

calculation = Label(root, textvariable = equation)

equation.set(“Enter your expression : “)

calculation.grid(row=2, columnspan=8)

def btnPress(num):
global equa
equa = equa + str(num)
equation.set(equa)

def EqualPress():
global equa
total = str(eval(equa))
equation.set(total)
equa = “”

def ClearPress():
global equa
equa = “”
equation.set(“”)

Button0 = Button(root, text=”0″, command = lambda:btnPress(0), borderwidth=1, relief=SOLID)
Button0.grid(row = 6, column = 2, padx=10, pady=10)
Button1 = Button(root, text=”1″, command = lambda:btnPress(1), borderwidth=1, relief=SOLID)
Button1.grid(row = 3, column = 1, padx=10, pady=10)
Button2 = Button(root, text=”2″, command = lambda:btnPress(2), borderwidth=1, relief=SOLID)
Button2.grid(row = 3, column = 2, padx=10, pady=10)
Button3 = Button(root, text=”3″, command = lambda:btnPress(3), borderwidth=1, relief=SOLID)
Button3.grid(row = 3, column = 3, padx=10, pady=10)
Button4 = Button(root, text=”4″, command = lambda:btnPress(4), borderwidth=1, relief=SOLID)
Button4.grid(row = 4, column = 1, padx=10, pady=10)
Button5 = Button(root, text=”5″, command = lambda:btnPress(5), borderwidth=1, relief=SOLID)
Button5.grid(row = 4, column = 2, padx=10, pady=10)
Button6 = Button(root, text=”6″, command = lambda:btnPress(6), borderwidth=1, relief=SOLID)
Button6.grid(row = 4, column = 3, padx=10, pady=10)
Button7 = Button(root, text=”7″, command = lambda:btnPress(7), borderwidth=1, relief=SOLID)
Button7.grid(row = 5, column = 1, padx=10, pady=10)
Button8 = Button(root, text=”8″, command = lambda:btnPress(8), borderwidth=1, relief=SOLID)
Button8.grid(row = 5, column = 2, padx=10, pady=10)
Button9 = Button(root, text=”9″, command = lambda:btnPress(9), borderwidth=1, relief=SOLID)
Button9.grid(row = 5, column = 3, padx=10, pady=10)
Plus = Button(root, text=”+”, command = lambda:btnPress(“+”), borderwidth=1, relief=SOLID)
Plus.grid(row = 3, column = 4, padx=10, pady=10)
Minus = Button(root, text=”-“, command = lambda:btnPress(“-“), borderwidth=1, relief=SOLID)
Minus.grid(row = 4, column = 4, padx=10, pady=10)
Multiply = Button(root, text=”“, command = lambda:btnPress(““), borderwidth=1, relief=SOLID)
Multiply.grid(row = 5, column = 4, padx=10, pady=10)
Divide = Button(root, text=”/”, command = lambda:btnPress(“/”), borderwidth=1, relief=SOLID)
Divide.grid(row = 6, column = 4, padx=10, pady=10)
Equal = Button(root, text=”=”, command = EqualPress, borderwidth=1, relief=SOLID)
Equal.grid(row=6, column=3, padx=10, pady=10)
Clear = Button(root, text=”C”, command = ClearPress, borderwidth=1, relief=SOLID)
Clear.grid(row = 6, column = 1, padx=10, pady=10)

root.mainloop()

 

Note:

Tkinter module comes with Python as no need to install by using third party tool,

if not fallow the below link for installing on respected platforms.

http://www.tkdocs.com/tutorial/install.html

Source link

http://codeshot.in/pythongui/calculator.php

Browser applications testing using Selenium with Python

Selenium:

Selenium is a web application testing framework that allows you to write tests in many programming languages like  Java, C#, Groovy, Perl, PHP, Python and Ruby. Selenium deploys on Windows, Linux, and MAC OS.

Selenium Components:

Selenium IDE is a Firefox add-on that records user activity and creates a test case based on it. It can also play the tests back and save them as a program in different languages.

Selenium RC (aka Selenium Remote Control or Selenium 1) receives Selenium Core commands via HTTP and executes them on a remote machine, proxying the web browser in order to avoid the “same host origin” restriction. This also allows writing the tests in other languages like C#, Python, Perl, PHP, Java and Ruby (via language bindings for Selenium Core).

Selenium-WebDriver (aka WebDriver or Selenium 2) is a successor of Selenium RC. It does the same job, but in a different way: instead of injecting a JavaScript code into the browser to simulate user actions, it uses the browser’s native support for automation (different for each browser). Also, instead of a dictionary-based API (used in Selenium RC), it offers the more convenient object-oriented API.

different browsers web drivers link(http://www.seleniumhq.org/download/)

Selenium-Grid allows you run the tests on different machines against different browsers in parallel; in other words it enables distributed test execution.

Selenium Server allows using Selenium-WebDriver on a remote machine.

Where to Start:

It’s good to start with Selenium IDE. It will help you to become more familiar with Selenium commands, and you can see how Selenium works by running the test scripts right from this tool. Note, however, that when you run your test scripts from Selenium IDE, they are executed in a different way than when you run them through other Selenium tools. If you need to test your application, you’d better use Selenium WebDriver or Selenium RC. I put Selenium WebDriver first, because it is the successor of Selenium RC which  has been officially deprecated.

You can download everything at http://docs.seleniumhq.org/download/.

Python Binding package for selenium:

Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way.

Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, Ie, Chrome, Remote etc. The current supported Python versions are 2.7, 3.2, 3.3 and 3.4.

Download python bindings:

You can download Python bindings for Selenium from the PyPI page for selenium package. However, a better approach would be to use pip to install the selenium package. Python 3.4 has pip available in the standard library. Using pip, you can install selenium like this:

pip install selenium

You may consider using virtualenv to create isolated Python environments. Python 3.4 has pyvenv which is almost same as virtualenv.

Small example:

If you have installed Selenium Python bindings, you can start using it from Python like this.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()

The above script can be saved into a file (eg:- python_org_search.py), then it can be run like this:
python python_org_search.py

Explanation about script:

The selenium.webdriver module provides all the WebDriver implementations. Currently supported WebDriver implementations are Firefox, Chrome, Ie and Remote. The Keys class provide keys in the keyboard like RETURN, F1, ALT etc.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Next, the instance of Firefox WebDriver is created.

driver = webdriver.Firefox()

The driver.get method will navigate to a page given by the URL. WebDriver will wait until the page has fully loaded (that is, the “onload” event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded.:

driver.get("http://www.python.org")

The next line is an assertion to confirm that title has “Python” word in it:

assert "Python" in driver.title

WebDriver offers a number of ways to find elements using one of the find_element_by_* methods. For example, the input text element can be located by its name attribute using find_element_by_name method. Detailed explanation of finding elements is available in the Locating Elements chapter:

elem = driver.find_element_by_name("q")

Next we are sending keys, this is similar to entering keys using your keyboard. Special keys can be send using Keys class imported from selenium.webdriver.common.keys:

elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)

After submission of the page, you should get the result if there is any. To ensure that some results are found, make an assertion:

assert "No results found." not in driver.page_source

Finally, the browser window is closed. You can also call quit method instead of close. The quit will exit entire browser where as close will close one tab, but if it just one tab, by default most browser will exit entirely.:

driver.close()


For Complete Reference of Python With Selenium:
link (http://selenium-python.readthedocs.org/)

Fabric Module in Python

What is Fabric?

Fabric is a Python library and command-line tool for streamlining the use of SSH
for application deployment or systems administration tasks. 

Typical usage involves creating a Python module containing one or more functions,
then executing them via the fab command-line tool.

You can execute shell commands over SSH, so you only need to have SSH running on
the remote machine. It interact with the remote machines that you specify as if
they were local. 


Installation

Fabric requires Python version 2.5 or 2.6 (Fabric has not yet been tested on
Python 3.x)

The most common ways of installing Fabric is via, pip, easy_install or via
the operating system's package manager:
pip install fabric

sudo easy_install fabric

sudo apt-get install fabric  # (the package is typically called fabric or python-fabric.)
Please read the official documentation for more information (dependancies etc..) 

Fabric Usage

On their website they write:

"it provides a basic suite of operations for executing local or remote shell
commands (normally or via sudo) and uploading/downloading files, as well as
auxiliary functionality such as prompting the running user for input, or
aborting execution"

Having that information, let's move on.
The installation process added a Python script called fab to a directory in
your path. 

This is the script which will be used to make everything happen with Fabric. 

Just running fab from the command-line won't do much at all.

In order to do anything interesting, we'll need to create our first fabfile. 

Before we do that I would like to show some of the functions in Fabric. 

Fabric functions

Fabric provides a set of commands in fabric.api that are simple but powerful.

With Fabric, you can use simple Fabric calls like
local  # execute a local command)
run # execute a remote command on all specific hosts, user-level permissions)
sudo    # sudo a command on the remote server)
put # copy over a local file to a remote destination)
get # download a file from the remote server)
prompt  # prompt user with text and return the input (like raw_input))
reboot  # reboot the remote system, disconnect, and wait for wait seconds)

Authentication

Fabric relies on the SSH Model, you can use SSH Keys but you can also control
access to root via sudoers. 

The user on the server does not need to be added to "~/.ssh/authorized_keys",
but if it is you don't have to type the password every time you want to execute
a command.

If you ever have to disable the access to a user, just turn off their SSH account.

The Fabfile

You can load Python modules with Fabric. 

By default, it looks for something named either fabfile or fabfile.py. 

This is the file that Fabric uses to execute tasks. 

Each task is a simple function.

The fabfile should be in the same directory where you run the Fabric tool. 

The fabfile is where all of your functions, roles, configurations, etc. will
be defined. 

It's just a little bit of Python which tells Fabric exactly what it needs to do. 

The "fabfile.py" file only has to be stored on your client. 

An SSH server like OpenSSH needs to be installed on your server and an
SSH client needs to be installed on your client.

Creating a Fabfile

To start just create a blank file called fabfile.py in the directory you’d like
to use the fabric commands from.

You basically write rules that do something and then you (can) specify on which
servers the rules will run on. 

Fabric then logs into one or more servers in turn and executes the shell commands 
defined in "fabfile.py". 

If you are located in the same dir as "fabfile.py" you can go "fab --list"
to see a list of available commands and then "fab [COMMAND_NAME]" to execute a
command.

From https://github.com/fabric/fabric

Below is a small but complete "fabfile" containing a single task:
from fabric.api import run
def host_type():
    run('uname -s')
Once a task is defined, it may be run on one or more servers, like so
$ fab -H localhost,linuxbox host_type

[localhost] run: uname -s
[localhost] out: Darwin
[linuxbox] run: uname -s
[linuxbox] out: Linux

Done.
Disconnecting from localhost... done.
Disconnecting from linuxbox... done.
You can run fab -h for a full list of command line options

In addition to use via the fab tool, Fabric's components may be imported into
other Python code, providing a Pythonic interface to the SSH protocol suite at
a higher level than that provided by e.g. the ssh library, 
(which Fabric itself uses.)

Connecting to remote servers

As you can see above, Fabric will look for the function host_type in the
fabfile.py of the current working directory.
In the next example we can see how the Fabric Api uses an internal env variable
to manage information for connecting to remote servers.

The user is the user name used to login remotely to the servers and the hosts is
a list of hosts to connect to. 

Fabric will use these values to connect remotely for use with the run
and sudo commands. 

It will prompt you for any passwords needed to execute commands or connect to
machines as this user. 
# First we import the Fabric api
from fabric.api import *

# We can then specify host(s) and run the same commands across those systems
env.user = 'username'

env.hosts = ['serverX']

def uptime():
    run("uptime")
This will first load the file ~/fabfile.py

Compiling the file into ~/fabfile.pyc # a standard pythonism

Connect via SSH to the host 'serverX'

Using the username 'username'

Show the output of running the command "uptime" upon that remote host.

Now, when we run the fabfile, we can see that we can connect to the remote server.
$ fab uptime
If you have different usernames on different hosts, you can use:
env.user = 'username'
env.hosts = ['userX@192.168.1.1', 'serverX']
Now userX username would be used on 192.168.1.1 and 'username' would be used
on 'serverX'

Roles

You can define roles in Fabric, and only run actions on servers tied to a
specific role. 

This script will run get_version on hosts members of the role "webservers",
by running first on www1, then www2 etc.
fab -R webservers
from fabric.api import *

# Define sets of servers as roles

env.roledefs = {
    'webservers': ['www1', 'www2', 'www3', 'www4', 'www5'],
    'databases': ['db1', 'db2']
}

# Set the user to use for ssh
env.user = 'fabuser'

# Restrict the function to the 'webservers' role

@roles('webservers')

def get_version():
    run('cat /etc/issue')
# To run get_version on both roles (webservers and databases);
$ fab get_version
@roles ('webservers', 'databases')

    def get_version():

 run('cat /etc/issue')
Any function you write in your fab script can be assigned to one or more roles. 

You can also include a single server in multiple roles.

Copy a directory to a remote machine

I would like to end this introduction of Fabric, by showing an example of
how to copy a directory to a remote machine.
from fabric.api import *

env.hosts = ['userX@serverX']

def copy():
    # make sure the directory is there!
    run('mkdir -p /home/userX/mynewfolder')

    # our local 'localdirectory' (it may contain files or subdirectories)
    put('localdirectory', '/home/userX/mynewfolder')

Conclusion

Fabric can be used for many things, including deploying, restarting servers,
stopping and restarting processes. 

You write the description of what is to be done in Python and Fabric takes
care of executing it on all the machines you specify. 

Once you've used it a bunch of times you'll accumulate many "fab files" that
you can re-use.

Basically, any time we would need to log in to multiple servers to do something,
you can use Fabric. 

It’s simple and powerful and the documentation is really good.
Further reading
http://docs.fabfile.org/en/1.5/index.html
https://gist.github.com/DavidWittman/1886632
http://mattsnider.com/using-fabric-for-painless-scripting/
http://www.clemesha.org/blog/modern-python-hacker-tools-virtualenv-fabric-pip/
http://code.mixpanel.com/2010/09/09/easy-python-deployment-with-fabric-and-git/
http://stackoverflow.com/questions/6308686/understanding-fabric/9894988#9894988



Reference taken from: http://www.pythonforbeginners.com

Unit Testing with Python

Unit testing is considered an essential part of software development. Through unit testing, we can evaluate each code component, find out how well it performs, and determine how well it reacts to valid or invalid input. A regression suite of unit tests is also an excellent way of detecting unexpected changes in a code base caused by refactoring or writing new code.

In this article, I examine the mechanisms of unit testing in Python, starting with the unittest module and its key classes. I examine tests individually and in suites, and I discuss how to facilitate their construction and use. Readers should have a working knowledge of Python. The sample test code requires Python 2.5 or later.

The unittest Module

The unittest module started life as the third-party module PyUnit. PyUnit was a Python port of JUnit, the Java unit testing framework. Designed by Steve Purcell, PyUnit became an official Python module starting with version 2.5.

Python Unit Tests
Figure 1: Core classes in unittest.

As Figure 1 shows, there are five key classes in the unittest module. The TestCase class holds the test routines and provides hooks for preparing each routine and for cleaning up after. The TestSuite class serves as a collection container. It can hold multiple TestCase objects and multiple TestSuite objects.

The TestLoader class loads test cases and suites defined locally or from an external file. It emits a TestSuite object that holds those cases and suites. The TextTestRunner class provides a standard platform to run the tests. The TestResults class provides a standard container for the test results.

Out of these five classes, only TestCase must be subclassed. The other four classes can also be subclassed, but they are generally used as is.

 

Preparing a Test Case

Figure 2 shows the structure of the TestCase class. In it are three sets of methods that are used most often in designing the tests. In the first set are the pre- and post-test hooks. The setUp() method fires before each test routine, the tearDown() after the routine. Override these methods when you create a custom test case.

Python Unit Tests
Figure 2: The structure of a TestCase class.

The second pair of methods control test execution. Both methods take a message string as input, and both abort an ongoing test. But the skipTest() method cancels the current test, while the fail() method fails it explicitly.

The third set of methods help identify the test. The method id() returns a string containing the name of the TestCase object and of the test routine. And the method shortDescription() returns the docstr comment at the start of each test routine. If the routine has no such comment, shortDescription() returns a None.

Listing One shows the sample bare bones test case FooTest. FooTest has two test routines: testA() and testB(). Both routines get the required argument of self. Both have a docstr comment for a first line.

Listing One: Code to show the sequence of unit test execution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/python
import unittest
class FooTest(unittest.TestCase):
    """Sample test case"""
    
    # preparing to test
    def setUp(self):
        """ Setting up for the test """
        print "FooTest:setUp_:begin"
        ## do something...
        print "FooTest:setUp_:end"
    
    # ending the test
    def tearDown(self):
        """Cleaning up after the test"""
        print "FooTest:tearDown_:begin"
        ## do something...
        print "FooTest:tearDown_:end"
    
    # test routine A
    def testA(self):
        """Test routine A"""
        print "FooTest:testA"
    
    # test routine B
    def testB(self):
        """Test routine B"""
        print "FooTest:testB"

Figure 3 shows how FooTest behaves when executed.

Python Unit Tests
Figure 3: FooTest behavior.

Note the same setUp() and tearDown() methods run before and after each test routine. So how do you let setUp() and tearDown() know which routine is being run?  You must first identify the routine by calling shortDescription() or id() (See Listing Two). Then use an if-else block to route to the appropriate code. In the sample snippet, FooTest calls shortDescription() to get the routine’s docstr comment, then runs the prep and clean-up code for that routine.

Listing Two: Using test descriptions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import unittest
class FooTest(unittest.TestCase):
    """Sample test case"""
    
    # preparing to test
    def setUp(self):
        """ Setting up for the test """
        print "FooTest:setUp_:begin"
        
        testName = self.shortDescription()
        if (testName == "Test routine A"):
            print "setting up for test A"
            
        elif (testName == "Test routine B"):
            print "setting up for test B"
            
        else:
            print "UNKNOWN TEST ROUTINE"
            
        print "FooTest:setUp_:end"
    
    # ending the test
    def tearDown(self):
        """Cleaning up after the test"""
        print "FooTest:tearDown_:begin"
        
        testName = self.shortDescription()
        if (testName == "Test routine A"):
            print "cleaning up after test A"
            
        elif (testName == "Test routine B"):
            print "cleaning up after test B"
            
        else:
            print "UNKNOWN TEST ROUTINE"
            
        print "FooTest:tearDown_:end"
    
    # see Listing One...

Designing a Test Routine

Each test routine must have the prefix “test” in its name. Without that prefix, the routine will not run. To perform a test, the test routine should use an assert method. An assert method gets one or more test arguments and an optional assert message. When a test fails, the assert halts the routine and sends the error message to stdout.

There are three sets of assert methods. In the first set (Table 1) are the basic Boolean asserts, which fire on a True or False result.

Assert Complement Assert Operation
assertTrue(a, M) assertFalse(a, M) a = True; a = False
assertEqual(a, b, M) assertNotEqual(a, b, M) a = b; a ≠ b
assertIs(a, b, M) assertIsNot(a, b, M) a is b; a is not b
assertIsNone(a, M) assertIsNotNone(a, M) a = nil; a ≠ nil
AssertIsInstance(a, b, M) AssertIsNotInstance(a, b, M) isinstance(a,b);
not isinstance(a,b)

Table 1: Basic asserts in unittest.

To check for just a True or False, use assertTrue() or assertFalse(), as in Listing Three:

Listing Three: Checking for True or False.

1
2
3
4
5
6
self.assertTrue(argState, "foobar() gave back a False")
# -- fires when the instance method foobar() returns a True
self.assertFalse(argState)
# -- fires when foobar() returns a False
# Notice this one does not supply an assert message

To check whether two arguments are the same, use assertEqual() and assertNotEqual() as in Listing Four. These last two asserts check the arguments’ values, as well as their data types.

Listing Four: Checking arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
argFoo = "narf"
argBar = "zort"
self.assertEqual(argFoo, argBar, "These are not the same")
# -- this assert will fail
self.assertNotEqual(argFoo, argBar, "These are the same")
# -- this assert will succeed
argFoo = 123
argBar = "123"
self.assertEqual(argFoo, argBar, "These are not the same")
# -- this assert will fail

To check if the arguments are the same objects, use assertIs() and assertIsNot(). Like assertEqual() and assertNotEqual(), these two asserts examine both argument values and type. To check if an argument is an instance of a specific class, use assertIsInstance() and assertIsNotInstance() as in Listing Five.

Listing Five: Checking if an argument is an instance of a specific class.

1
2
3
4
5
6
7
8
9
argFoo = Bar()
# checking against class Bar
self.assertIsInstance(argFoo, Bar, "The object is not an instance of class Bar")
# -- this assert will succeed
# checking against class Foo
self.assertIsNotInstance(argFoo, Foo, "The object is an instance of class Foo")
# -- this assert will fail

Both asserts get a class name as a second argument. Both behave similarly to the library function isInstance(). Finally, to check for a nil, use assertIsNone() and assertIsNotNone().

The second set of asserts are comparative (see Table 2).

Assert Complement Assert Operation
assertGreater(a, b, M) assertLess(a, b, M) a > b; a < b
assertGreaterEqual(a, b, M) assertLessEqual(a, b, M) a ≥ b; a ≤ b
assertAlmostEqual(a, b, n, M) assertNotAlmostEqual(a, b, n, M) round(a-b, n) = 0
round)a-b, n) ≠ 0
assertItemsEqual(a, b, M) none sort(a) = sort(b);
sort(a) ≠ sort(b)

Table 2: The comparative assertions.

To check whether one argument is greater or less than another, use assertGreater() and assertLess() as in Listing Six.

Listing Six: Greater or Less.

1
2
3
4
5
6
7
8
argFoo = 123
argBar = 452
self.assertGreater(argFoo, argBar, "Foo is less than Bar")
# -- this assert will fail
self.assertLess(argFoo, argBar, "Foo is greater than Bar")
# -- this assert will succeed

To check whether one argument is greater, less than or equal to the other, use assertGreaterEqual() and assertLessEqual(). The arguments in these four asserts can be a primitive (integer, float, character), a sequence, or a collection. Both arguments, however, must have the same data type.

To do a tolerance check, use assertAlmostEqual() and assertAlmostNotEqual(). These two asserts round off the arguments to a fixed number of decimal places before comparing their values. The number of decimal places is 7 by default. To change it, pass the new number with a places label.

To compare two sequences, use assertItemsEqual(). Its two arguments must be the same sequence type (list, tuple, set, and so on). Note that this assert sorts the sequence items prior to comparison.

Third set of asserts (Table 3) work with collection objects such as dictionaries, lists, sets, and tuples.

Assert Complement Assert Operation
assertIn(a, b, M) assertNotIn(a, b, M) a in b; a not in b
assertDictContainsSubset(a, b, M) none a has b
assertDictEqual(a, b, M) none a = b
assertListEqual(a, b, M) none a = b
assertSetEqual(a, b, M) none a = b
assertSequenceEqual(a, b, M) none a = b
assertTupleEqual(a, b, M) none a = b
assertMultilineEqual(a, b, M) none a = b

Table 3: Assertions for collections.

Arguments must be a collection type. Some assertions need not use arguments of the same type. All but one assert in this set have no complements.

To check whether one dictionary has some of the key/value pairs as the other, use assertDictContainsSubset() as shown in Listing Seven.

Listing Seven.

1
2
3
4
5
6
7
8
9
10
11
argBar = {'narf':456, 'poink':789}
self.assertDictContainsSubset(argFoo, argBar, "Foo does not have Bar")
# -- this assert will succeed
self.assertDictContainsSubset(argBar, argFoo, "Foo does not have Bar")
# -- this assert will fail
argBar = {'narf':456, 'egad':789}
self.assertDictContainsSubset(argFoo, argBar, "Foo does not have Bar")
# -- this assert will also fail

The first argument serves as reference; the second holds the pairs in question. To check if both dictionaries have the same key/value pairs, use assertDictEqual(). Each pair must have the same key labels and data values. How the pairs are arranged is irrelevant.

To check two sequence objects, use assertSequenceEqual(). Sequence types include lists, sets, tuples, even strings. For sequence objects to be same, they must have the same number of data items. The items must have the same value and they must be arranged the same. The sequence type must also be the same.

To check if two list objects are the same, use assertListEqual(). Both objects must have the same number of items. Those items must have the same values and the same order. To check two set objects, use assertSetEqual(). As with lists, both set objects must have the same number of items and item values. But item order is irrelevant, because set objects arrange their items internally.

Finally, to check if two tuples are the same, use assertTuplesEqual(). To check if two strings are the same, use assertMultilineEqual(). And to find out if one string is or is not inside another string, use assertIn() and assertNotIn().

This third set of asserts has one interesting behavior. If the collection objects are not equal, the assert will report the differences between the objects. It also adds this diff result to the assert message, if one is available.

Preparing a Test Suite

Usually, a few test cases are enough for your testing needs of a single class. But what if you have a dozen or more tests cases on hand — some you wrote yourself, some written by others? What if you want only a subset of test routines to run from the same test case? What if you want to refactor your test routines for easier cataloging and distribution? For these situations, you might need a test suite.

Figure 4 shows the basic structure of the TestSuite class.

Python Unit Tests
Figure 4: The TestSuite class.

There are three sets of instance methods. The first set lets us add test cases to the suite. To add a single test case, use the addTest() method as shown in Listing Eight.

Listing Eight.

1
2
3
4
5
6
7
8
9
10
class FooTest(unittest.TestCase):
    def testA(self):
        """Test routine A"""
        print "Running test A"
# creating a new test suite
newSuite = unittest.TestSuite()
# adding a test case
newSuite.addTest(unittest.makeSuite(FooTest))

Pass the test case (here being FooTest) to the instance method using the convenience function makeSuite(). You can also use makeSuite() to “convert” the test case into a test suite.

newSuite = unittest.makeSuite(FooTest)

To add a specific test routine, pass the test case object to the suite through the same addTest() method. Then pass the name of the test routine to the test case’s constructor. Notice the routine name is passed as a string.

newSuite.addTest(FooTest("testA"))

You can also use the same method to add two or more test routines to the same suite:

newSuite.addTest(FooTest(“testA”))
newSuite.addTest(FooTest(“testB”))
#…

To add two or more test cases, gather the names of the test cases into a list as shown in Listing Nine.

Listing Nine.

1
2
3
4
5
6
7
8
9
testList = [FooTest, BarTest]
testLoad = unittest.TestLoader()
caseList = []
for testCase in testList:
    testSuite = testLoad.loadTestsFromTestCase(testCase)
    caseList.append(testSuite)
newSuite = unittest.TestSuite(caseList)

Parse the list with a for loop, then use a TestLoader object (testLoad) to read each case. Add the read cases to a second list (caseList). Then create the TestSuite object (newSuite), passing to the class constructor the list object caseList.

Suppose you want to add another test suite to the suite. Simply pass the other suite to the addTest() method — no need to reuse the makeSuite() function to prepare the added suite.

fooSuite = unittest.TestSuite()
fooSuite.addTest(unittest.makeSuite(FooTest))
#...
barSuite = unittest.TestSuite()
barSuite.addTest(fooSuite)

The second set of methods run the tests in the test suite. The run() method takes a TestResult object as input, while debug() does not. But debug() does let an external debugger monitor the ongoing test.

Finally, the last set contains the method countTestCases(). This method returns the number of test cases held in the suite.

testCount = fooSuite.countTestCases()

Running the Tests

You have two ways to run your unit tests. If the test script is a single file with one or more test cases, add these lines after the last test case.

if name == "main":
unittest.main()

The if block detects how the file is acted upon. If the file is imported into another file, the macro __name__ is unchanged. If the file is executed directly, either from the text editor, from another script, or from the command-line, the __name__ macro resolves into "__main__", and the class method main() gets called. This in turn invokes the run() methods of every test case defined or imported by the script file.

If the script file defines a test suite, first create an instance of TextTestRunner. Then pass the test suite object to the runner’s run() method.

fooRunner = unittest.TextTestRunner()
fooRunner.run(fooSuite)

Regardless of approach, test cases and their routines run in alphanumeric order. BarTest runs before FooTest, FooTest before Test123, and test_12() before test_A(). Consider the test script in Listing Nine. In it, you have two test cases: BarTest and FooTest. BarTest has three test routines; FooTest has two.

Figure 5 shows how these two test cases run. BarTest runs first, FooTest second.

Python Unit Tests
Figure 5: BarTest and FooTest.

The test routines in BarTest run in the order from A to C. Those in FooTest run from 1 to 2. The same setUp() and tearDown() methods run before and after each test routine. But the BarTest routines have their own setUp() and tearDown(). The same also holds for the FooTest routines.

Finally, you have the option to skip or fail some of the test routines. To skip a routine unconditionally, use the class method unittest.skip() as shown in Listing Ten.

Listing Ten: Skipping a routine.

1
2
3
4
5
6
@unittest.skip("Skip over the entire test routine")
def testB():
    """Test routine B"""
    # the following code will not run
    fooA = narf()
    self.assertNotEqual(fooA, 123)

This method gets one argument: a log message describing the reason for the skip. Place the method call before the test routine, and make sure to prefix the call with a @ token. Alternatively, use the instance method skipTest(), which you can place inside the test routine as in Listing Eleven.

Listing Eleven.

1
2
3
4
5
6
"""Test routine B"""
self.skipTest("Skip over the rest of the routine")
# the following code will not run
fooA = narf()
self.assertNotEqual(fooA, 123)

 

To skip a test routine conditionally, use the class methods unittest.skipIf() and unittest.skipUnless() as in Listing Twelve:

Listing Twelve.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@unittest.skipIf(self.fooC > 456, "Skip over this routine")
def testB():
    """Test routine B"""
    # the following code will run only when fooC is less
    # than or equal to 456
    fooA = narf()
    self.assertNotEqual(fooA, 123)
@unittest.skipUnless(self.fooC > 456, "Skip over this routine")
def testC():
    """Test routine C"""
    # the following code will run only when fooC is
    # greater than 456
    fooA = zort()
    self.assertNotEqual(fooA, 123)

The first method causes a skip when a condition is met, the second when a condition is not met. Both get two arguments: the condition and the reason for the skip. Both must be placed before the test routine. The condition may involve a class property or another class method.

To fail a test routine, use the instance method fail() as in Listing Thirteen:

Listing Thirteen.

1
2
3
4
5
6
7
8
9
10
11
def testB():
    """Test routine B"""
    self.fail("Force this routine to fail.")
    
    # the following code will not run
    fooA = narf()
    self.assertNotEqual(fooA, 123)
def testC():
    """Test routine C"""
    print "This routine still runs after testB."

This method takes a log message explaining the reason for failure. Like skipTest(), the fail() method goes inside the test routine. Code placed after the call to fail() will not run, but test routines after the failed routine still get to run.

Viewing the Test Results

There are two possible forms of output from the TextTestRunner: console text or a TestResult object. First, let’s look at the console output, which shows each test’s result. You can control this output by passing three optional arguments to the class constructor.

unittest.TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1)

The first argument (labelled stream) sets the output destination. This defaults to sys.stderr if one is not specified. Next argument (labelled descriptions) controls how errors and failures are reported. Passing a True (default) tells the runner to name those routines that erred, failed, or skipped. Passing a False tells it not to.

The last constructor argument (labelled verbosity) sets the level of detail. There are three possible levels. For a verbosity of 0, the results show only the number of executed tests and the final outcome of those tests. For a verbosity of 1, the results marks a successful test with a dot, a failed one with an F, a skipped one with an s, and an erroneous one with an E. And for a verbosity of 2, the results lists each test case and test routine, plus the outcome of each routine.

To demonstrate, let’s run the test script in Listing Fourteen:

Listing Fourteen: Test script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import sys
import unittest
class FooTest(unittest2.TestCase):
    """Sample test case"""
    
    # preparing to test
    def setUp(self):
        """ Setting up for the test """
        print "FooTest:setUp_"
    
    # ending the test
    def tearDown(self):
        """Cleaning up after the test"""
        print "FooTest:tearDown_"
    
    # test routine A
    #@unittest2.skip("FooTest:test_A:skipped")
    def test_A(self):
        """Test routine A"""
        self.skipTest("FooTest:test_A:skipped")
        print "FooTest:test_A"
    
    # test routine B
    def test_B(self):
        """Test routine B"""
        fooA = 123
        fooB = 234
        self.assertEqual(fooA, fooB, "A is not equal to B")
        print "FooTest:test_B"
    
    # test routine C
    def test_C(self):
        """Test routine C"""
        fooA = 123
        self.assertEqual(fooA, fooB, "A is not equal to B")
        print "FooTest:test_C"
    
    # test routine D
    def test_D(self):
        """Test routine D"""
        self.fail("FooTest:test_D:fail_")
        print "FooTest:test_D"
# Run the test case
if __name__ == '__main__':
    fooSuite = unittest.TestLoader().loadTestsFromTestCase(FooTest)

If you create the test runner as follows:

fooRunner = unittest.TextTestRunner(description=True)
fooRunner.run(fooSuite)

The results appear as shown next:

sFEF
================================================================
ERROR: test_C (__main__.FooTest)
Test routine C
----------------------------------------------------------------

================================================================
FAIL: test_B (__main__.FooTest)
Test routine B
----------------------------------------------------------------

================================================================
FAIL: test_D (__main__.FooTest)
Test routine D
----------------------------------------------------------------

----------------------------------------------------------------
Ran 4 tests in 0.004s

FAILED (failures=2, errors=1, skipped=1) 

But if you create the runner as follows:

fooRunner = unittest.TextTestRunner(description=False)

The docstr comment line from each test routine will not be included.

The console output above has a verbosity level of 1. It starts with the line sFEF, which states two failed tests, one skipped, and one erroneous test. But suppose you created the test runner by typing

fooRunner = unittest.TextTestRunner(verbosity=0)

Then, the sFEF line will not appear. If you create the test runner by typing

fooRunner = unittest.TextTestRunner(verbosity=2)

Then the console output appears as:

test_A (__main__.FooTest)
Test routine A ... skipped 'FooTest:test_A:skipped'
test_B (__main__.FooTest)
Test routine B ... FAIL
test_C (__main__.FooTest)
Test routine C ... ERROR
test_D (__main__.FooTest)
Test routine D ... FAIL

================================================================
ERROR: test_C (__main__.FooTest)
Test routine C
----------------------------------------------------------------

================================================================
FAIL: test_B (__main__.FooTest)
Test routine B
----------------------------------------------------------------

================================================================
FAIL: test_D (__main__.FooTest)
Test routine D
----------------------------------------------------------------

----------------------------------------------------------------
Ran 4 tests in 0.009s

FAILED (failures=2, errors=1, skipped=1)

Note that the sFEF line is replaced by four pairs of lines, each pair naming the test case and routine, the final test state, the docstr comment of each routine, and any assert messages.

The second type of output is the TestResults object. This one is returned by the runner object after all the tests have run:

fooResult = fooRunner.run(fooSuite)

The TestResult object has two sets of property accessors (Figure 6).

Python Unit Tests
Figure 6: The TestResult object (in part).

This is not a complete set of accessors, but these are ones you will most likely use. The first set returns a list of tuples. Each tuple reveals how each test routine fared when executed. The errors accessor lists identified routines that raised an exception. Each tuple has the name of the test case and routine, the location of the test script, the line position of the error, a trace-back, and a reason for the error.

The failures accessor lists test routines that failed. Its tuples contain the same information as tuples from the errors accessor. The skipped accessor lists routines that were skipped, conditionally or not. Its tuples name the test case and routine, and give the reason for the skip.

The second set of accessors provides additional data. testsRun gives the number of test routines that ran, regardless of outcome. And wasSuccessful() returns a True if all routines ran without problems, False if at least one routine had a problem. Notice this last accessor is written as a function.

Listing Fifteen demonstrates how the TestResult object works.

Listing Fifteen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sys
import unittest
class FooTest(unittest.TestCase):
    """Sample test case"""
    
# Run the test case
if __name__ == '__main__':
    fooSuite = unittest.TestLoader().loadTestsFromTestCase(FooTest)
    
    fooRunner = unittest.TextTestRunner()
    fooResult = fooRunner.run(fooSuite)
    
    print
    print "---- START OF TEST RESULTS"
    print fooResult
    print
    print "fooResult::errors"
    print fooResult.errors
    print
    print "fooResult::failures"
    print fooResult.failures
    print
    print "fooResult::skipped"
    print fooResult.skipped
    print
    print "fooResult::successful"
    print fooResult.wasSuccessful()
    print
    print "fooResult::test-run"
    print fooResult.testsRun
    print "---- END OF TEST RESULTS"
    print

This script uses the same FooTest case defined in Listing Fourteen. After it invokes the run() method in the runner object fooRunner, the script stores the results into the local fooResults. Then it invokes each accessor and prints the test result on the console window.

Here are the test results returned by fooRunner:

---- START: Test Results:
<unittest2.runner.TextTestResult run=4 errors=1 failures=2>

fooResult::errors
[(<__main__.FooTest testMethod=test_C>, 'Traceback (most
recent call last):\n  File "/Volumes/Projects/Pro_Articles/_ddj/
18_pyUnitTest/ddj18_code/foo_testRun.py", line 49, in test_C\n    
self.assertEqual(fooA, fooB, "A is not equal to B")\nNameError: 
global name \'fooB\' is not defined\n')]

fooResult::failures
[(<__main__.FooTest testMethod=test_B>, 'Traceback (most 
recent call last):\n  File "/Volumes/Projects/Pro_Articles/_ddj/
18_pyUnitTest/ddj18_code/foo_testRun.py", line 41, in test_B\n    
self.assertEqual(fooA, fooB, "A is not equal to B")
\nAssertionError: 123 != 234 : A is not equal to B\n'), 
(<__main__.FooTest testMethod=test_D>, 'Traceback (most 
recent call last):\n  File "/Volumes/Projects/Pro_Articles/_ddj/
18_pyUnitTest/ddj18_code/foo_testRun.py", line 55, in test_D\n    
self.fail("FooTest:test_D:fail_")\nAssertionError: 
FooTest:test_D:fail_\n')]

fooResult::skipped
[(<__main__.FooTest testMethod=test_A>, 'FooTest:test_A:skipped')]

fooResult::successful?
False

fooResult::test-run
4

The second line summarizes the results. It shows the total number of test routines and how many routines have erred or failed. The paragraph below it reveals the erroneous routine: test_C(). It also reveals the cause of the error: the undefined variable fooB.

The next clump of text reveals the failed routines: test_B() and test_D(). It reveals why test_B() failed: two unequal values passed to assertEqual(). And it reveals that test_D() has explicitly called the instance method fail().

Below that is shown the skipped routine, test_A(). The next line shows what problems were encountered. And the last two lines report that a total of four test routines ran, confirming what was reported initially.

Conclusion

Python has substantial resources to enable unit testing. In this article, I looked into the unittest module and examined those classes essential for unit testing. I showed how to create a test case, how to design the test routines, and how to gather several test cases into one test suite.

The unittest module can do more than just run basic tests. With it, we can design tests that focus on exceptions or tests that do pattern matching. We can load and execute tests stored in separate files. We can even design tests that use simulated objects (known as mocks). But these are topics for a later article. Meanwhile, the “Recommended References” can provide additional guidance on these more-advanced features.

 

This Article Referenced from (http://www.drdobbs.com/testing/unit-testing-with-python)

For More Info on Python UnitTest

Recommended References

Test-Driven Development in Python, Jason Diamond. ONLamp.com/O’Reilly Publishing.

Introduction to unittest, Michael Foord. Voidspace.

unittest: Automated testing framework, Doug Hellman. PyMOTW.

unittest: Unit testing framework, Python 2.7.6 documentation.

Testing Your Code, Kenneth Reitz. The Hitchhiker’s Guide to Python.

__name__ == “__main__” in Python

When you run a python script directly (example: $ python script.py), you want to set a starting point of the script. Python scripts are interpreted from the first line, then goes to the second line and so on …

import module

def my_function():

code here

x = my_function()

But you want to make your code more structured, so you come up with this:

import module

def my_function():

code here

def main():
x = my_function()

the program starts from here

main()

This is good, but problem is, if you import the script from another script (from module import *), the main() function gets executed, but you may not want to do this. You want to call the main() function only when this script is exclusively executed. And you can do this using name == “main“.

import module

def my_function():

code here

def main():
x = my_function()

the program starts from here

if name == “main“:
main()

Thus you can make your script to make it a reusable script (import from another script) and a standalone script as well.