Movatterモバイル変換


[0]ホーム

URL:


Ganesh Bhosale, profile picture
Uploaded byGanesh Bhosale
PPTX, PDF19 views

2.Python_Testing_Using_PyUnit_PyTest.pptx

Testing 2

Embed presentation

Download to read offline
PyUnit
Overview• Unit Testing Basics: What, Why, When• How: Python Unit Test Class• Unit Test Writing Tips and Resources
Unit Testing Basics• Functional tests: done by QA to testfunctionality according to a test plan basedon requirements and design specs.• Unit tests: done by developers to testspecific code. Typically “white box” testing.• Essential part of Extreme Programming andother agile methods.
Why Write Unit Tests• Increase developers’ confidence in code. Ifsomeone challenges your work, you can say“the tests passed.”• Avoid regression. If unit test suite is runfrequently, you know when new codebreaks old code.• If you write tests first, you know whenyou’re done, i.e., when the tests pass.• Encourages minimal interfaces andmodularity.
When to Write/RunUnit Tests• Always!• Before you check code into repository, soyou know your code works.• Before debugging, to ease the process andhelp you know when you’re done.
Test Writing Tips• Make code modular: use interfaces/template classes/abstract baseclasses.• Use mock objects to inspect behavior ofobject you’re testing and to stand in for“heavy” objects, e.g., you don’t want to donetwork I/O in a unit test.• Modular, loosely coupled interfaces makemock objects possible.• Excessive coupling is enemy of unit testing.
Using PyUnit to write your own tests• InstallationThe classes needed to write tests are to befound in the 'unittest' module. This module ispart of the standard Python library for Python2.1 and later. If you are using an older Pythonversion, you should obtain the module fromthe separate PyUnit distribution.
An introduction to TestCases• The basic building blocks of unit testing are'test cases' -- single scenarios that must be setup and checked for correctness. In PyUnit, testcases are represented by the TestCase class inthe unittest module. To make your own testcases you must write subclasses of TestCase.• An instance of a TestCase class is an object thatcan completely run a single test method,together with optional set-up and tidy-up code.
Creating a simple test case• The simplest test case subclass will simply overridethe runTest method in order to perform specific testing code:import unittestclass DefaultWidgetSizeTestCase(unittest.TestCase):def runTest(self):widget = Widget("The widget")assert widget.size() == (50,50), 'incorrect defaultsize'
Note that in order to test something, we just use thebuilt-in 'assert' statement of Python. If the assertionfails when the test case runs, an AssertionError willbe raised, and the testing framework will identify thetest case as a 'failure'. Other exceptions that do notarise from explicit 'assert' checks are identified bythe testing framework as 'errors'.
Re-using set-up code: creating 'fixtures'• Now, such test cases can be numerous, and theirset-up can be repetitive. In the above case,constructing a 'Widget' in each of 100 Widget testcase subclasses would mean unsightly duplication.• Luckily, we can factor out such set-up code byimplementing a hook method called setUp, whichthe testing framework will automatically call for uswhen we run the test:
import unittest classSimpleWidgetTestCase(unittest.TestCase):def setUp(self):self.widget = Widget("The widget")class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):def runTest(self):assert self.widget.size() == (50,50), 'incorrect defaultsize'class WidgetResizeTestCase(SimpleWidgetTestCase):def runTest(self):self.widget.resize(100,150)assert self.widget.size() == (100,150),  'wrong sizeafter resize'
• If the setUp method raises an exception while the test is running, theframework will consider the test to have suffered an error, andthe runTest method will not be executed.• Similarly, we can provide a tearDown method that tidies up afterthe runTest method has been run:import unittest classSimpleWidgetTestCase(unittest.TestCase):def setUp(self):self.widget = Widget("The widget")def tearDown(self):self.widget.dispose()self.widget = None• If setUp succeeded, the tearDown method will be run regardless of whetheror not runTest succeeded.• Such a working environment for the testing code is termed a fixture.
TestCase classes with several test methods• Often, many small test cases will use the same fixture. In this case, we would end upsubclassing SimpleWidgetTestCase into many small one-method classes suchas DefaultWidgetSizeTestCase. This is time-consuming and discouragingimport unittest classWidgetTestCase(unittest.TestCase):def setUp(self):self.widget = Widget("The widget")def tearDown(self):self.widget.dispose()self.widget = Nonedef testDefaultSize(self):assert self.widget.size() == (50,50), 'incorrect default size'def testResize(self):self.widget.resize(100,150)assert self.widget.size() == (100,150),  'wrong size after resize'
TestCase classes with several test methods• Here we have not provided a runTest method, but have instead providedtwo different test methods. Class instances will now each run one ofthe test methods, with self.widget created and destroyed separately foreach instance. When creating an instance we must specify the testmethod it is to run. We do this by passing the method name in theconstructor:defaultSizeTestCase = WidgetTestCase("testDefaultSize")resizeTestCase = WidgetTestCase("testResize")
Running tests• The unittest module contains a function called main, which can be used toeasily turn a test module into a script that will run the tests it contains.The main function uses the unittest.TestLoader class to automatically findand load test cases within the current module.• Therefore, if you name your test methods using the test* convention, youcan place the following code at the bottom of your test module:if __name__ == "__main__":unittest.main()

