Show Menu

Unit testing in Python Cheat Sheet by

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

Unit testing in Python


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):­lf.a­ss­ert­Equ­al(­4,3­,"4 not equal to 3")

if __name__ == "­__m­ain­__":
.....# called when exec from CL


calling from CL:
python my_tes­t_t­hin­
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 Cheatographers:

Eric Normandeau fire9


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.