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

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

More Related Content

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

Similar to 2.Python_Testing_Using_PyUnit_PyTest.pptx

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

More from Ganesh Bhosale

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

Recently uploaded

PDF
Cheryl Hung, Vibe Coding Auth Without Melting Down! isaqb Software Architectu...
PPTX
"Feelings versus facts: why metrics are more important than intuition", Igor ...
 
PDF
ODSC AI West: Agent Optimization: Beyond Context engineering
PDF
Mulesoft Meetup Online Portuguese: MCP e IA
PDF
Open Source Post-Quantum Cryptography - Matt Caswell
PDF
[BDD 2025 - Full-Stack Development] Agentic AI Architecture: Redefining Syste...
PDF
Rolling out Enterprise AI: Tools, Insights, and Team Empowerment
PDF
[BDD 2025 - Full-Stack Development] PHP in AI Age: The Laravel Way. (Rizqy Hi...
PDF
Oracle MySQL HeatWave - Short - Version 3
PPTX
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
PDF
Dev Dives: Build smarter agents with UiPath Agent Builder
PPTX
kernel PPT (Explanation of Windows Kernal).pptx
PPTX
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
PDF
Beyond Basics: How to Build Scalable, Intelligent Imagery Pipelines
PDF
So You Want to Work at Google | DevFest Seattle 2025
PDF
Transcript: The partnership effect: Libraries and publishers on collaborating...
PDF
[BDD 2025 - Mobile Development] Crafting Immersive UI with E2E and AGSL Shade...
PDF
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
PDF
Top 10 AI Development Companies in UK 2025
PDF
The partnership effect: Libraries and publishers on collaborating and thrivin...
Cheryl Hung, Vibe Coding Auth Without Melting Down! isaqb Software Architectu...
"Feelings versus facts: why metrics are more important than intuition", Igor ...
 
ODSC AI West: Agent Optimization: Beyond Context engineering
Mulesoft Meetup Online Portuguese: MCP e IA
Open Source Post-Quantum Cryptography - Matt Caswell
[BDD 2025 - Full-Stack Development] Agentic AI Architecture: Redefining Syste...
Rolling out Enterprise AI: Tools, Insights, and Team Empowerment
[BDD 2025 - Full-Stack Development] PHP in AI Age: The Laravel Way. (Rizqy Hi...
Oracle MySQL HeatWave - Short - Version 3
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
Dev Dives: Build smarter agents with UiPath Agent Builder
kernel PPT (Explanation of Windows Kernal).pptx
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
Beyond Basics: How to Build Scalable, Intelligent Imagery Pipelines
So You Want to Work at Google | DevFest Seattle 2025
Transcript: The partnership effect: Libraries and publishers on collaborating...
[BDD 2025 - Mobile Development] Crafting Immersive UI with E2E and AGSL Shade...
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
Top 10 AI Development Companies in UK 2025
The partnership effect: Libraries and publishers on collaborating and thrivin...

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