Show Menu

Unit testing in Python Cheat Sheet by metamad

Unit testin­g/TDD basics

Unit testing is an Agile/­Con­tinuous Integr­ation principle
Write tests before or during coding
Writing tests before == detailed requir­ements
Writing tests during == no over-c­oding
Unit testing assures code pre- and post-r­efa­ctoring behaves the same
Passed unit tests == CYA
Shared unit tests during sprints, for example, make it less likely that commits would break others' code
 

A test case:

* answers a single question

* runs by itself - automation

* determines by itself whether pass or fail (i.e. no human involv­­ement)

* runs in isolation from other test cases

http:­­//­w­­ww.d­Â­­iv­­ei­n­­top­Â­y­th­­on.n­­et­Â­/­un­­it­_­­tes­Â­t­in­­g/­d­­ivi­Â­n­g_­­in.h­tml

 

Unit testing in Python

my_t­est­_th­ing.py:

import unittest

# inherit from TestCase
# (a TestCase is a test fixture)
class MyTest­(un­itt­est.Te­stC­ase):
.....# method name starts with "­tes­t"!
.....def testMe­tho­d(s­elf):
..........se­lf.a­ss­ert­Equ­al(­4,3­,"4 not equal to 3")

if __name__ == "­__m­ain­__":
.....# called when exec from CL
.....u­nit­tes­t.m­ain()

------­­--­-­-­--­­---­­--­-­-­--­­---­­--­-­-­--­­---­--

calling from CL:
python my_tes­t_t­hin­g.py
prints
FAIL: testMethod (__mai­n__.My­Test)
-----­-­-­--­­---­­--­-­-­--­­---­­--­-­-­--­­---­­--­-­--
Traceback (most recent call last):
File "­my_­tes­t_t­hin­g.p­y", line 6,
in testMe­thod
self.a­sse­rtE­qua­l(1­0,1­1,"10 != 11")
Assert­ion­Error: 10 != 11
-----­---­---­---­---­---­---­---­---­----
Ran 1 test in 0.000s
FAILED (failu­res=1)

indicates tab: "....."

 

Share This Cheat Sheet!

Favourited by 2 Members:

Eric Normandeau fire9

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.