SlideShare une entreprise Scribd logo
1  sur  51
Object Oriented Testing
(Unit Testing)
Damian Gordon
Object Oriented Testing
• Unit Testing is concerned with testing small chunks of a
program, for example, testing a single class or a single method.
• Python has a library for unit testing called unittest. It
provides several tools for creating and running unit tests.
Object Oriented Testing
• One of the most important classes in unittest is called
TestCase which provides a set of methods to compare
values, set up tests and clean up after tests are finished.
• To write unit tests, we create a subclass of TestCase and
write individual methods to do the actual testing. Typically we
start all of these methods with the name test.
Object Oriented Testing
• Let’s look at a simple example:
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Create a subclass of
the TestCase class
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Create a subclass of
the TestCase class
This test checks if the
integer and real
value 1 are equal.
Object Oriented Testing
• Let’s look at a simple example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Make sure this is
being run as a script
Create a subclass of
the TestCase class
This test checks if the
integer and real
value 1 are equal.
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
.
-------------------------------------------------
Ran 1 test in 0.020s
OK
Object Oriented Testing
• And if we run this, we get:
.
-------------------------------------------------
Ran 1 test in 0.020s
OK
Dot means the test has passed
Object Oriented Testing
• Let’s try another example:
Object Oriented Testing
• Let’s try another example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_string_float(self):
self.assertEqual(“1”, 1.0)
# END test_string_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
Object Oriented Testing
• Let’s try another example:
import unittest
class CheckNumbers(unittest.TestCase):
def test_string_float(self):
self.assertEqual(“1”, 1.0)
# END test_string_float
# END CheckNumbers
if __name__ == "__main__":
unittest.main()
# ENDIF
This test checks if the
string and real value
1 are equal.
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
F
=========================================================
FAIL: test_string_float (__main__.CheckNumbers)
This test checks if the string and real value 1 are equal.
--------------------------------------------------------
Traceback (most recent call last):
File "C:/Users/damian/AppData/Local/Programs/Python/Python35-
32/CheckNumbers-string-float.py", line 9, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
--------------------------------------------------------
Ran 1 test in 0.060s
FAILED (failures=1)
Object Oriented Testing
• And if we run this, we get:
F
=========================================================
FAIL: test_string_float (__main__.CheckNumbers)
This test checks if the string and real value 1 are equal.
--------------------------------------------------------
Traceback (most recent call last):
File "C:/Users/damian/AppData/Local/Programs/Python/Python35-
32/CheckNumbers-string-float.py", line 9, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
--------------------------------------------------------
Ran 1 test in 0.060s
FAILED (failures=1)
“F” means the test has failed
Object Oriented Testing
• Let’s combine the two tests together:
Object Oriented Testing
• Let’s combine the two tests together:
import unittest
class CheckNumbers(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
# ENDIF
def test_int_float(self):
self.assertEqual(1, 1.0)
# END test_int_float
def test_string_float(self):
self.assertEqual(“1”, 1.0)
# END test_string_float
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
.F
=================================================================
FAIL: test_string_float (__main__.CheckNumbers)
---------------------------=-------------------------------------
Traceback (most recent call last):
File "C:UsersdamianAppDataLocalProgramsPythonPython35-
32CheckNumbers.py", line 10, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
-----------------------------------------------------------------
Ran 2 tests in 0.010s
FAILED (failures=1)
Object Oriented Testing
• And if we run this, we get:
.F
=================================================================
FAIL: test_string_float (__main__.CheckNumbers)
---------------------------=-------------------------------------
Traceback (most recent call last):
File "C:UsersdamianAppDataLocalProgramsPythonPython35-
32CheckNumbers.py", line 10, in test_string_float
self.assertEqual("1", 1.0)
AssertionError: '1' != 1.0
-----------------------------------------------------------------
Ran 2 tests in 0.010s
FAILED (failures=1)
“.F” means the first test passed and the
second test has failed
Assertion Methods
Object Oriented Testing
• A test case typically sets certain variables to known values, runs
one or more methods or processes, and then show that correct
expected results were returned by using TestCase assertion
methods.
• There are a few different assertion methods available to confirm
that specific results have been achieved. We already saw
assertEqual, which will cause a test failure if the two
parameters do not pass an equality check. The inverse,
assertNotEqual, will fail if the two parameters do compare as
equal.
Object Oriented Testing
• The assertTrue and assertFalse methods each accept
a single expression, and fail if the expression does not pass an
IF test. These tests are not checking for the Boolean values
True or False, but instead:
– To pass the assertFalse method the test should return False,
None, 0, or an empty list, dictionary, string, set, or tuple.
– To pass the assertFalse method the test should return True,
non-zero numbers, containers with values in.
Methods Description
assertEqual
assertNotEqual
Accept two comparable objects and ensure the named equality
holds.
assertTrue
assertFalse
Accept a single expression, and fail if the expression does not
pass an IF test.
assertGreater
assertGreaterEqual
assertLess
assertLessEqual
Accept two comparable objects and ensure the named
inequality holds.
asssertIn
assertNotIn
Ensure an element is (or is not) an element in a container
object.
assertIsNone
assertIsNotNone
Ensure an element is (or is not) the exact value None (but not
another false value).
assertSameElements Ensure two container objects have the same elements, ignoring
the order.
assertSequenceEqualassertDictEqual
assertSetEqual
assertListEqual
assertTupleEqual
Ensure two containers have the same elements in the same
order. If there's a failure, show a code diff comparing the two
lists to see where they differ. The last four methods also test the
type of the list.
assertRaises Ensure that a specific function call raises a specific exception.
Object Oriented Testing
• Let’s look at the assertRaises method in a bit more detail.
• This method can be used to ensure a specific function call
raises a specific exception. The test passes if the code inside
the with statement raises the proper exception; otherwise, it
fails.
Object Oriented Testing
• Let’s look at an example:
Object Oriented Testing
• Let’s look at an example:
import unittest
def MyAverage(seq):
return sum(seq) / len(seq)
# END average
Continued 
• Let’s look at an example:
Object Oriented Testing
class TestAverage(unittest.TestCase):
def test_zero(self):
self.assertRaises(ZeroDivisionError, MyAverage, [])
# END test_zero
def test_with_zero(self):
with self.assertRaises(ZeroDivisionError):
MyAverage([])
# END test_with_zero
# END CLASS TestAverage
Continued 
 Continued
• Let’s look at an example:
Object Oriented Testing
class TestAverage(unittest.TestCase):
def test_zero(self):
self.assertRaises(ZeroDivisionError, MyAverage, [])
# END test_zero
def test_with_zero(self):
with self.assertRaises(ZeroDivisionError):
MyAverage([])
# END test_with_zero
# END CLASS TestAverage
Continued 
 Continued
We can test if a call to
MyAverage gives an error is
a blank list is passed in
• Let’s look at an example:
Object Oriented Testing
class TestAverage(unittest.TestCase):
def test_zero(self):
self.assertRaises(ZeroDivisionError, MyAverage, [])
# END test_zero
def test_with_zero(self):
with self.assertRaises(ZeroDivisionError):
MyAverage([])
# END test_with_zero
# END CLASS TestAverage
Continued 
 Continued
We can test if a call to
MyAverage gives an error is
a blank list is passed in
The same test, but calling the
method directly, which will
return a divide-by-zero error,
so we need to use the with
statement to tidy up.
Object Oriented Testing
• Let’s look at an example:
if __name__ == "__main__":
unittest.main()
# ENDIF
 Continued
Object Oriented Testing
• Now let’s look at a more detailed example.
• Let’s look at a program, and it’s test program:
Stats.py Stats-test.py
class StatsList class TestValidInputs
def mean
def median
def mode
def test_mean
def test_median
def test_mode
Object Oriented Testing
• Here’s stats.py:
from collections import defaultdict
class StatsList(list):
def mean(self):
return sum(self) / len(self)
# END mean
Continued 
• Here’s stats.py:
Object Oriented Testing
Continued 
 Continued
def median(self):
if len(self) % 2:
return self[int(len(self) / 2)]
else:
idx = int(len(self) / 2)
return (self[idx] + self[idx-1]) / 2
# ENDIF
# END median
• Here’s stats.py:
Object Oriented Testing
 Continued
def mode(self):
freqs = defaultdict(int)
for item in self:
freqs[item] += 1
mode_freq = max(freqs.values())
modes = []
for item, value in freqs.items():
if value == mode_freq:
modes.append(item)
# ENDIF
# ENDFOR
return modes
# END mode
Object Oriented Testing
• We are going to test this program by creating a new file with
our testing code in it.
• So we’ll import unittest, and use the TestCase class
from it, to create a setUp method to do initialization for each
test.
• The setUp method accepts no arguments, and allows us to do
arbitrary setup before each test is run.
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Import the program we’ve just
created, and it’s main class.
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Import the program we’ve just
created, and it’s main class.
Import unittest.
Object Oriented Testing
• Here’s stats-test.py:
from stats import StatsList
import unittest
class TestValidInputs(unittest.TestCase):
def setUp(self):
self.stats = StatsList([1,2,2,3,3,4])
# END setUp
Continued 
Import the program we’ve just
created, and it’s main class.
Import unittest.
Create the setup method, to
set up values to be tested.
• Here’s stats-test.py:
Object Oriented Testing
Continued 
 Continued
def test_mean(self):
self.assertEqual(self.stats.mean(), 2.5)
# END test_mean
• Here’s stats-test.py:
Object Oriented Testing
Continued 
 Continued
def test_median(self):
self.assertEqual(self.stats.median(), 2.5)
self.stats.append(4)
self.assertEqual(self.stats.median(), 3)
# END test_median
• Here’s stats-test.py:
Object Oriented Testing
 Continued
def test_mode(self):
self.assertEqual(self.stats.mode(), [2,3])
self.stats.remove(2)
self.assertEqual(self.stats.mode(), [3])
# END test_mode
Object Oriented Testing
• And if we run this, we get:
Object Oriented Testing
• And if we run this, we get:
...
----------------------------------------------------------
Ran 3 tests in 0.050s
OK
Object Oriented Testing
• And if we run this, we get:
...
----------------------------------------------------------
Ran 3 tests in 0.050s
OK
“…” means all three tests have passed
Object Oriented Testing
• The setUp method is never explicitly called inside any of the
three test_* methods, the test suite does the call.
• Also note that test_median alters the list, by adding a “4”
to it, yet when test_mode is called, the list has returned to
the values specified in setUp. This shows that setUp is called
individually before each test, to ensure the test class starts
with a clean slate. Tests can be executed in any order, and the
results of one test should not depend on any other tests.
Object Oriented Testing
• TestCase also offers a no-argument tearDown method, which
can be used for cleaning up after each and every test on the class
has run.
• This is useful, for example, if we are testing code that does file I/O,
our tests may create new files as a side effect of testing; the
tearDown method can remove these files and ensure the system
is in the same state it was before the tests ran.
• Test cases should never have side effects.
etc.

Contenu connexe

Tendances

Using Git/Gerrit and Jenkins to Manage the Code Review Processord
Using Git/Gerrit and Jenkins to Manage the Code Review ProcessordUsing Git/Gerrit and Jenkins to Manage the Code Review Processord
Using Git/Gerrit and Jenkins to Manage the Code Review ProcessordMarc Karasek
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriverAnuraj S.L
 
코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011Esun Kim
 
Top 50 Software Testing Interview Questions & Answers | Edureka
Top 50 Software Testing Interview Questions & Answers | EdurekaTop 50 Software Testing Interview Questions & Answers | Edureka
Top 50 Software Testing Interview Questions & Answers | EdurekaEdureka!
 
Web automation using selenium.ppt
Web automation using selenium.pptWeb automation using selenium.ppt
Web automation using selenium.pptAna Sarbescu
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftallanh0526
 
Testes de ponta a ponta
Testes de ponta a pontaTestes de ponta a ponta
Testes de ponta a pontaElias Nogueira
 
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템강 민우
 
Selenium with Cucumber
Selenium  with Cucumber Selenium  with Cucumber
Selenium with Cucumber Knoldus Inc.
 
Software Testing - Test Design Techniques
Software Testing - Test Design TechniquesSoftware Testing - Test Design Techniques
Software Testing - Test Design TechniquesRegina Vitalicio
 
Intellij idea tutorial
Intellij idea tutorialIntellij idea tutorial
Intellij idea tutorialHarikaReddy115
 
QA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. SeleniumQA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. SeleniumLyudmil Latinov
 
What is WebElement in Selenium | Web Elements & Element Locators | Edureka
What is WebElement in Selenium | Web Elements & Element Locators | EdurekaWhat is WebElement in Selenium | Web Elements & Element Locators | Edureka
What is WebElement in Selenium | Web Elements & Element Locators | EdurekaEdureka!
 
Test Automation and Selenium
Test Automation and SeleniumTest Automation and Selenium
Test Automation and SeleniumKarapet Sarkisyan
 
How to Release Rock-solid RESTful APIs and Ice the Testing BackBlob
How to Release Rock-solid RESTful APIs and Ice the Testing BackBlobHow to Release Rock-solid RESTful APIs and Ice the Testing BackBlob
How to Release Rock-solid RESTful APIs and Ice the Testing BackBlobBob Binder
 

Tendances (20)

Api security-testing
Api security-testingApi security-testing
Api security-testing
 
Using Git/Gerrit and Jenkins to Manage the Code Review Processord
Using Git/Gerrit and Jenkins to Manage the Code Review ProcessordUsing Git/Gerrit and Jenkins to Manage the Code Review Processord
Using Git/Gerrit and Jenkins to Manage the Code Review Processord
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
 
코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011코드 생성을 사용해 개발 속도 높이기 NDC2011
코드 생성을 사용해 개발 속도 높이기 NDC2011
 
Top 50 Software Testing Interview Questions & Answers | Edureka
Top 50 Software Testing Interview Questions & Answers | EdurekaTop 50 Software Testing Interview Questions & Answers | Edureka
Top 50 Software Testing Interview Questions & Answers | Edureka
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Web automation using selenium.ppt
Web automation using selenium.pptWeb automation using selenium.ppt
Web automation using selenium.ppt
 
Unit testing in xcode 8 with swift
Unit testing in xcode 8 with swiftUnit testing in xcode 8 with swift
Unit testing in xcode 8 with swift
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Testes de ponta a ponta
Testes de ponta a pontaTestes de ponta a ponta
Testes de ponta a ponta
 
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
[IGC 2016] 엔씨소프트 김종원 - 모바일 테스트 자동화 시스템
 
Selenium with Cucumber
Selenium  with Cucumber Selenium  with Cucumber
Selenium with Cucumber
 
Software Testing - Test Design Techniques
Software Testing - Test Design TechniquesSoftware Testing - Test Design Techniques
Software Testing - Test Design Techniques
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
 
Intellij idea tutorial
Intellij idea tutorialIntellij idea tutorial
Intellij idea tutorial
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 
QA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. SeleniumQA Challenge Accepted 4.0 - Cypress vs. Selenium
QA Challenge Accepted 4.0 - Cypress vs. Selenium
 
What is WebElement in Selenium | Web Elements & Element Locators | Edureka
What is WebElement in Selenium | Web Elements & Element Locators | EdurekaWhat is WebElement in Selenium | Web Elements & Element Locators | Edureka
What is WebElement in Selenium | Web Elements & Element Locators | Edureka
 
Test Automation and Selenium
Test Automation and SeleniumTest Automation and Selenium
Test Automation and Selenium
 
How to Release Rock-solid RESTful APIs and Ice the Testing BackBlob
How to Release Rock-solid RESTful APIs and Ice the Testing BackBlobHow to Release Rock-solid RESTful APIs and Ice the Testing BackBlob
How to Release Rock-solid RESTful APIs and Ice the Testing BackBlob
 

En vedette

Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
 
Python: Object-oriented Testing
Python: Object-oriented TestingPython: Object-oriented Testing
Python: Object-oriented TestingDamian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator PatternDamian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Python: Common Design Patterns
Python: Common Design PatternsPython: Common Design Patterns
Python: Common Design PatternsDamian T. Gordon
 
Operating Systems: Virtual Memory
Operating Systems: Virtual MemoryOperating Systems: Virtual Memory
Operating Systems: Virtual MemoryDamian T. Gordon
 
Operating Systems: Memory Management
Operating Systems: Memory ManagementOperating Systems: Memory Management
Operating Systems: Memory ManagementDamian T. Gordon
 
Testing of Object-Oriented Software
Testing of Object-Oriented SoftwareTesting of Object-Oriented Software
Testing of Object-Oriented SoftwarePraveen Penumathsa
 
Use of Specularities and Motion in the Extraction of Surface Shape
Use of Specularities and Motion in the Extraction of Surface ShapeUse of Specularities and Motion in the Extraction of Surface Shape
Use of Specularities and Motion in the Extraction of Surface ShapeDamian T. Gordon
 
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...The Use of Behavioural Economics to Encourage First-Year Completion and Reten...
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...Damian T. Gordon
 
A Compendium of Creativity Tools
A Compendium of Creativity ToolsA Compendium of Creativity Tools
A Compendium of Creativity ToolsDamian T. Gordon
 
Concepts from Random Words
Concepts from Random WordsConcepts from Random Words
Concepts from Random WordsDamian T. Gordon
 
Diagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont ReportDiagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont ReportDamian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party LibrariesDamian T. Gordon
 
Computer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image UnderstandingComputer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image UnderstandingDamian T. Gordon
 

En vedette (20)

Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
 
How to Program
How to ProgramHow to Program
How to Program
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Python: Object-oriented Testing
Python: Object-oriented TestingPython: Object-oriented Testing
Python: Object-oriented Testing
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Python: Common Design Patterns
Python: Common Design PatternsPython: Common Design Patterns
Python: Common Design Patterns
 
Operating Systems: Virtual Memory
Operating Systems: Virtual MemoryOperating Systems: Virtual Memory
Operating Systems: Virtual Memory
 
Operating Systems: Memory Management
Operating Systems: Memory ManagementOperating Systems: Memory Management
Operating Systems: Memory Management
 
Testing of Object-Oriented Software
Testing of Object-Oriented SoftwareTesting of Object-Oriented Software
Testing of Object-Oriented Software
 
Use of Specularities and Motion in the Extraction of Surface Shape
Use of Specularities and Motion in the Extraction of Surface ShapeUse of Specularities and Motion in the Extraction of Surface Shape
Use of Specularities and Motion in the Extraction of Surface Shape
 
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...The Use of Behavioural Economics to Encourage First-Year Completion and Reten...
The Use of Behavioural Economics to Encourage First-Year Completion and Reten...
 
A Compendium of Creativity Tools
A Compendium of Creativity ToolsA Compendium of Creativity Tools
A Compendium of Creativity Tools
 
Concepts from Random Words
Concepts from Random WordsConcepts from Random Words
Concepts from Random Words
 
Creative Commons Sites
Creative Commons SitesCreative Commons Sites
Creative Commons Sites
 
Diagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont ReportDiagrams of the 2009 Claremont Report
Diagrams of the 2009 Claremont Report
 
The Only Way is Ethics
The Only Way is EthicsThe Only Way is Ethics
The Only Way is Ethics
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
 
Computer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image UnderstandingComputer Vision: Reflectance Analysis for Image Understanding
Computer Vision: Reflectance Analysis for Image Understanding
 

Similaire à Python: Object-Oriented Testing (Unit Testing)

SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)Amr E. Mohamed
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnitAktuğ Urun
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Fariz Darari
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitAmr E. Mohamed
 