Recommended

PDF
Py.test
 
PPTX
Introduction to unit testing in python
PDF
Write unit test from scratch
PPTX
Unit testing and mocking in Python - PyCon 2018 - Kenya
PPTX
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
PPTX
1.Python_Testing_Using_PyUnit_Pytest.pptx
ODT
Testing in-python-and-pytest-framework
PPTX
Upstate CSCI 540 Unit testing
PPTX
unittestinginpythonfor-PYDevelopers.pptx
PDF
PresentationqwertyuiopasdfghUnittest.pdf
PDF
Unit Testing in Software Development: Why It Matters and How to Do It Right
PDF
Testing Django Applications
PPT
Python testing
PDF
Plone Testing Tools And Techniques
PDF
Python and test
PPTX
Python Programming Essentials - M39 - Unit Testing
PPS
Unit Testing
PDF
The Future is Now: Writing Automated Tests To Grow Your Code
PPTX
Standard Libraries in Python Programming
ODP
Intro to Testing in Zope, Plone
PDF
Debugging 2013- Thomas Ammitzboell-Bach
PDF
Factories, mocks and spies: a tester's little helpers
 
PDF
Pragmatic Introduction to Python Unit Testing (PyDays 2018)
PPTX
Mockito para tus pruebas unitarias
PPS
Why Unit Testingl
PPS
Why Unit Testingl
PPS
Why unit testingl
PPTX
Unit tests and mocks
PPTX
Python_Functions_Advanced3_KMSolutions.pptx
PPTX
Python_Functions_Advanced2_KMSolutions.pptx

More Related Content

PDF
Py.test
 
PPTX
Introduction to unit testing in python
PDF
Write unit test from scratch
PPTX
Unit testing and mocking in Python - PyCon 2018 - Kenya
PPTX
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
PPTX
1.Python_Testing_Using_PyUnit_Pytest.pptx
ODT
Testing in-python-and-pytest-framework
PPTX
Upstate CSCI 540 Unit testing
Py.test
 
Introduction to unit testing in python
Write unit test from scratch
Unit testing and mocking in Python - PyCon 2018 - Kenya
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
1.Python_Testing_Using_PyUnit_Pytest.pptx
Testing in-python-and-pytest-framework
Upstate CSCI 540 Unit testing

Similar to 2.Python_Testing_Using_PyUnit_PyTest.pptx

