SlideShare a Scribd company logo
Unit Testing in Python
Haim Michael
August 1st
, 2022
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
life
michae
l
Quality Assurance Automation
www.lifemichael.com
© 2008 Haim Michael 20150805
What is Unit Testing?
© 2008 Haim Michael 20150805
What is Unit Testing?
 Unit test is a way of testing a unit (the smallest piece of code
that can be logically isolated in a system). In most
programming languages, that is a function, a subroutine, a
method or a property.
© 2008 Haim Michael 20150805
The TDD Methodology
 Test Driven Development (TDD) is a software development
methodology that focuses on creating unit test cases before
developing the actual code.
© 2008 Haim Michael 20150805
The TDD Methodology
 TDD leads to repetitive work flow in which we write the test,
write the code to be tested, execute the test and repeat these
two steps till the test passes.
Image Credit: TutorialPoint.com
© 2008 Haim Michael 20150805
The pytest Framework
© 2008 Haim Michael 20150805
The pytest Framework
 The pytest framework assists us with the development of
small readable tests. In addition, we can also use this library
when developing complex functional tests.
https://pytest.org
© 2008 Haim Michael 20150805
Installing The pytest Framework
 We can easily install this framework using the pip utility.
pip install -U pytest
 We can easily check the version of the pytest library we have
just installed using the following command:
pytest --version
Upgrading to Newest Version
© 2008 Haim Michael 20150805
Using The pytest Framework
 We can easily use the pytest framework by executing the
utility. Doing so, all files of the form test_*.py or
_test.py in the current directory and its subdirectories will
be examined, and all tests (functions their names start with
test_) will be called.
pytest
© 2008 Haim Michael 20150805
Simple Code Sample
def total(num1: int, num2: int) -> int:
result = num1 + num2
return result
def multiply(num1: int, num2: int) -> int:
result = num1 * num2
return result
utils.py
© 2008 Haim Michael 20150805
Simple Code Sample
import utils
def test_total():
actual_value = utils.total(3, 5)
expected_value = 8
assert actual_value == expected_value
def test_multiply():
actual_value = utils.multiply(3, 5)
expected_value = 15
assert actual_value == expected_value
test_utils.py
© 2008 Haim Michael 20150805
Simple Code Sample
© 2008 Haim Michael 20150805
Grouping Multiple Tests in Class
 We can group our tests in a class. We just need to define
each and every function with a name that starts with test_.
 There is no need to define a class that extends a specific
class that already exists. We just need to make sure that the
name of our class starts with Test.
© 2008 Haim Michael 20150805
Simple Code Sample
class BankAccount:
def __init__(self,id,balance):
self.id = id
self.balance = balance
def deposit(self,sum):
self.balance += sum
def withdraw(self,sum):
self.balance -= sum
banking.py
© 2008 Haim Michael 20150805
Simple Code Sample
import banking
class TestBankAccount:
def test_deposit(self):
ob = banking.BankAccount(123123,1000)
ob.deposit(80)
ob.deposit(120)
ob.deposit(400)
assert ob.balance == 1600
def test_withdraw(self):
ob = banking.BankAccount(123123,1000)
ob.withdraw(80)
ob.withdraw(120)
ob.withdraw(400)
assert ob.balance == 400
test_banking.py
© 2008 Haim Michael 20150805
Simple Code Sample
© 2008 Haim Michael 20150805
Assert Exceptions Raising
 We can assert whether a specific function raised an exception
using the raises helper.
© 2008 Haim Michael 20150805
Simple Code Sample
class BankAccount:
def __init__(self, id, balance):
self.id = id
self.balance = balance
def deposit(self, sum):
self.balance += sum
def withdraw(self, sum):
if sum<self.balance:
self.balance -= sum
else:
raise BankException("balance cannot be negative")
class BankException(Exception):
def __init__(self, message):
super().__init__(self, message)
banking.py
© 2008 Haim Michael 20150805
Simple Code Sample
import banking
import pytest
class TestBankAccount:
def perform_withdraws(self):
ob = banking.BankAccount(123123, 100)
ob.withdraw(80)
ob.withdraw(10)
ob.withdraw(30)
def test_withdraw(self):
with pytest.raises(banking.BankException):
self.perform_withdraws()
test_banking.py
© 2008 Haim Michael 20150805
Simple Code Sample
© 2008 Haim Michael 20150805
The requests Library
© 2008 Haim Michael 20150805
The Requests Library
 Requests is a simple HTTP library for Python. It allows us to
