Movatterモバイル変換


[0]ホーム

URL:


Jachym Cepicky, profile picture
Uploaded byJachym Cepicky
PDF, PPTX566 views

Python testing-frameworks overview

The document provides an overview of Python testing frameworks such as unittest, pytest, and doctest, highlighting their pros and cons. It also discusses the importance of testing in software development and the differences between various testing methods. Ultimately, it concludes that while doctests serve well for documentation purposes, pytest is seen as the leading testing framework for more comprehensive testing needs.

Embed presentation

Download as PDF, PPTX
What is doctest?Python testing frameworks overview1 / 26
What am I doing here?2 / 26
What am I doing here?FactsJachym CepickyGIS (maps in computer)Open source softwareNot factsnot a testernot educated software engineernor GIS educated3 / 26
What am I doing here?Me: confused py.test with doctest4 / 26
Let's get started5 / 26
Testing motivation6 / 26
Everybody loves to tests.7 / 26
Everybody has heard, that using TDD is the only way how to writecode loves to tests.8 / 26
TDD9 / 26
The factWriting tests...does make sense10 / 26
SummaryMaking sure, that the systemmeets the requirements that guided its design and development,responds correctly to all kinds of inputs,performs its functions within an acceptable time,is sufficiently usable,can be installed and run in its intended environments, andachieves the general result its stakeholders desire.https://en.wikipedia.org/wiki/Software_testing11 / 26
Testing in Python - overview12 / 26
It's pretty cool and easy to test in Python13 / 26
Unittesthttps://docs.python.org/3/library/unittest.htmloriginally inspired by JUnit (inspired by SUnit for Smalltalk, since 1998)https://shebanator.com/2007/08/21/a-brief-history-of-test-frameworks/ProsNative frameworkTesting methodsSupported everywhereAuto discovery of test classes and functionsConsClassesTesting methodsComplicated (for some people)Lack of Group fixtures (specified environment for a whole group)Still better to separate testing code from business logicUnit-test oriented14 / 26
import unittestclass TestStringMethods(unittest.TestCase):def test_upper(self):self.assertEqual('foo'.upper(), 'FOO')def test_isupper(self):self.assertTrue('FOO'.isupper())self.assertFalse('Foo'.isupper())def test_split(self):s = 'hello world'self.assertEqual(s.split(), ['hello', 'world'])# check that s.split fails when the separator is not a stringwith self.assertRaises(TypeError):s.split(2)if __name__ == '__main__':unittest.main()15 / 26
$ python my_unittest.py.F.======================================================================FAIL: test_split (__main__.TestStringMethods)----------------------------------------------------------------------Traceback (most recent call last):File "neco.py", line 14, in test_splitself.assertEqual(s.split(), ['hellox', 'world'])AssertionError: Lists differ: ['hello', 'world'] != ['hellox', 'world']First differing element 0:'hello''hellox'- ['hello', 'world']+ ['hellox', 'world']? +----------------------------------------------------------------------Ran 3 tests in 0.001sFAILED (failures=1)16 / 26
py.testhttp://doc.pytest.org/en/latest/ProsPluginsHTML outputSimpler and more straight-forward syntaxAuto discovery of test functionsDistributedConsNot nativeCan get complicated too (decorators)17 / 26
def inc(x):return x + 1def test_answer():assert inc(3) == 518 / 26
$ python3 -m pytest my_pytest.py============================================ test session starts ============================================platform linux -- Python 3.5.2+, pytest-3.0.6, py-1.4.32, pluggy-0.4.0rootdir: /tmp, inifile:collected 2 itemsneco.py F.================================================= FAILURES ==================================================________________________________________________ test_answer ________________________________________________def test_answer():> assert inc(3) == 5E assert 4 == 5E + where 4 = inc(3)neco.py:5: AssertionError==================================== 1 failed, 1 passed in 0.03 seconds =====================================19 / 26
Doctesthttps://docs.python.org/3/library/doctest.htmlProsNativeTests are (can be) part of class and method documentationCan be in separated text (e.g. README) filesSupported by SphinxConsNot suitable for larger testing systemsNo fixtures20 / 26
def unique_words(page):''' Returns set of the unique words in list of lines of textExample:>>> from StringIO import StringIO>>> fileText = """the cat sat on the mat... the mat was ondur the cat... one fish two fish red fish... blue fish... This fish has a yellow car... This fish has a yellow star""">>> file = StringIO(fileText)>>> page = file.readlines()>>> words = unique_words(page)>>> print sorted(list(words))["This", "a", "blue", "car", "cat", "fish", "has", "mat","on", "ondur", "one", "red", "sat", "star", "the", "two","was", "yellow"]>>>'''return set(word for line in page for word in line.split())def _test():import doctestdoctest.testmod()if __name__ == "__main__":_test()21 / 26
$ python2 my_doctest.py**********************************************************************File "neco.py", line 16, in __main__.unique_wordsFailed example:print sorted(list(words))Expected:["This", "a", "blue", "car", "cat", "fish", "has", "mat","on", "ondur", "one", "red", "sat", "star", "the", "two","was", "yellow"]Got:['This', 'a', 'blue', 'car', 'cat', 'fish', 'has', 'mat', 'on', 'ondur', 'one', 'red', 'sat', 'star', 'the', 'two', 'was', 'yellow']**********************************************************************1 items had failures:1 of 6 in __main__.unique_words***Test Failed*** 1 failures.22 / 26
nose (nose2)nose extends unittest to make testing easiersmart developer should get familiar doctest, unittest, pytest, and nosehttps://pypi.python.org/pypi/nose/ --> new projects should use py.test ornose2https://github.com/nose-devs/nose2ProsBuild on top of unittestsOverpasses some of it's limitsCommand line toolConsnose not maintained any more --> nose2Not nativeUnder development (nose2)23 / 26
Python unittests overview24 / 26
ConclusionDoctests != py.testDoctests are the natural way, how to test your code and how to documentitDoctests should be used for documentation, not for testingpy.test seems to be current leading testing frameworkEvent /me knows, what is the difference between doctests and py.test25 / 26
That's all folks#jachymcjachym.cepicky at opengeolabs dot cz26 / 26