PPTX
unittestinginpythonfor-PYDevelopers.pptx
PDF
PresentationqwertyuiopasdfghUnittest.pdf
PDF
Unit Testing in Software Development: Why It Matters and How to Do It Right
PDF
Testing Django Applications
PPT
Python testing
PDF
Plone Testing Tools And Techniques
PDF
Python and test
PPTX
Python Programming Essentials - M39 - Unit Testing
PPS
Unit Testing
PDF
The Future is Now: Writing Automated Tests To Grow Your Code
PPTX
Standard Libraries in Python Programming
ODP
Intro to Testing in Zope, Plone
PDF
Debugging 2013- Thomas Ammitzboell-Bach
PDF
Factories, mocks and spies: a tester's little helpers
 
PDF
Pragmatic Introduction to Python Unit Testing (PyDays 2018)
PPTX
Mockito para tus pruebas unitarias
PPS
Why Unit Testingl
PPS
Why Unit Testingl
PPS
Why unit testingl
PPTX
Unit tests and mocks
unittestinginpythonfor-PYDevelopers.pptx
PresentationqwertyuiopasdfghUnittest.pdf
Unit Testing in Software Development: Why It Matters and How to Do It Right
Testing Django Applications
Python testing
Plone Testing Tools And Techniques
Python and test
Python Programming Essentials - M39 - Unit Testing
Unit Testing
The Future is Now: Writing Automated Tests To Grow Your Code
Standard Libraries in Python Programming
Intro to Testing in Zope, Plone
Debugging 2013- Thomas Ammitzboell-Bach
Factories, mocks and spies: a tester's little helpers
 
Pragmatic Introduction to Python Unit Testing (PyDays 2018)
Mockito para tus pruebas unitarias
Why Unit Testingl
Why Unit Testingl
Why unit testingl
Unit tests and mocks

More from Ganesh Bhosale

PPTX
Python_Functions_Advanced3_KMSolutions.pptx
PPTX
Python_Functions_Advanced2_KMSolutions.pptx
PPTX
Python_Functions_Advancedby_KMSolutions.pptx
DOCX
3.AWR and ASH Reportsfor Oracle Tuning.docx
DOCX
Step by stepDoc for Oracle TuningsandAWR.docx
PPTX
awsfundamentals1_cloud_Infrastructure.pptx
PPTX
Generators-in-Python-for-Developers.pptx
PPTX
Advance-Python-Iterators-for-developers.pptx
PPTX
The ES Library for JavaScript Developers
PPTX
Git Repository for Developers working in Various Locations
PPTX
4.Problem Solving Techniques and Data Structures.pptx
PPTX
3.Problem Solving Techniques and Data Structures.pptx
PPTX
2.Problem Solving Techniques and Data Structures.pptx
PPTX
1. Problem Solving Techniques and Data Structures.pptx
PPTX
SQL-queries-for-Data-Analysts-Updated.pptx
PPTX
javascriptbasicsPresentationsforDevelopers
PPTX
Cloud-Architecture-Technology-Deovps-Eng
PDF
Backup-and-Recovery Procedures decribed in AWS
PPTX
KMSUnix and Linux.pptx
PPT
RDBMS_Concept.ppt
Python_Functions_Advanced3_KMSolutions.pptx
Python_Functions_Advanced2_KMSolutions.pptx
Python_Functions_Advancedby_KMSolutions.pptx
3.AWR and ASH Reportsfor Oracle Tuning.docx
Step by stepDoc for Oracle TuningsandAWR.docx
awsfundamentals1_cloud_Infrastructure.pptx
Generators-in-Python-for-Developers.pptx
Advance-Python-Iterators-for-developers.pptx
The ES Library for JavaScript Developers
Git Repository for Developers working in Various Locations
4.Problem Solving Techniques and Data Structures.pptx
3.Problem Solving Techniques and Data Structures.pptx
2.Problem Solving Techniques and Data Structures.pptx
1. Problem Solving Techniques and Data Structures.pptx
SQL-queries-for-Data-Analysts-Updated.pptx
javascriptbasicsPresentationsforDevelopers
Cloud-Architecture-Technology-Deovps-Eng
Backup-and-Recovery Procedures decribed in AWS
KMSUnix and Linux.pptx
RDBMS_Concept.ppt

Recently uploaded