send HTTP requests.
https://docs.python-requests.org
© 2008 Haim Michael 20150805
Installation of Requests
 We can easily install Requests by using the pip command:
pip install requests
© 2008 Haim Michael 20150805
The GET Request
 We can easily initiate a GET request by calling the
requests.get() method.
© 2008 Haim Michael 20150805
The GET Request
import requests
data = requests.get("https://api.coinbase.com/v2/currencies")
print(data.status_code)
print(data.content)
print(data.text)
print(data.json()) #dict object
print(data.headers) #dict object
© 2008 Haim Michael 20150805
The GET Request
© 2008 Haim Michael 20150805
Query String Parameters
 We can easily customize the GET request, and send query
string parameters in the URL, by passing over a reference for
a dict object that holds those parameters.
© 2008 Haim Michael 20150805
Query String Parameters
import requests
response = requests.get(
"https://api.github.com/search/repositories",
params={'q': 'requests+language:python'})
data = response.json()
print(data)
© 2008 Haim Michael 20150805
Request Headers
 We can easily customize the headers that are sent together
with the request by passing over a reference for a dict object
that holds the headers we want to customize. The names of
the headers are the keys, and the values of the headers are
the values of those keys.
© 2008 Haim Michael 20150805
Request Headers
import requests
response = requests.get(
"https://api.github.com/search/repositories",
params={'q': 'requests+language:python'},
headers={'sec-ch-ua-platform': 'macOS'})
data = response.json()
print(data)
© 2008 Haim Michael 20150805
Other HTTP Methods
 In addition to the get() method, The Requests library
provides us with other similar methods for each one of the
other HTTP methods.
© 2008 Haim Michael 20150805
Other HTTP Methods
import requests
response = requests.post('https://httpbin.org/post',
data={'key':'value'})
print(response.json())
response = requests.put('https://httpbin.org/put',
data={'key':'value'})
print(response.json())
response = requests.delete('https://httpbin.org/delete')
print(response.json())
© 2008 Haim Michael 20150805
Other HTTP Methods
© 2008 Haim Michael 20150805
Introspecting The Request
 When making the request, the Requests library prepares the
request before sending it.
 We can introspect the request by referring the request
attribute of the response object.
© 2008 Haim Michael 20150805
Introspecting The Request
import requests
response = requests.post('https://httpbin.org/post', data={'key':'value'})
print(response.request.headers['Content-Type'])
print(response.request.url)
print(response.request.body)
© 2008 Haim Michael 20150805
REStful Web Services Testing
 We can easily write unit tests for REStful web services using
the PyTest unit testing framework and the Requests library.
© 2008 Haim Michael 20150805
REStful Web Services Testing
import requests
def test_get_status_code_ok_from_httpbin():
response = requests.get(
'https://httpbin.org/get',
data={'key': 'value'})
assert response.status_code == 200
© 2008 Haim Michael 20150805
Best Practices
08/01/22 © Abelski eLearning 39
Readable Code
 The unit tests we develop should be updated in accordance
with the changes that take place in the code we test.
 Having readable code will eases the update of the unit tests
code, either by us or by others.
08/01/22 © Abelski eLearning 40
Deterministic Tests
 It would be better if we use deterministic data instead of
randomized generated one.
 Deterministic tests either pass in all executions or not. They
exhibit the same behavior every time they run.
08/01/22 © Abelski eLearning 41
Avoid Interdependencies
 We better have each test case with its own setup and
teardown mechanism in order to avoid interdependencies
between the tests.
08/01/22 © Abelski eLearning 42
Avoid Logic
 Writing unit tests with logical conditions, manual strings
concatenation and various calculations might increase the
risk for bugs in our unit tests. The tests should focus on the
expected result.
08/01/22 © Abelski eLearning 43
Implementing TDD
 When we develop our unit tests before we develop the code
the quality of our tests improves.
08/01/22 © Abelski eLearning 44
CI/CD Integration
 Integrating our unit tests into the CI/CD pipeline will allow us
to run them several times per day (automatically). Doing so
will improve the quality of our code.
08/01/22 © Abelski eLearning 45
Update Our Tests
 Maintaining and updating the tests periodically will improve
their quality.
© 2009 Haim Michael All Rights Reserved 46
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
+972+54+6655837 (whatsapp)
life
michael

More Related Content

