SlideShare a Scribd company logo
TDD in Python With
Pytest
Eddy Reyes
eddy@tasqr.io
http://www.tasqr.io
Overview
● High-level discussion of TDD
● TDD walk-through with pytest
● Mocking with pytest
Not looking to proselytize TDD in this
presentation
● I’m just presenting the concepts and method.
Further Reading
Uncle Bob Martin
● http://blog.8thlight.com/uncle-bob/archive.html
Kent Beck
● Extreme Programming Explained (book)
Is TDD Dead? video series
● https://www.youtube.com/watch?v=z9quxZsLcfo (part 1)
Code From This Presentation
● https://github.com/ereyes01/apug-pytest-prez
What Is TDD?
● Methodology of Implementing Software
● It is NOT a silver bullet!
● It is NOT the only way to write good
software!
○ But, if followed, will help you write solid software!
Effective TDD
● TDD Method- To change a Program:
○ Write a unit test, watch it fail
○ Change the code to make the test pass
○ Rinse, repeat...
● Unit tests are effective when they are self-contained
○ No external dependencies
● TDD is not for prototyping!
○ Use when you fully understand your design and how
to code your solution
Anatomy of a Test
● Given… precondition
● When… X happens
● Then… Y must be true
Tests == Formal Design Spec
● Make your tests as readable as you would a (formal)
specification document.
Python TDD Tools
● Standard library
○ unittest
○ unittest.mock
■ As of Python 3.3
● Nosetests
● pytest
○ http://www.pytest.org
Testing With Pytest
● No classes needed!
● Fully takes advantage of Python’s dynamism to help
you design beautiful tests.
● Use plain Python assert instead of Xunit jargon
● Fixtures
○ Makes it easy to define your test preconditions
○ Fixtures can be nested arbitrarily, allowing complex
dependency trees
○ Cleanup is handled gracefully
Pytest Fixture Example
from my_flask_app import create_app
@pytest.fixture
def app():
app = create_app("test")
return app
@pytest.fixture
def app_client(app):
client = app.test_client()
return client
# GIVEN: app_client
def test_hello_route(app_client):
# WHEN:
reply = app_client.get(“/hello”)
# THEN:
assert reply.data == “Hello World”
Easy Test Dependencies
● Fixtures allow arbitrarily nested test
dependencies, eliminate DRY in your tests!
○ Compare with unittest... fixtures look like:
class TestSomething(unittest.TestCase):
def setUp():
# fixture code here
def tearDown():
# cleanup fixture here
def testSomething():
# test case code here
Example: TDD and Flask Hello World
● Let’s walk through how we would implement
the Flask Hello World example using TDD.
○ http://flask.pocoo.org
● Requirements:
○ Need a Flask app
○ Must reply the text “hello world” to a GET of the
“/hello” route.
Need to Experiment?
● Not yet sure how to build this?
○ Stop your TDD!
○ Play, read docs learn, experiment…
○ Build a prototype if you like
…
● Do NOT commit that code!
○ TDD is not for learning… it’s for executing on
something you already know how to build.
Step 1: Start With A Test
test_hello.py:
def test_hello():
"""
GIVEN: A flask hello app
WHEN: I GET the hello/ route
THEN: The response should be "hello world"
"""
assert True
Step 2: Define Test Dependencies
test_hello.py
import pytest
import hello_app
@pytest.fixture
def app():
return hello_app.app
@pytest.fixture
def test_client(app):
return app.test_client()
def test_hello(test_client):
"""
GIVEN: A flask hello app
WHEN: I GET the hello/ route
THEN: The response should be "hello world"
"""
assert True
Step 2 Cont’d
Step 3: Add hello_app Module
hello_app.py
import flask
app = flask.Flask(__name__)
Step 4: Add Test For /hello Route
test_hello.py
import pytest
import hello_app
@pytest.fixture
def app():
return hello_app.app
@pytest.fixture
def test_client(app):
return app.test_client()
def test_hello(test_client):
"""
GIVEN: A flask hello app
WHEN: I GET the hello/ route
THEN: The response should be "hello world"
"""
response = test_client.get("/hello")
assert response.data.decode("utf-8") == "hello world"
Step 4 Cont’d
Step 5: Add The /hello Route
hello_app.py
import flask
app = flask.Flask(__name__)
@app.route("/hello")
def hello():
return "hello world"
We’re Done!
Congratulations, you’ve just followed TDD to
create a Flask hello world web application!
Real Life is Never That Simple!
● Of course it’s not
● Applications connect to the network,
● Use databases,
● Do I/O on enormous files,
● etc.
Mocking The Edges Of Your App
● Mocks are a testing technique to stub out the
“edges” of your application
○ “Edges” == external components
● You don’t want to test external components
out of your control
○ Network
○ Database
○ Large Files
Mocking with Pytest’s monkeypatch
● Pytest defines a special fixture called monkeypatch
● Allows arbitrary setattr on anything in your tested
code’s namespace
● Example:
def test_unknown_file(monkeypatch):
monkeypatch.setattr("os.path.islink", lambda x: False)
monkeypatch.setattr("os.path.isdir", lambda x: False)
mylib.check_file("/some/path" )
● Monkeypatched symbols are restored in test cleanup
Mocks as Your Own Fixtures
● monkeypatch can be nested within your own fixtures to
define high-level dependencies
● Helps you write clean test code with mocks that follows
the pattern of Given-When-Then
● Mocks help your application code remain separate from
your testing mechanisms.
Let’s Extend Our Flask Example
● We will add a new route:
○ /hacker_news_encoding
○ This route returns the “Content-Encoding” header
value returned by the Hacker News site
● We can’t directly test Hacker News
○ Site could change
○ Site could be down
○ Unreliable test results
Step 6: Add a Test For The Route
MOCK_ENCODING = “mock-encoding”
def test_encoding_header(test_client, mock_encoding_request ):
"""
GIVEN: A flask hello app
A mock request handler
WHEN: I GET the /hacker_news_encoding route
THEN: The response should be the expected Content-Encoding
"""
response = test_client.get("/hacker_news_encoding")
assert response.data.decode("utf-8") == MOCK_ENCODING
Step 7: Add The Mock Fixture
class MockEncodingResponse:
def __init__(self):
self.headers = {"Content-Encoding": MOCK_ENCODING}
def _mock_get(url):
assert url == "https://news.ycombinator.com"
return MockEncodingResponse()
@pytest.fixture
def mock_encoding_request(monkeypatch):
monkeypatch.setattr("requests.get", _mock_get)
Step 7 Cont’d
Step 8: Add The New Route
hello_app.py
import flask
import requests
app = flask.Flask(__name__)
@app.route("/hello")
def hello():
return "hello world"
@app.route("/hacker_news_encoding")
def hacker_news_encoding():
url = "https://news.ycombinator.com"
resp = requests.get(url)
return response.headers["Content-Encoding"]
Step 8 Cont’d
Want The Code?
Fork me on Github!
https://github.com/ereyes01/apug-pytest-prez