Dreamforce Campfire - Apex Testing Tips and Tricks
Dreamforce Campfire - Apex Testing Tips and TricksDreamforce Campfire - Apex Testing Tips and Tricks
Dreamforce Campfire - Apex Testing Tips and TricksDaniel Ballinger
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingOrtus Solutions, Corp
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 

Similaire à Python: Object-Oriented Testing (Unit Testing) (20)

Junit
JunitJunit
Junit
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Junit
JunitJunit
Junit
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
TDD Training
TDD TrainingTDD Training
TDD Training
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Dreamforce Campfire - Apex Testing Tips and Tricks
Dreamforce Campfire - Apex Testing Tips and TricksDreamforce Campfire - Apex Testing Tips and Tricks
Dreamforce Campfire - Apex Testing Tips and Tricks
 
Just Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration TestingJust Do It! ColdBox Integration Testing
Just Do It! ColdBox Integration Testing
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Unit testing
Unit testingUnit testing
Unit testing
 

Plus de Damian T. Gordon

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Damian T. Gordon
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesDamian T. Gordon
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingDamian T. Gordon
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSDamian T. Gordon
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOTDamian T. Gordon
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricDamian T. Gordon
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDamian T. Gordon
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSUREDamian T. Gordon
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDamian T. Gordon
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDamian T. Gordon
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDamian T. Gordon
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsDamian T. Gordon
 