Recommended

PDF
Applying Real-time SQL Changes in your Hazelcast Data Grid
PDF
python高级内存管理
PDF
AST: threats and opportunities
PDF
benpresentation_django
 
PDF
Python fundamentals - basic | WeiYuan
PDF
Robert Bernier - Recovering From A Damaged PostgreSQL Cluster @ Postgres Open
PDF
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
PDF
PostgreSQL 9.6 새 기능 소개
PDF
PythonOOP
RTF
Seistech SQL code
PDF
PostgreSQL: Advanced indexing
PDF
Advanced pg_stat_statements: Filtering, Regression Testing & more
PDF
Statistical computing 01
PDF
Quick reference for Grafana
PDF
Read data from Excel spreadsheets into R
PDF
Python and sysadmin I
ODP
PPTX
PDF
Chapter 2: R tutorial Handbook for Data Science and Machine Learning Practiti...
PDF
Introducción a Elixir
PPTX
R intro 20140716-advance
TXT
Quick reference for hql
TXT
Quick reference for solr
PDF
M12 random forest-part01
PDF
MySQL Query tuning 101
TXT
Quick reference for HBase shell commands
PDF
M11 bagging loo cv
PDF
Demystifying cost based optimization
PDF
PyWPS-4.0.0
PDF
Descriptors In Python

More Related Content

PDF
Applying Real-time SQL Changes in your Hazelcast Data Grid
PDF
python高级内存管理
PDF
AST: threats and opportunities
PDF
benpresentation_django
 
PDF
Python fundamentals - basic | WeiYuan
PDF
Robert Bernier - Recovering From A Damaged PostgreSQL Cluster @ Postgres Open
PDF
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
PDF
PostgreSQL 9.6 새 기능 소개
Applying Real-time SQL Changes in your Hazelcast Data Grid
python高级内存管理
AST: threats and opportunities
benpresentation_django
 
Python fundamentals - basic | WeiYuan
Robert Bernier - Recovering From A Damaged PostgreSQL Cluster @ Postgres Open
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
PostgreSQL 9.6 새 기능 소개

What's hot

PDF
PythonOOP
RTF
Seistech SQL code
PDF
PostgreSQL: Advanced indexing
PDF
Advanced pg_stat_statements: Filtering, Regression Testing & more
PDF
Statistical computing 01
PDF
Quick reference for Grafana
PDF
Read data from Excel spreadsheets into R
PDF
Python and sysadmin I
ODP
PPTX
PDF
Chapter 2: R tutorial Handbook for Data Science and Machine Learning Practiti...
PDF
Introducción a Elixir
PPTX
R intro 20140716-advance
TXT
Quick reference for hql
TXT
Quick reference for solr
PDF
M12 random forest-part01
PDF
MySQL Query tuning 101
TXT
Quick reference for HBase shell commands
PDF
M11 bagging loo cv
PDF
Demystifying cost based optimization
PythonOOP
Seistech SQL code
PostgreSQL: Advanced indexing
Advanced pg_stat_statements: Filtering, Regression Testing & more
Statistical computing 01
Quick reference for Grafana
Read data from Excel spreadsheets into R
Python and sysadmin I
Chapter 2: R tutorial Handbook for Data Science and Machine Learning Practiti...
Introducción a Elixir
R intro 20140716-advance
Quick reference for hql
Quick reference for solr
M12 random forest-part01
MySQL Query tuning 101
Quick reference for HBase shell commands
M11 bagging loo cv
Demystifying cost based optimization