More Related Content

What's hot (20)

PPTX
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Simplilearn
 
PDF
Python testing using mock and pytest
Suraj Deshmukh
 
ODP
Introduction to Perl - Day 1
Dave Cross
 
ODP
Python unit testing
Darryl Sherman
 
PPTX
Test Automation Framework with BDD and Cucumber
Rhoynar Software Consulting
 
PPTX
Cucumber With Selenium
Vishwanath KC
 
PPTX
docker.pptx
kohay75604
 
PPTX
Bdd and spec flow
Charles Nurse
 
PDF
객체지향 개념 (쫌 아는체 하기)
Seung-June Lee
 
PDF
Effective testing with pytest
Hector Canto
 
PDF
Robot Framework with Python | Edureka
Edureka!
 
PDF
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
PPTX
Clean Code - Writing code for human
NETKO Solution
 
PDF
Combinatorial software test design beyond pairwise testing
Justin Hunter
 
PDF
Clean code
Arturo Herrero
 
PPTX
Python: The Iterator Pattern
Damian T. Gordon
 
PPTX
Monitoring, Logging and Tracing on Kubernetes
Martin Etmajer
 
PPTX
TDD - Agile
harinderpisces
 
PPTX
Robot framework
boriau
 
PPTX
Unit Tests And Automated Testing
Lee Englestone
 
Selenium Tutorial For Beginners | Selenium Automation Testing Tutorial | Sele...
Simplilearn
 
Python testing using mock and pytest
Suraj Deshmukh
 
Introduction to Perl - Day 1
Dave Cross
 
Python unit testing
Darryl Sherman
 
Test Automation Framework with BDD and Cucumber
Rhoynar Software Consulting
 
Cucumber With Selenium
Vishwanath KC
 
docker.pptx
kohay75604
 