What's hot

Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test PresentationSayedur Rahman
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
José Paumard
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
Prashant Cholachagudd
 
Keyword-driven Test Automation Framework
Keyword-driven Test Automation FrameworkKeyword-driven Test Automation Framework
Keyword-driven Test Automation Framework
Mikhail Subach
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
Michał Pierzchała
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
Devvrat Shukla
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
Dror Helper
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
ikhwanhayat
 
Create an architecture for web test automation
Create an architecture for web test automationCreate an architecture for web test automation
Create an architecture for web test automation
Elias Nogueira
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
Mindfire Solutions
 
JUnit 5
JUnit 5JUnit 5
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
CodeOps Technologies LLP
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
Siddhi
 
Testing In Django
Testing In DjangoTesting In Django
Testing In Django
Daniel Greenfeld
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
David Berliner
 
Karate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleKarate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made Simple
VodqaBLR
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
Baskar K
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
intuit_india
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Sergey Podolsky
 

What's hot (20)

Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test Presentation
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Keyword-driven Test Automation Framework
Keyword-driven Test Automation FrameworkKeyword-driven Test Automation Framework
Keyword-driven Test Automation Framework
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Create an architecture for web test automation
Create an architecture for web test automationCreate an architecture for web test automation
Create an architecture for web test automation
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Testing In Django
Testing In DjangoTesting In Django
Testing In Django
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Karate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleKarate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made Simple
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 

Similar to Unit Testing in Python

OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
Haim Michael
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
Haim Michael
 
Typescript vas ES6
Typescript vas ES6Typescript vas ES6
Typescript vas ES6
Haim Michael
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
Haim Michael
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
Rohit Radhakrishnan
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Ukraine
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript Seminar
Haim Michael
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023
Scott Keck-Warren
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
Rohit Radhakrishnan
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
Haim Michael
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023
Scott Keck-Warren
 
Best Practices for Measuring your Code Pipeline
Best Practices for Measuring your Code PipelineBest Practices for Measuring your Code Pipeline
Best Practices for Measuring your Code Pipeline
New Relic
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
Seb Rose
 
Functional programming in Java
Functional programming in Java  Functional programming in Java
Functional programming in Java
Haim Michael
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
Gianluca Padovani
 
Automation service introduction
Automation service introductionAutomation service introduction
Automation service introduction
Hai Tran Son
 
Aether T-Innovations company presentation
Aether T-Innovations company presentationAether T-Innovations company presentation
Aether T-Innovations company presentation
Shriniwas Gadage
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
Tao Xie
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
justmeanscsr
 

Similar to Unit Testing in Python (20)

OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
 
Typescript vas ES6
Typescript vas ES6Typescript vas ES6
Typescript vas ES6
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
TypeScript Seminar
TypeScript SeminarTypeScript Seminar
TypeScript Seminar
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023
 
Best Practices for Measuring your Code Pipeline
Best Practices for Measuring your Code PipelineBest Practices for Measuring your Code Pipeline
Best Practices for Measuring your Code Pipeline
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Functional programming in Java
Functional programming in Java  Functional programming in Java
Functional programming in Java
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Automation service introduction
Automation service introductionAutomation service introduction
Automation service introduction
 
Aether T-Innovations company presentation
Aether T-Innovations company presentationAether T-Innovations company presentation
Aether T-Innovations company presentation
 
Automated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and ChallengesAutomated Developer Testing: Achievements and Challenges
Automated Developer Testing: Achievements and Challenges
 
Justmeans power point
Justmeans power pointJustmeans power point
Justmeans power point
 
Top Testing Tips
Top Testing TipsTop Testing Tips
Top Testing Tips
 

More from Haim Michael

Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
Haim Michael
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
Haim Michael
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
Haim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
Haim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
Haim Michael
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
Haim Michael
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
Haim Michael
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
Haim Michael
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
Haim Michael
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
Haim Michael
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
Haim Michael
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
Haim Michael
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]
Haim Michael
 

More from Haim Michael (20)

Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
 
Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 
The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]The Power of Decorators in Python [Meetup]
The Power of Decorators in Python [Meetup]
 

Recently uploaded

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