Viewers also liked

PDF
PyWPS-4.0.0
PDF
Descriptors In Python
PDF
Lazy evaluation in Python
PDF
Function arguments In Python
PDF
Ansible loves Python, Python Philadelphia meetup
PPTX
Advance OOP concepts in Python
PDF
Generators: The Final Frontier
PDF
Mastering Python 3 I/O (Version 2)
PDF
An Introduction to Python Concurrency
PDF
Visual Design with Data
PyWPS-4.0.0
Descriptors In Python
Lazy evaluation in Python
Function arguments In Python
Ansible loves Python, Python Philadelphia meetup
Advance OOP concepts in Python
Generators: The Final Frontier
Mastering Python 3 I/O (Version 2)
An Introduction to Python Concurrency
Visual Design with Data

Similar to Python testing-frameworks overview

PDF
Writing tests
PDF
New and improved: Coming changes to the unittest module
PPT
Python testing
ODT
Testing in-python-and-pytest-framework
PDF
Test Driven Development With Python
 
PPTX
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
PPTX
1.Python_Testing_Using_PyUnit_Pytest.pptx
PDF
PresentationqwertyuiopasdfghUnittest.pdf
PDF
Next Level Testing
PPTX
unittestinginpythonfor-PYDevelopers.pptx
PPTX
Introduction to unit testing in python
PPT
4 b file-io-if-then-else
PPTX
2015 bioinformatics python_strings_wim_vancriekinge
PDF
MT_01_unittest_python.pdf
PPTX
Python material
PDF
Write unit test from scratch
PDF
Python types and doctests by Lauri Kainulainen
PPTX
Testing in Python: doctest and unittest
PDF
Testing in Django
PDF
Python Advanced – Building on the foundation
Writing tests
New and improved: Coming changes to the unittest module
Python testing
Testing in-python-and-pytest-framework
Test Driven Development With Python
 
2.Python_Unit _Testing_Using_PyUnit_Pytest.pptx
1.Python_Testing_Using_PyUnit_Pytest.pptx
PresentationqwertyuiopasdfghUnittest.pdf
Next Level Testing
unittestinginpythonfor-PYDevelopers.pptx
Introduction to unit testing in python
4 b file-io-if-then-else
2015 bioinformatics python_strings_wim_vancriekinge
MT_01_unittest_python.pdf
Python material
Write unit test from scratch
Python types and doctests by Lauri Kainulainen
Testing in Python: doctest and unittest
Testing in Django
Python Advanced – Building on the foundation

More from Jachym Cepicky

PDF
Switch from shapefile
PPTX
What is the price of open source
PDF
Testing web application with Python
PPTX
Danube hack 2015 - Open (-data, -communities)
PDF
Push it through the wire
PDF
How Prague is opening data
PDF
Webgis, Cloud computing, OGC OWS
PDF
Co může udělat vaše firma pro open source
PDF
Otevřené standardy, Otevřená data, Otevřený software, Otevření lidé
PDF
Úvod do otevřená geoinfrastruktury
PDF
PyWPS Status report
PDF
Geosense Geoportal
PDF
Cepicky pywps4
PDF
Sdílené intelektuální spoluvlastnictví
PDF
Co brání většímu rozšíření open source nástrojů
PDF
Open Source JavaScript Mapping Framework
PDF
PyWPS at COST WPS Workshop
PDF
Cepicky osgeocz
PDF
Cepicky os-mapping-frameworks
PDF
Cepicky wikikonf-2013
Switch from shapefile
What is the price of open source
Testing web application with Python
Danube hack 2015 - Open (-data, -communities)
Push it through the wire
How Prague is opening data
Webgis, Cloud computing, OGC OWS
Co může udělat vaše firma pro open source
Otevřené standardy, Otevřená data, Otevřený software, Otevření lidé
Úvod do otevřená geoinfrastruktury
PyWPS Status report
Geosense Geoportal
Cepicky pywps4
Sdílené intelektuální spoluvlastnictví
Co brání většímu rozšíření open source nástrojů
Open Source JavaScript Mapping Framework
PyWPS at COST WPS Workshop
Cepicky osgeocz
Cepicky os-mapping-frameworks
Cepicky wikikonf-2013