Bdd and spec flow
Charles Nurse
 
객체지향 개념 (쫌 아는체 하기)
Seung-June Lee
 
Effective testing with pytest
Hector Canto
 
Robot Framework with Python | Edureka
Edureka!
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Clean Code - Writing code for human
NETKO Solution
 
Combinatorial software test design beyond pairwise testing
Justin Hunter
 
Clean code
Arturo Herrero
 
Python: The Iterator Pattern
Damian T. Gordon
 
Monitoring, Logging and Tracing on Kubernetes
Martin Etmajer
 
TDD - Agile
harinderpisces
 
Robot framework
boriau
 
Unit Tests And Automated Testing
Lee Englestone
 

Viewers also liked (20)

PPTX
TDD in Go with Ginkgo and Gomega
Eddy Reyes
 
PPTX
Mocking in python
Ooblioob
 
PPTX
Mozilla Web QA - Evolution of our Python WebDriver framework
davehunt82
 
PDF
All about unit testing using (power) mock
Pranalee Rokde
 
PPT
AUTOMATED TESTING USING PYTHON (ATE)
Yuvaraja Ravi
 
PDF
Funcargs & other fun with pytest
Brianna Laugher
 
PDF
Pytest: escreva menos, teste mais
Erick Wilder
 
PDF
Учим автотесты человеческому языку с помощью Allure и PyTest
Rina Uzhevko
 
PDF
Python Testing Fundamentals
cbcunc
 
PDF
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
PDF
Нескучное тестирование с pytest
Roman Imankulov
 
PPTX
Comparative Analysis Of GoLang Testing Frameworks
Dushyant Bhalgami
 
PDF
Writing HTTP Middleware In Go
Shiju Varghese
 
PDF
Python-nose: A unittest-based testing framework for Python that makes writing...
Timo Stollenwerk
 
PDF
Python Unit Test
David Xie
 
PPTX
Python in Test automation
Krishnana Sreeraman
 
PDF
Data pipelines from zero to solid
Lars Albertsson
 
PDF
Socket Programming In Python
didip
 
PPTX
Automated Python Test Frameworks for Hardware Verification and Validation
Barbara Jones
 
PPT
Automated hardware testing using python
Yuvaraja Ravi
 
TDD in Go with Ginkgo and Gomega
Eddy Reyes
 
Mocking in python
Ooblioob
 
Mozilla Web QA - Evolution of our Python WebDriver framework
davehunt82
 
All about unit testing using (power) mock
Pranalee Rokde
 
AUTOMATED TESTING USING PYTHON (ATE)
Yuvaraja Ravi
 
Funcargs & other fun with pytest
Brianna Laugher
 
Pytest: escreva menos, teste mais
Erick Wilder
 
Учим автотесты человеческому языку с помощью Allure и PyTest
Rina Uzhevko
 
Python Testing Fundamentals
cbcunc
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland
 
Нескучное тестирование с pytest
Roman Imankulov
 
Comparative Analysis Of GoLang Testing Frameworks
Dushyant Bhalgami
 
Writing HTTP Middleware In Go
Shiju Varghese
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Timo Stollenwerk
 
Python Unit Test
David Xie
 
Python in Test automation
Krishnana Sreeraman
 
Data pipelines from zero to solid
Lars Albertsson
 
Socket Programming In Python
didip
 
Automated Python Test Frameworks for Hardware Verification and Validation
Barbara Jones
 
Automated hardware testing using python
Yuvaraja Ravi
 
Ad

Similar to TDD in Python With Pytest (20)

PPT
Python testing
John(Qiang) Zhang
 
PPTX
Unit testing and mocking in Python - PyCon 2018 - Kenya
Erick M'bwana
 
PDF
Write unit test from scratch
Wen-Shih Chao
 
PDF
Testdriven Development With Python 1st Edition Harry J W Percival
ykvfacwe5221
 
PPTX
Mocking in Python
Excella
 
PPTX
Intro to Mocking - DjangoCon 2015
Excella
 
PDF
Python and test
Micron Technology
 
PDF
DIY in 5 Minutes: Testing Django App with Pytest
Inexture Solutions
 
KEY
Overview of Testing Talks at Pycon
Jacqueline Kazil
 
PDF
TDD super mondays-june-2014
Alex Kavanagh
 
PPTX
Write tests, please
Joan López de la Franca
 
ODP
Automated Testing in Django
Loek van Gent
 