Unit Testing in Python

  • 1. Unit Testing in Python Haim Michael August 1st , 2022 All logos, trade marks and brand names used in this presentation belong to the respective owners. life michae l Quality Assurance Automation www.lifemichael.com
  • 2. © 2008 Haim Michael 20150805 What is Unit Testing?
  • 3. © 2008 Haim Michael 20150805 What is Unit Testing?  Unit test is a way of testing a unit (the smallest piece of code that can be logically isolated in a system). In most programming languages, that is a function, a subroutine, a method or a property.
  • 4. © 2008 Haim Michael 20150805 The TDD Methodology  Test Driven Development (TDD) is a software development methodology that focuses on creating unit test cases before developing the actual code.
  • 5. © 2008 Haim Michael 20150805 The TDD Methodology  TDD leads to repetitive work flow in which we write the test, write the code to be tested, execute the test and repeat these two steps till the test passes. Image Credit: TutorialPoint.com
  • 6. © 2008 Haim Michael 20150805 The pytest Framework
  • 7. © 2008 Haim Michael 20150805 The pytest Framework  The pytest framework assists us with the development of small readable tests. In addition, we can also use this library when developing complex functional tests. https://pytest.org
  • 8. © 2008 Haim Michael 20150805 Installing The pytest Framework  We can easily install this framework using the pip utility. pip install -U pytest  We can easily check the version of the pytest library we have just installed using the following command: pytest --version Upgrading to Newest Version
  • 9. © 2008 Haim Michael 20150805 Using The pytest Framework  We can easily use the pytest framework by executing the utility. Doing so, all files of the form test_*.py or _test.py in the current directory and its subdirectories will be examined, and all tests (functions their names start with test_) will be called. pytest
  • 10. © 2008 Haim Michael 20150805 Simple Code Sample def total(num1: int, num2: int) -> int: result = num1 + num2 return result def multiply(num1: int, num2: int) -> int: result = num1 * num2 return result utils.py
  • 11. © 2008 Haim Michael 20150805 Simple Code Sample import utils def test_total(): actual_value = utils.total(3, 5) expected_value = 8 assert actual_value == expected_value def test_multiply(): actual_value = utils.multiply(3, 5) expected_value = 15 assert actual_value == expected_value test_utils.py
  • 12. © 2008 Haim Michael 20150805 Simple Code Sample
  • 13. © 2008 Haim Michael 20150805 Grouping Multiple Tests in Class  We can group our tests in a class. We just need to define each and every function with a name that starts with test_.  There is no need to define a class that extends a specific class that already exists. We just need to make sure that the name of our class starts with Test.
  • 14. © 2008 Haim Michael 20150805 Simple Code Sample class BankAccount: def __init__(self,id,balance): self.id = id self.balance = balance def deposit(self,sum): self.balance += sum def withdraw(self,sum): self.balance -= sum banking.py
  • 15. © 2008 Haim Michael 20150805 Simple Code Sample import banking class TestBankAccount: def test_deposit(self): ob = banking.BankAccount(123123,1000) ob.deposit(80) ob.deposit(120) ob.deposit(400) assert ob.balance == 1600 def test_withdraw(self): ob = banking.BankAccount(123123,1000) ob.withdraw(80) ob.withdraw(120) ob.withdraw(400) assert ob.balance == 400 test_banking.py
  • 16. © 2008 Haim Michael 20150805 Simple Code Sample
  • 17. © 2008 Haim Michael 20150805 Assert Exceptions Raising  We can assert whether a specific function raised an exception using the raises helper.
  • 18. © 2008 Haim Michael 20150805 Simple Code Sample class BankAccount: def __init__(self, id, balance): self.id = id self.balance = balance def deposit(self, sum): self.balance += sum def withdraw(self, sum): if sum<self.balance: self.balance -= sum else: raise BankException("balance cannot be negative") class BankException(Exception): def __init__(self, message): super().__init__(self, message) banking.py
  • 19. © 2008 Haim Michael 20150805 Simple Code Sample import banking import pytest class TestBankAccount: def perform_withdraws(self): ob = banking.BankAccount(123123, 100) ob.withdraw(80) ob.withdraw(10) ob.withdraw(30) def test_withdraw(self): with pytest.raises(banking.BankException): self.perform_withdraws() test_banking.py
  • 20. © 2008 Haim Michael 20150805 Simple Code Sample
  • 21. © 2008 Haim Michael 20150805 The requests Library
  • 22. © 2008 Haim Michael 20150805 The Requests Library  Requests is a simple HTTP library for Python. It allows us to send HTTP requests. https://docs.python-requests.org
  • 23. © 2008 Haim Michael 20150805 Installation of Requests  We can easily install Requests by using the pip command: pip install requests
  • 24. © 2008 Haim Michael 20150805 The GET Request  We can easily initiate a GET request by calling the requests.get() method.
  • 25. © 2008 Haim Michael 20150805 The GET Request import requests data = requests.get("https://api.coinbase.com/v2/currencies") print(data.status_code) print(data.content) print(data.text) print(data.json()) #dict object print(data.headers) #dict object
  • 26. © 2008 Haim Michael 20150805 The GET Request
  • 27. © 2008 Haim Michael 20150805 Query String Parameters  We can easily customize the GET request, and send query string parameters in the URL, by passing over a reference for a dict object that holds those parameters.
  • 28. © 2008 Haim Michael 20150805 Query String Parameters import requests response = requests.get( "https://api.github.com/search/repositories", params={'q': 'requests+language:python'}) data = response.json() print(data)
  • 29. © 2008 Haim Michael 20150805 Request Headers  We can easily customize the headers that are sent together with the request by passing over a reference for a dict object that holds the headers we want to customize. The names of the headers are the keys, and the values of the headers are the values of those keys.
  • 30. © 2008 Haim Michael 20150805 Request Headers import requests response = requests.get( "https://api.github.com/search/repositories", params={'q': 'requests+language:python'}, headers={'sec-ch-ua-platform': 'macOS'}) data = response.json() print(data)
  • 31. © 2008 Haim Michael 20150805 Other HTTP Methods  In addition to the get() method, The Requests library provides us with other similar methods for each one of the other HTTP methods.
  • 32. © 2008 Haim Michael 20150805 Other HTTP Methods import requests response = requests.post('https://httpbin.org/post', data={'key':'value'}) print(response.json()) response = requests.put('https://httpbin.org/put', data={'key':'value'}) print(response.json()) response = requests.delete('https://httpbin.org/delete') print(response.json())
  • 33. © 2008 Haim Michael 20150805 Other HTTP Methods
  • 34. © 2008 Haim Michael 20150805 Introspecting The Request  When making the request, the Requests library prepares the request before sending it.  We can introspect the request by referring the request attribute of the response object.
  • 35. © 2008 Haim Michael 20150805 Introspecting The Request import requests response = requests.post('https://httpbin.org/post', data={'key':'value'}) print(response.request.headers['Content-Type']) print(response.request.url) print(response.request.body)
  • 36. © 2008 Haim Michael 20150805 REStful Web Services Testing  We can easily write unit tests for REStful web services using the PyTest unit testing framework and the Requests library.
  • 37. © 2008 Haim Michael 20150805 REStful Web Services Testing import requests def test_get_status_code_ok_from_httpbin(): response = requests.get( 'https://httpbin.org/get', data={'key': 'value'}) assert response.status_code == 200
  • 38. © 2008 Haim Michael 20150805 Best Practices
  • 39. 08/01/22 © Abelski eLearning 39 Readable Code  The unit tests we develop should be updated in accordance with the changes that take place in the code we test.  Having readable code will eases the update of the unit tests code, either by us or by others.
  • 40. 08/01/22 © Abelski eLearning 40 Deterministic Tests  It would be better if we use deterministic data instead of randomized generated one.  Deterministic tests either pass in all executions or not. They exhibit the same behavior every time they run.
  • 41. 08/01/22 © Abelski eLearning 41 Avoid Interdependencies  We better have each test case with its own setup and teardown mechanism in order to avoid interdependencies between the tests.
  • 42. 08/01/22 © Abelski eLearning 42 Avoid Logic  Writing unit tests with logical conditions, manual strings concatenation and various calculations might increase the risk for bugs in our unit tests. The tests should focus on the expected result.
  • 43. 08/01/22 © Abelski eLearning 43 Implementing TDD  When we develop our unit tests before we develop the code the quality of our tests improves.
  • 44. 08/01/22 © Abelski eLearning 44 CI/CD Integration  Integrating our unit tests into the CI/CD pipeline will allow us to run them several times per day (automatically). Doing so will improve the quality of our code.
  • 45. 08/01/22 © Abelski eLearning 45 Update Our Tests  Maintaining and updating the tests periodically will improve their quality.
  • 46. © 2009 Haim Michael All Rights Reserved 46 Questions & Answers Thanks for Your Time! Haim Michael haim.michael@lifemichael.com +972+3+3726013 ext:700 +972+54+6655837 (whatsapp) life michael