PDF
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
PDF
Integrating AI with Meaningful Human Collaboration
PDF
Crane Accident Prevention Guide: Key OSHA Regulations for Safer Operations
PPTX
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
PDF
DUBAI IT MODERNIZATION WITH AZURE MANAGED SERVICES.pdf
PPTX
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
PPTX
MuleSoft AI Series : Introduction to MCP
PDF
Top Crypto Supers 15th Report November 2025
PPTX
Connecting the unconnectable: Exploring LoRaWAN for IoT
PDF
Cheryl Hung, Vibe Coding Auth Without Melting Down! isaqb Software Architectu...
PDF
Mulesoft Meetup Online Portuguese: MCP e IA
PDF
Mastering UiPath Maestro – Session 2 – Building a Live Use Case - Session 2
PPTX
Leon Brands - Intro to GPU Occlusion (Graphics Programming Conference 2024)
PDF
How Much Does It Cost To Build Software
PDF
"DISC as GPS for team leaders: how to lead a team from storming to performing...
 
PDF
[BDD 2025 - Artificial Intelligence] Building AI Systems That Users (and Comp...
PPTX
kernel PPT (Explanation of Windows Kernal).pptx
PDF
Transforming Content Operations in the Age of AI
PDF
The partnership effect: Libraries and publishers on collaborating and thrivin...
PDF
[DevFest Strasbourg 2025] - NodeJs Can do that !!
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
Integrating AI with Meaningful Human Collaboration
Crane Accident Prevention Guide: Key OSHA Regulations for Safer Operations
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
DUBAI IT MODERNIZATION WITH AZURE MANAGED SERVICES.pdf
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
MuleSoft AI Series : Introduction to MCP
Top Crypto Supers 15th Report November 2025
Connecting the unconnectable: Exploring LoRaWAN for IoT
Cheryl Hung, Vibe Coding Auth Without Melting Down! isaqb Software Architectu...
Mulesoft Meetup Online Portuguese: MCP e IA
Mastering UiPath Maestro – Session 2 – Building a Live Use Case - Session 2
Leon Brands - Intro to GPU Occlusion (Graphics Programming Conference 2024)
How Much Does It Cost To Build Software
"DISC as GPS for team leaders: how to lead a team from storming to performing...
 
[BDD 2025 - Artificial Intelligence] Building AI Systems That Users (and Comp...
kernel PPT (Explanation of Windows Kernal).pptx
Transforming Content Operations in the Age of AI
The partnership effect: Libraries and publishers on collaborating and thrivin...
[DevFest Strasbourg 2025] - NodeJs Can do that !!

2.Python_Testing_Using_PyUnit_PyTest.pptx

  • 1.
  • 2.
    Overview• Unit TestingBasics: What, Why, When• How: Python Unit Test Class• Unit Test Writing Tips and Resources
  • 3.
    Unit Testing Basics•Functional tests: done by QA to testfunctionality according to a test plan basedon requirements and design specs.• Unit tests: done by developers to testspecific code. Typically “white box” testing.• Essential part of Extreme Programming andother agile methods.
  • 4.
    Why Write UnitTests• Increase developers’ confidence in code. Ifsomeone challenges your work, you can say“the tests passed.”• Avoid regression. If unit test suite is runfrequently, you know when new codebreaks old code.• If you write tests first, you know whenyou’re done, i.e., when the tests pass.• Encourages minimal interfaces andmodularity.
  • 5.
    When to Write/RunUnitTests• Always!• Before you check code into repository, soyou know your code works.• Before debugging, to ease the process andhelp you know when you’re done.
  • 6.
    Test Writing Tips•Make code modular: use interfaces/template classes/abstract baseclasses.• Use mock objects to inspect behavior ofobject you’re testing and to stand in for“heavy” objects, e.g., you don’t want to donetwork I/O in a unit test.• Modular, loosely coupled interfaces makemock objects possible.• Excessive coupling is enemy of unit testing.
  • 7.
    Using PyUnit towrite your own tests• InstallationThe classes needed to write tests are to befound in the 'unittest' module. This module ispart of the standard Python library for Python2.1 and later. If you are using an older Pythonversion, you should obtain the module fromthe separate PyUnit distribution.
  • 8.
    An introduction toTestCases• The basic building blocks of unit testing are'test cases' -- single scenarios that must be setup and checked for correctness. In PyUnit, testcases are represented by the TestCase class inthe unittest module. To make your own testcases you must write subclasses of TestCase.• An instance of a TestCase class is an object thatcan completely run a single test method,together with optional set-up and tidy-up code.
  • 9.
    Creating a simpletest case• The simplest test case subclass will simply overridethe runTest method in order to perform specific testing code:import unittestclass DefaultWidgetSizeTestCase(unittest.TestCase):def runTest(self):widget = Widget("The widget")assert widget.size() == (50,50), 'incorrect defaultsize'
  • 10.
    Note that inorder to test something, we just use thebuilt-in 'assert' statement of Python. If the assertionfails when the test case runs, an AssertionError willbe raised, and the testing framework will identify thetest case as a 'failure'. Other exceptions that do notarise from explicit 'assert' checks are identified bythe testing framework as 'errors'.
  • 11.
    Re-using set-up code:creating 'fixtures'• Now, such test cases can be numerous, and theirset-up can be repetitive. In the above case,constructing a 'Widget' in each of 100 Widget testcase subclasses would mean unsightly duplication.• Luckily, we can factor out such set-up code byimplementing a hook method called setUp, whichthe testing framework will automatically call for uswhen we run the test:
  • 12.
    import unittest classSimpleWidgetTestCase(unittest.TestCase):defsetUp(self):self.widget = Widget("The widget")class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):def runTest(self):assert self.widget.size() == (50,50), 'incorrect defaultsize'class WidgetResizeTestCase(SimpleWidgetTestCase):def runTest(self):self.widget.resize(100,150)assert self.widget.size() == (100,150), 'wrong sizeafter resize'
  • 13.
    • If thesetUp method raises an exception while the test is running, theframework will consider the test to have suffered an error, andthe runTest method will not be executed.• Similarly, we can provide a tearDown method that tidies up afterthe runTest method has been run:import unittest classSimpleWidgetTestCase(unittest.TestCase):def setUp(self):self.widget = Widget("The widget")def tearDown(self):self.widget.dispose()self.widget = None• If setUp succeeded, the tearDown method will be run regardless of whetheror not runTest succeeded.• Such a working environment for the testing code is termed a fixture.
  • 14.
    TestCase classes withseveral test methods• Often, many small test cases will use the same fixture. In this case, we would end upsubclassing SimpleWidgetTestCase into many small one-method classes suchas DefaultWidgetSizeTestCase. This is time-consuming and discouragingimport unittest classWidgetTestCase(unittest.TestCase):def setUp(self):self.widget = Widget("The widget")def tearDown(self):self.widget.dispose()self.widget = Nonedef testDefaultSize(self):assert self.widget.size() == (50,50), 'incorrect default size'def testResize(self):self.widget.resize(100,150)assert self.widget.size() == (100,150), 'wrong size after resize'
  • 15.
    TestCase classes withseveral test methods• Here we have not provided a runTest method, but have instead providedtwo different test methods. Class instances will now each run one ofthe test methods, with self.widget created and destroyed separately foreach instance. When creating an instance we must specify the testmethod it is to run. We do this by passing the method name in theconstructor:defaultSizeTestCase = WidgetTestCase("testDefaultSize")resizeTestCase = WidgetTestCase("testResize")
  • 16.
    Running tests• Theunittest module contains a function called main, which can be used toeasily turn a test module into a script that will run the tests it contains.The main function uses the unittest.TestLoader class to automatically findand load test cases within the current module.• Therefore, if you name your test methods using the test* convention, youcan place the following code at the bottom of your test module:if __name__ == "__main__":unittest.main()

[8]ページ先頭

©2009-2025 Movatter.jp