Plus de Damian T. Gordon (20)

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Cloud Identity Management
Cloud Identity ManagementCloud Identity Management
Cloud Identity Management
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Introduction to ChatGPT
Introduction to ChatGPTIntroduction to ChatGPT
Introduction to ChatGPT
 
How to Argue Logically
How to Argue LogicallyHow to Argue Logically
How to Argue Logically
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONS
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOT
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson Rubric
 
Evaluating Teaching: LORI
Evaluating Teaching: LORIEvaluating Teaching: LORI
Evaluating Teaching: LORI
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause Procedure
 
Designing Teaching: ADDIE
Designing Teaching: ADDIEDesigning Teaching: ADDIE
Designing Teaching: ADDIE
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSURE
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning Types
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of Instruction
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration Theory
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some Considerations
 

Dernier

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 

Dernier (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

Python: Object-Oriented Testing (Unit Testing)

  • 1. Object Oriented Testing (Unit Testing) Damian Gordon
  • 2. Object Oriented Testing • Unit Testing is concerned with testing small chunks of a program, for example, testing a single class or a single method. • Python has a library for unit testing called unittest. It provides several tools for creating and running unit tests.
  • 3. Object Oriented Testing • One of the most important classes in unittest is called TestCase which provides a set of methods to compare values, set up tests and clean up after tests are finished. • To write unit tests, we create a subclass of TestCase and write individual methods to do the actual testing. Typically we start all of these methods with the name test.
  • 4. Object Oriented Testing • Let’s look at a simple example:
  • 5. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF
  • 6. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF Create a subclass of the TestCase class
  • 7. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF Create a subclass of the TestCase class This test checks if the integer and real value 1 are equal.
  • 8. Object Oriented Testing • Let’s look at a simple example: import unittest class CheckNumbers(unittest.TestCase): def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF Make sure this is being run as a script Create a subclass of the TestCase class This test checks if the integer and real value 1 are equal.
  • 9. Object Oriented Testing • And if we run this, we get:
  • 10. Object Oriented Testing • And if we run this, we get: . ------------------------------------------------- Ran 1 test in 0.020s OK
  • 11. Object Oriented Testing • And if we run this, we get: . ------------------------------------------------- Ran 1 test in 0.020s OK Dot means the test has passed
  • 12. Object Oriented Testing • Let’s try another example:
  • 13. Object Oriented Testing • Let’s try another example: import unittest class CheckNumbers(unittest.TestCase): def test_string_float(self): self.assertEqual(“1”, 1.0) # END test_string_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF
  • 14. Object Oriented Testing • Let’s try another example: import unittest class CheckNumbers(unittest.TestCase): def test_string_float(self): self.assertEqual(“1”, 1.0) # END test_string_float # END CheckNumbers if __name__ == "__main__": unittest.main() # ENDIF This test checks if the string and real value 1 are equal.
  • 15. Object Oriented Testing • And if we run this, we get:
  • 16. Object Oriented Testing • And if we run this, we get: F ========================================================= FAIL: test_string_float (__main__.CheckNumbers) This test checks if the string and real value 1 are equal. -------------------------------------------------------- Traceback (most recent call last): File "C:/Users/damian/AppData/Local/Programs/Python/Python35- 32/CheckNumbers-string-float.py", line 9, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 -------------------------------------------------------- Ran 1 test in 0.060s FAILED (failures=1)
  • 17. Object Oriented Testing • And if we run this, we get: F ========================================================= FAIL: test_string_float (__main__.CheckNumbers) This test checks if the string and real value 1 are equal. -------------------------------------------------------- Traceback (most recent call last): File "C:/Users/damian/AppData/Local/Programs/Python/Python35- 32/CheckNumbers-string-float.py", line 9, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 -------------------------------------------------------- Ran 1 test in 0.060s FAILED (failures=1) “F” means the test has failed
  • 18. Object Oriented Testing • Let’s combine the two tests together:
  • 19. Object Oriented Testing • Let’s combine the two tests together: import unittest class CheckNumbers(unittest.TestCase): if __name__ == "__main__": unittest.main() # ENDIF def test_int_float(self): self.assertEqual(1, 1.0) # END test_int_float def test_string_float(self): self.assertEqual(“1”, 1.0) # END test_string_float
  • 20. Object Oriented Testing • And if we run this, we get:
  • 21. Object Oriented Testing • And if we run this, we get: .F ================================================================= FAIL: test_string_float (__main__.CheckNumbers) ---------------------------=------------------------------------- Traceback (most recent call last): File "C:UsersdamianAppDataLocalProgramsPythonPython35- 32CheckNumbers.py", line 10, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 ----------------------------------------------------------------- Ran 2 tests in 0.010s FAILED (failures=1)
  • 22. Object Oriented Testing • And if we run this, we get: .F ================================================================= FAIL: test_string_float (__main__.CheckNumbers) ---------------------------=------------------------------------- Traceback (most recent call last): File "C:UsersdamianAppDataLocalProgramsPythonPython35- 32CheckNumbers.py", line 10, in test_string_float self.assertEqual("1", 1.0) AssertionError: '1' != 1.0 ----------------------------------------------------------------- Ran 2 tests in 0.010s FAILED (failures=1) “.F” means the first test passed and the second test has failed
  • 24. Object Oriented Testing • A test case typically sets certain variables to known values, runs one or more methods or processes, and then show that correct expected results were returned by using TestCase assertion methods. • There are a few different assertion methods available to confirm that specific results have been achieved. We already saw assertEqual, which will cause a test failure if the two parameters do not pass an equality check. The inverse, assertNotEqual, will fail if the two parameters do compare as equal.
  • 25. Object Oriented Testing • The assertTrue and assertFalse methods each accept a single expression, and fail if the expression does not pass an IF test. These tests are not checking for the Boolean values True or False, but instead: – To pass the assertFalse method the test should return False, None, 0, or an empty list, dictionary, string, set, or tuple. – To pass the assertFalse method the test should return True, non-zero numbers, containers with values in.
  • 26. Methods Description assertEqual assertNotEqual Accept two comparable objects and ensure the named equality holds. assertTrue assertFalse Accept a single expression, and fail if the expression does not pass an IF test. assertGreater assertGreaterEqual assertLess assertLessEqual Accept two comparable objects and ensure the named inequality holds. asssertIn assertNotIn Ensure an element is (or is not) an element in a container object. assertIsNone assertIsNotNone Ensure an element is (or is not) the exact value None (but not another false value). assertSameElements Ensure two container objects have the same elements, ignoring the order. assertSequenceEqualassertDictEqual assertSetEqual assertListEqual assertTupleEqual Ensure two containers have the same elements in the same order. If there's a failure, show a code diff comparing the two lists to see where they differ. The last four methods also test the type of the list. assertRaises Ensure that a specific function call raises a specific exception.
  • 27. Object Oriented Testing • Let’s look at the assertRaises method in a bit more detail. • This method can be used to ensure a specific function call raises a specific exception. The test passes if the code inside the with statement raises the proper exception; otherwise, it fails.
  • 28. Object Oriented Testing • Let’s look at an example:
  • 29. Object Oriented Testing • Let’s look at an example: import unittest def MyAverage(seq): return sum(seq) / len(seq) # END average Continued 
  • 30. • Let’s look at an example: Object Oriented Testing class TestAverage(unittest.TestCase): def test_zero(self): self.assertRaises(ZeroDivisionError, MyAverage, []) # END test_zero def test_with_zero(self): with self.assertRaises(ZeroDivisionError): MyAverage([]) # END test_with_zero # END CLASS TestAverage Continued   Continued
  • 31. • Let’s look at an example: Object Oriented Testing class TestAverage(unittest.TestCase): def test_zero(self): self.assertRaises(ZeroDivisionError, MyAverage, []) # END test_zero def test_with_zero(self): with self.assertRaises(ZeroDivisionError): MyAverage([]) # END test_with_zero # END CLASS TestAverage Continued   Continued We can test if a call to MyAverage gives an error is a blank list is passed in
  • 32. • Let’s look at an example: Object Oriented Testing class TestAverage(unittest.TestCase): def test_zero(self): self.assertRaises(ZeroDivisionError, MyAverage, []) # END test_zero def test_with_zero(self): with self.assertRaises(ZeroDivisionError): MyAverage([]) # END test_with_zero # END CLASS TestAverage Continued   Continued We can test if a call to MyAverage gives an error is a blank list is passed in The same test, but calling the method directly, which will return a divide-by-zero error, so we need to use the with statement to tidy up.
  • 33. Object Oriented Testing • Let’s look at an example: if __name__ == "__main__": unittest.main() # ENDIF  Continued
  • 34. Object Oriented Testing • Now let’s look at a more detailed example. • Let’s look at a program, and it’s test program: Stats.py Stats-test.py class StatsList class TestValidInputs def mean def median def mode def test_mean def test_median def test_mode
  • 35. Object Oriented Testing • Here’s stats.py: from collections import defaultdict class StatsList(list): def mean(self): return sum(self) / len(self) # END mean Continued 
  • 36. • Here’s stats.py: Object Oriented Testing Continued   Continued def median(self): if len(self) % 2: return self[int(len(self) / 2)] else: idx = int(len(self) / 2) return (self[idx] + self[idx-1]) / 2 # ENDIF # END median
  • 37. • Here’s stats.py: Object Oriented Testing  Continued def mode(self): freqs = defaultdict(int) for item in self: freqs[item] += 1 mode_freq = max(freqs.values()) modes = [] for item, value in freqs.items(): if value == mode_freq: modes.append(item) # ENDIF # ENDFOR return modes # END mode
  • 38. Object Oriented Testing • We are going to test this program by creating a new file with our testing code in it. • So we’ll import unittest, and use the TestCase class from it, to create a setUp method to do initialization for each test. • The setUp method accepts no arguments, and allows us to do arbitrary setup before each test is run.
  • 39. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued 
  • 40. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued  Import the program we’ve just created, and it’s main class.
  • 41. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued  Import the program we’ve just created, and it’s main class. Import unittest.
  • 42. Object Oriented Testing • Here’s stats-test.py: from stats import StatsList import unittest class TestValidInputs(unittest.TestCase): def setUp(self): self.stats = StatsList([1,2,2,3,3,4]) # END setUp Continued  Import the program we’ve just created, and it’s main class. Import unittest. Create the setup method, to set up values to be tested.
  • 43. • Here’s stats-test.py: Object Oriented Testing Continued   Continued def test_mean(self): self.assertEqual(self.stats.mean(), 2.5) # END test_mean
  • 44. • Here’s stats-test.py: Object Oriented Testing Continued   Continued def test_median(self): self.assertEqual(self.stats.median(), 2.5) self.stats.append(4) self.assertEqual(self.stats.median(), 3) # END test_median
  • 45. • Here’s stats-test.py: Object Oriented Testing  Continued def test_mode(self): self.assertEqual(self.stats.mode(), [2,3]) self.stats.remove(2) self.assertEqual(self.stats.mode(), [3]) # END test_mode
  • 46. Object Oriented Testing • And if we run this, we get:
  • 47. Object Oriented Testing • And if we run this, we get: ... ---------------------------------------------------------- Ran 3 tests in 0.050s OK
  • 48. Object Oriented Testing • And if we run this, we get: ... ---------------------------------------------------------- Ran 3 tests in 0.050s OK “…” means all three tests have passed
  • 49. Object Oriented Testing • The setUp method is never explicitly called inside any of the three test_* methods, the test suite does the call. • Also note that test_median alters the list, by adding a “4” to it, yet when test_mode is called, the list has returned to the values specified in setUp. This shows that setUp is called individually before each test, to ensure the test class starts with a clean slate. Tests can be executed in any order, and the results of one test should not depend on any other tests.
  • 50. Object Oriented Testing • TestCase also offers a no-argument tearDown method, which can be used for cleaning up after each and every test on the class has run. • This is useful, for example, if we are testing code that does file I/O, our tests may create new files as a side effect of testing; the tearDown method can remove these files and ensure the system is in the same state it was before the tests ran. • Test cases should never have side effects.
  • 51. etc.