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

More Related Content

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

What's hot

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

Viewers also liked

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

Similar to Python testing-frameworks overview

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

More from Jachym Cepicky

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

Recently uploaded

PPTX
UFCD 0797 - SISTEMAS OPERATIVOS_Unidade Completa.pptx
PDF
[BDD 2025 - Full-Stack Development] Digital Accessibility: Why Developers nee...
PDF
Accessibility & Inclusion: What Comes Next. Presentation of the Digital Acces...
PDF
Mastering UiPath Maestro – Session 2 – Building a Live Use Case - Session 2
PDF
Open Source Post-Quantum Cryptography - Matt Caswell
PDF
Transcript: The partnership effect: Libraries and publishers on collaborating...
PPTX
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
PPTX
"Feelings versus facts: why metrics are more important than intuition", Igor ...
 
PDF
Top Crypto Supers 15th Report November 2025
PDF
Cheryl Hung, Vibe Coding Auth Without Melting Down! isaqb Software Architectu...
PDF
The partnership effect: Libraries and publishers on collaborating and thrivin...
PPTX
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
PDF
Transforming Supply Chains with Amazon Bedrock AgentCore (AWS Swiss User Grou...
PDF
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
PDF
The Necessity of Digital Forensics, the Digital Forensics Process & Laborator...
PDF
Crane Accident Prevention Guide: Key OSHA Regulations for Safer Operations
PDF
How Much Does It Cost to Build an eCommerce Website in 2025.pdf
PDF
"DISC as GPS for team leaders: how to lead a team from storming to performing...
 
PDF
5 Common Supply Chain Attacks and How They Work | CyberPro Magazine
PDF
How Much Does It Cost To Build Software
UFCD 0797 - SISTEMAS OPERATIVOS_Unidade Completa.pptx
[BDD 2025 - Full-Stack Development] Digital Accessibility: Why Developers nee...
Accessibility & Inclusion: What Comes Next. Presentation of the Digital Acces...
Mastering UiPath Maestro – Session 2 – Building a Live Use Case - Session 2
Open Source Post-Quantum Cryptography - Matt Caswell
Transcript: The partnership effect: Libraries and publishers on collaborating...
The power of Slack and MuleSoft | Bangalore MuleSoft Meetup #60
"Feelings versus facts: why metrics are more important than intuition", Igor ...
 
Top Crypto Supers 15th Report November 2025
Cheryl Hung, Vibe Coding Auth Without Melting Down! isaqb Software Architectu...
The partnership effect: Libraries and publishers on collaborating and thrivin...
Guardrails in Action - Ensuring Safe AI with Azure AI Content Safety.pptx
Transforming Supply Chains with Amazon Bedrock AgentCore (AWS Swiss User Grou...
Mastering Agentic Orchestration with UiPath Maestro | Hands on Workshop
The Necessity of Digital Forensics, the Digital Forensics Process & Laborator...
Crane Accident Prevention Guide: Key OSHA Regulations for Safer Operations
How Much Does It Cost to Build an eCommerce Website in 2025.pdf
"DISC as GPS for team leaders: how to lead a team from storming to performing...
 
5 Common Supply Chain Attacks and How They Work | CyberPro Magazine
How Much Does It Cost To Build Software

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