PDF
10 ways to shoot yourself in the foot with tests - Shai Geva, PyCon IL, 2024
Shai Geva
 
PDF
Unit Testing in Python
Haim Michael
 
PDF
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
PPTX
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
PDF
Scale and Load Testing of Micro-Service
IRJET Journal
 
PPTX
Mockito para tus pruebas unitarias
Antonio Robres Turon
 
PDF
Testing Django Applications
Gareth Rushgrove
 
PDF
Behaviour Driven Development and Thinking About Testing
dn
 
Python testing
John(Qiang) Zhang
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Erick M'bwana
 
Write unit test from scratch
Wen-Shih Chao
 
Testdriven Development With Python 1st Edition Harry J W Percival
ykvfacwe5221
 
Mocking in Python
Excella
 
Intro to Mocking - DjangoCon 2015
Excella
 
Python and test
Micron Technology
 
DIY in 5 Minutes: Testing Django App with Pytest
Inexture Solutions
 
Overview of Testing Talks at Pycon
Jacqueline Kazil
 
TDD super mondays-june-2014
Alex Kavanagh
 
Write tests, please
Joan López de la Franca
 
Automated Testing in Django
Loek van Gent
 
10 ways to shoot yourself in the foot with tests - Shai Geva, PyCon IL, 2024
Shai Geva
 
Unit Testing in Python
Haim Michael
 
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
2.Python_Testing_Using_PyUnit_PyTest.pptx
Ganesh Bhosale
 
Scale and Load Testing of Micro-Service
IRJET Journal
 
Mockito para tus pruebas unitarias
Antonio Robres Turon
 
Testing Django Applications
Gareth Rushgrove
 
Behaviour Driven Development and Thinking About Testing
dn
 
Ad

Recently uploaded (20)

PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Executive Business Intelligence Dashboards
vandeslie24
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Import Data Form Excel to Tally Services
Tally xperts
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 