Recently uploaded

PDF
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
PDF
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
PDF
Mastering UiPath Maestro – Session 2 – Building a Live Use Case - Session 2
PDF
Transforming Supply Chains with Amazon Bedrock AgentCore (AWS Swiss User Grou...
PDF
5 Common Supply Chain Attacks and How They Work | CyberPro Magazine
PPTX
Leon Brands - Intro to GPU Occlusion (Graphics Programming Conference 2024)
PPTX
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
PPTX
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
PPTX
kernel PPT (Explanation of Windows Kernal).pptx
PDF
Open Source Post-Quantum Cryptography - Matt Caswell
PDF
MuleSoft Meetup: Dreamforce'25 Tour- Vibing With AI & Agents.pdf
PDF
[BDD 2025 - Mobile Development] Mobile Engineer and Software Engineer: Are we...
PDF
[BDD 2025 - Full-Stack Development] Digital Accessibility: Why Developers nee...
PDF
KMWorld - KM & AI Bring Collectivity, Nostalgia, & Selectivity
PDF
How Much Does It Cost to Build an eCommerce Website in 2025.pdf
PDF
Transcript: The partnership effect: Libraries and publishers on collaborating...
PDF
Cybersecurity Prevention and Detection: Unit 2
PDF
Parallel Computing BCS702 Module notes of the vtu college 7th sem 4.pdf
PDF
So You Want to Work at Google | DevFest Seattle 2025
PDF
The partnership effect: Libraries and publishers on collaborating and thrivin...
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
PCCC25(設立25年記念PCクラスタシンポジウム):エヌビディア合同会社 テーマ2「NVIDIA BlueField-4 DPU」
Mastering UiPath Maestro – Session 2 – Building a Live Use Case - Session 2
Transforming Supply Chains with Amazon Bedrock AgentCore (AWS Swiss User Grou...
5 Common Supply Chain Attacks and How They Work | CyberPro Magazine
Leon Brands - Intro to GPU Occlusion (Graphics Programming Conference 2024)
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
kernel PPT (Explanation of Windows Kernal).pptx
Open Source Post-Quantum Cryptography - Matt Caswell
MuleSoft Meetup: Dreamforce'25 Tour- Vibing With AI & Agents.pdf
[BDD 2025 - Mobile Development] Mobile Engineer and Software Engineer: Are we...
[BDD 2025 - Full-Stack Development] Digital Accessibility: Why Developers nee...
KMWorld - KM & AI Bring Collectivity, Nostalgia, & Selectivity
How Much Does It Cost to Build an eCommerce Website in 2025.pdf
Transcript: The partnership effect: Libraries and publishers on collaborating...
Cybersecurity Prevention and Detection: Unit 2
Parallel Computing BCS702 Module notes of the vtu college 7th sem 4.pdf
So You Want to Work at Google | DevFest Seattle 2025
The partnership effect: Libraries and publishers on collaborating and thrivin...

Python testing-frameworks overview

  • 1.
    What is doctest?Pythontesting frameworks overview1 / 26
  • 2.
    What am Idoing here?2 / 26
  • 3.
    What am Idoing here?FactsJachym CepickyGIS (maps in computer)Open source softwareNot factsnot a testernot educated software engineernor GIS educated3 / 26
  • 4.
    What am Idoing here?Me: confused py.test with doctest4 / 26
  • 5.
  • 6.
  • 7.
    Everybody loves totests.7 / 26
  • 8.
    Everybody has heard,that using TDD is the only way how to writecode loves to tests.8 / 26
  • 9.
  • 10.
  • 11.
    SummaryMaking sure, thatthe systemmeets the requirements that guided its design and development,responds correctly to all kinds of inputs,performs its functions within an acceptable time,is sufficiently usable,can be installed and run in its intended environments, andachieves the general result its stakeholders desire.https://en.wikipedia.org/wiki/Software_testing11 / 26
  • 12.
    Testing in Python- overview12 / 26
  • 13.
    It's pretty cooland easy to test in Python13 / 26
  • 14.
    Unittesthttps://docs.python.org/3/library/unittest.htmloriginally inspired byJUnit (inspired by SUnit for Smalltalk, since 1998)https://shebanator.com/2007/08/21/a-brief-history-of-test-frameworks/ProsNative frameworkTesting methodsSupported everywhereAuto discovery of test classes and functionsConsClassesTesting methodsComplicated (for some people)Lack of Group fixtures (specified environment for a whole group)Still better to separate testing code from business logicUnit-test oriented14 / 26
  • 15.
    import unittestclass TestStringMethods(unittest.TestCase):deftest_upper(self):self.assertEqual('foo'.upper(), 'FOO')def test_isupper(self):self.assertTrue('FOO'.isupper())self.assertFalse('Foo'.isupper())def test_split(self):s = 'hello world'self.assertEqual(s.split(), ['hello', 'world'])# check that s.split fails when the separator is not a stringwith self.assertRaises(TypeError):s.split(2)if __name__ == '__main__':unittest.main()15 / 26
  • 16.
    $ python my_unittest.py.F.======================================================================FAIL:test_split (__main__.TestStringMethods)----------------------------------------------------------------------Traceback (most recent call last):File "neco.py", line 14, in test_splitself.assertEqual(s.split(), ['hellox', 'world'])AssertionError: Lists differ: ['hello', 'world'] != ['hellox', 'world']First differing element 0:'hello''hellox'- ['hello', 'world']+ ['hellox', 'world']? +----------------------------------------------------------------------Ran 3 tests in 0.001sFAILED (failures=1)16 / 26
  • 17.
    py.testhttp://doc.pytest.org/en/latest/ProsPluginsHTML outputSimpler andmore straight-forward syntaxAuto discovery of test functionsDistributedConsNot nativeCan get complicated too (decorators)17 / 26
  • 18.
    def inc(x):return x+ 1def test_answer():assert inc(3) == 518 / 26
  • 19.
    $ python3 -mpytest my_pytest.py============================================ test session starts ============================================platform linux -- Python 3.5.2+, pytest-3.0.6, py-1.4.32, pluggy-0.4.0rootdir: /tmp, inifile:collected 2 itemsneco.py F.================================================= FAILURES ==================================================________________________________________________ test_answer ________________________________________________def test_answer():> assert inc(3) == 5E assert 4 == 5E + where 4 = inc(3)neco.py:5: AssertionError==================================== 1 failed, 1 passed in 0.03 seconds =====================================19 / 26
  • 20.
    Doctesthttps://docs.python.org/3/library/doctest.htmlProsNativeTests are (canbe) part of class and method documentationCan be in separated text (e.g. README) filesSupported by SphinxConsNot suitable for larger testing systemsNo fixtures20 / 26
  • 21.
    def unique_words(page):''' Returnsset of the unique words in list of lines of textExample:>>> from StringIO import StringIO>>> fileText = """the cat sat on the mat... the mat was ondur the cat... one fish two fish red fish... blue fish... This fish has a yellow car... This fish has a yellow star""">>> file = StringIO(fileText)>>> page = file.readlines()>>> words = unique_words(page)>>> print sorted(list(words))["This", "a", "blue", "car", "cat", "fish", "has", "mat","on", "ondur", "one", "red", "sat", "star", "the", "two","was", "yellow"]>>>'''return set(word for line in page for word in line.split())def _test():import doctestdoctest.testmod()if __name__ == "__main__":_test()21 / 26
  • 22.
    $ python2 my_doctest.py**********************************************************************File"neco.py", line 16, in __main__.unique_wordsFailed example:print sorted(list(words))Expected:["This", "a", "blue", "car", "cat", "fish", "has", "mat","on", "ondur", "one", "red", "sat", "star", "the", "two","was", "yellow"]Got:['This', 'a', 'blue', 'car', 'cat', 'fish', 'has', 'mat', 'on', 'ondur', 'one', 'red', 'sat', 'star', 'the', 'two', 'was', 'yellow']**********************************************************************1 items had failures:1 of 6 in __main__.unique_words***Test Failed*** 1 failures.22 / 26
  • 23.
    nose (nose2)nose extendsunittest to make testing easiersmart developer should get familiar doctest, unittest, pytest, and nosehttps://pypi.python.org/pypi/nose/ --> new projects should use py.test ornose2https://github.com/nose-devs/nose2ProsBuild on top of unittestsOverpasses some of it's limitsCommand line toolConsnose not maintained any more --> nose2Not nativeUnder development (nose2)23 / 26
  • 24.
  • 25.
    ConclusionDoctests != py.testDoctestsare the natural way, how to test your code and how to documentitDoctests should be used for documentation, not for testingpy.test seems to be current leading testing frameworkEvent /me knows, what is the difference between doctests and py.test25 / 26
  • 26.
    That's all folks#jachymcjachym.cepickyat opengeolabs dot cz26 / 26

[8]ページ先頭

©2009-2025 Movatter.jp