TDD in Python With Pytest

  • 1. TDD in Python With Pytest Eddy Reyes [email protected] http://www.tasqr.io
  • 2. Overview ● High-level discussion of TDD ● TDD walk-through with pytest ● Mocking with pytest Not looking to proselytize TDD in this presentation ● I’m just presenting the concepts and method.
  • 3. Further Reading Uncle Bob Martin ● http://blog.8thlight.com/uncle-bob/archive.html Kent Beck ● Extreme Programming Explained (book) Is TDD Dead? video series ● https://www.youtube.com/watch?v=z9quxZsLcfo (part 1) Code From This Presentation ● https://github.com/ereyes01/apug-pytest-prez
  • 4. What Is TDD? ● Methodology of Implementing Software ● It is NOT a silver bullet! ● It is NOT the only way to write good software! ○ But, if followed, will help you write solid software!
  • 5. Effective TDD ● TDD Method- To change a Program: ○ Write a unit test, watch it fail ○ Change the code to make the test pass ○ Rinse, repeat... ● Unit tests are effective when they are self-contained ○ No external dependencies ● TDD is not for prototyping! ○ Use when you fully understand your design and how to code your solution
  • 6. Anatomy of a Test ● Given… precondition ● When… X happens ● Then… Y must be true Tests == Formal Design Spec ● Make your tests as readable as you would a (formal) specification document.
  • 7. Python TDD Tools ● Standard library ○ unittest ○ unittest.mock ■ As of Python 3.3 ● Nosetests ● pytest ○ http://www.pytest.org
  • 8. Testing With Pytest ● No classes needed! ● Fully takes advantage of Python’s dynamism to help you design beautiful tests. ● Use plain Python assert instead of Xunit jargon ● Fixtures ○ Makes it easy to define your test preconditions ○ Fixtures can be nested arbitrarily, allowing complex dependency trees ○ Cleanup is handled gracefully
  • 9. Pytest Fixture Example from my_flask_app import create_app @pytest.fixture def app(): app = create_app("test") return app @pytest.fixture def app_client(app): client = app.test_client() return client # GIVEN: app_client def test_hello_route(app_client): # WHEN: reply = app_client.get(“/hello”) # THEN: assert reply.data == “Hello World”
  • 10. Easy Test Dependencies ● Fixtures allow arbitrarily nested test dependencies, eliminate DRY in your tests! ○ Compare with unittest... fixtures look like: class TestSomething(unittest.TestCase): def setUp(): # fixture code here def tearDown(): # cleanup fixture here def testSomething(): # test case code here
  • 11. Example: TDD and Flask Hello World ● Let’s walk through how we would implement the Flask Hello World example using TDD. ○ http://flask.pocoo.org ● Requirements: ○ Need a Flask app ○ Must reply the text “hello world” to a GET of the “/hello” route.
  • 12. Need to Experiment? ● Not yet sure how to build this? ○ Stop your TDD! ○ Play, read docs learn, experiment… ○ Build a prototype if you like … ● Do NOT commit that code! ○ TDD is not for learning… it’s for executing on something you already know how to build.
  • 13. Step 1: Start With A Test test_hello.py: def test_hello(): """ GIVEN: A flask hello app WHEN: I GET the hello/ route THEN: The response should be "hello world" """ assert True
  • 14. Step 2: Define Test Dependencies test_hello.py import pytest import hello_app @pytest.fixture def app(): return hello_app.app @pytest.fixture def test_client(app): return app.test_client() def test_hello(test_client): """ GIVEN: A flask hello app WHEN: I GET the hello/ route THEN: The response should be "hello world" """ assert True
  • 16. Step 3: Add hello_app Module hello_app.py import flask app = flask.Flask(__name__)
  • 17. Step 4: Add Test For /hello Route test_hello.py import pytest import hello_app @pytest.fixture def app(): return hello_app.app @pytest.fixture def test_client(app): return app.test_client() def test_hello(test_client): """ GIVEN: A flask hello app WHEN: I GET the hello/ route THEN: The response should be "hello world" """ response = test_client.get("/hello") assert response.data.decode("utf-8") == "hello world"
  • 19. Step 5: Add The /hello Route hello_app.py import flask app = flask.Flask(__name__) @app.route("/hello") def hello(): return "hello world"
  • 20. We’re Done! Congratulations, you’ve just followed TDD to create a Flask hello world web application!
  • 21. Real Life is Never That Simple! ● Of course it’s not ● Applications connect to the network, ● Use databases, ● Do I/O on enormous files, ● etc.
  • 22. Mocking The Edges Of Your App ● Mocks are a testing technique to stub out the “edges” of your application ○ “Edges” == external components ● You don’t want to test external components out of your control ○ Network ○ Database ○ Large Files
  • 23. Mocking with Pytest’s monkeypatch ● Pytest defines a special fixture called monkeypatch ● Allows arbitrary setattr on anything in your tested code’s namespace ● Example: def test_unknown_file(monkeypatch): monkeypatch.setattr("os.path.islink", lambda x: False) monkeypatch.setattr("os.path.isdir", lambda x: False) mylib.check_file("/some/path" ) ● Monkeypatched symbols are restored in test cleanup
  • 24. Mocks as Your Own Fixtures ● monkeypatch can be nested within your own fixtures to define high-level dependencies ● Helps you write clean test code with mocks that follows the pattern of Given-When-Then ● Mocks help your application code remain separate from your testing mechanisms.
  • 25. Let’s Extend Our Flask Example ● We will add a new route: ○ /hacker_news_encoding ○ This route returns the “Content-Encoding” header value returned by the Hacker News site ● We can’t directly test Hacker News ○ Site could change ○ Site could be down ○ Unreliable test results
  • 26. Step 6: Add a Test For The Route MOCK_ENCODING = “mock-encoding” def test_encoding_header(test_client, mock_encoding_request ): """ GIVEN: A flask hello app A mock request handler WHEN: I GET the /hacker_news_encoding route THEN: The response should be the expected Content-Encoding """ response = test_client.get("/hacker_news_encoding") assert response.data.decode("utf-8") == MOCK_ENCODING
  • 27. Step 7: Add The Mock Fixture class MockEncodingResponse: def __init__(self): self.headers = {"Content-Encoding": MOCK_ENCODING} def _mock_get(url): assert url == "https://news.ycombinator.com" return MockEncodingResponse() @pytest.fixture def mock_encoding_request(monkeypatch): monkeypatch.setattr("requests.get", _mock_get)
  • 29. Step 8: Add The New Route hello_app.py import flask import requests app = flask.Flask(__name__) @app.route("/hello") def hello(): return "hello world" @app.route("/hacker_news_encoding") def hacker_news_encoding(): url = "https://news.ycombinator.com" resp = requests.get(url) return response.headers["Content-Encoding"]
  • 31. Want The Code? Fork me on Github! https://github.com/ereyes01/apug-pytest-prez