SlideShare a Scribd company logo
Unit Testing Workshop
It’s not that scary
2
BEFORE THE WORKSHOP
● Download a code editor if you don’t have one
○ https://code.visualstudio.com/, or
○ https://www.jetbrains.com/pycharm/download/
● git clone https://github.com/davified/unit-testing-workshop
Windows users:
● docker run -it -v C:pathtounit-testing-workshop:/code -p 8888:8888 unit-testing-workshop
● Run all commands in the README up until:
○ nosetests --with-watch
● Configure your IDE (we’ll do this together)
3
WHY TEST?
Complexity
+
Change
©ThoughtWorks 2019 Commercial in Confidence
4
Feedback
Time
Unit
tests
Jupyter
notebooks
IT’S ALL ABOUT FEEDBACK
5
TEST PYRAMID
Unit tests
ML metrics tests
Any other
automated tests
Manual tests
Automate
d
Time
required
How do we unit test?
7
ANATOMY OF A UNIT TEST
assert_that(do_something(input) => expected_output)
8
ANATOMY OF A UNIT TEST
assert_that(do_something(input) => expected_output)
1. Think about what your function is doing
2. Write the simplest possible test case to assert that
9
ANATOMY OF A UNIT TEST
def add(n1, n2):
return n1 + n2
self.assertEqual(2, add(1,1))
10
EXERCISE 1: UNIT TESTING A CALCULATOR
1. Code walkthrough: src/test_calculator.py and src/calculator.py
11
EXERCISE 1: UNIT TESTING A CALCULATOR
● unittest module (built-in python module)
● How to write a unit test
○ File name must start with Test____
○ Define a class that extends unittest.TestCase
○ Method name must start with test____(self)
● Assertions
○ self.assertEqual(expected, actual())
● How to run tests
○ nosetests --with-watch
12
EXERCISE 1: UNIT TESTING A CALCULATOR - YOUR TURN!
● Implement
○ subtract(a, b)
○ multiply(a, b)
○ divide(a, b)
● Challenge: write the tests first!
13
GOOD TESTING PRACTICES
● Do the simplest thing possible
● Red green refactor
● Descriptive test names
● Pair program (+ ping pong)
14
ANTI-PATTERNS / BAD TESTING HABITS
● Redundant tests
● Bad test names
● Empty tests (no assertions)
● Unspecific tests (e.g. Asserting that add(2, 3) isNotNone)
● Non-deterministic tests (causes flaky tests)
● Tautological tests (i.e. repeating implementation details in test cases)
15
EXERCISE 2: UNIT TESTING + REFACTORING A JUPYTER NOTEBOOK
notebooks/sklearn-nlp-pipeline-before-refactoring.ipynb
16
EXERCISE 2: UNIT TESTING + REFACTORING A JUPYTER NOTEBOOK
Instructions
● Read the notebook to get a sense of what it’s doing (it’s training a simple
NLP model for sentiment classification)
● Sit back and relax
17
● Readable notebooks
● Automated tests -- no more visual eyeballing of long notebooks
● Smaller units → Separation of concerns
● Unit tests == living documentation
● Unit tests == safety harness
● Partition complexity (esp. if you TDD)
● Lesser bugs in production
● Possibility of refactoring → Ability to evolve to adapt to changing needs
BENEFITS
18
NEXT STEPS
● Learn by doing
○ http://codewars.com
○ Start with 1 unit test in your project codebase
○ Explore unittest docs: https://docs.python.org/3/library/unittest.html
(they’re good)
● Resources
○ Unit Testing for Data Scientists - Hanna Torrence
○ Lots of tutorials on the internet

More Related Content

What's hot (20)

PPTX
Python selenium
Ducat
 
PDF
Modern UI Development With Node.js
Ryan Anklam
 
PPTX
Unit Testing with Python
MicroPyramid .
 
PPT
Selenium
Adam Goucher
 
PDF
An introduction to unit testing
Adam Stephensen
 
PDF
Introducing Playwright's New Test Runner
Applitools
 
PDF
Présentation de Django @ Orange Labs (FR)
Martin Latrille
 
PDF
Robot framework 을 이용한 기능 테스트 자동화
Jaehoon Oh
 
PDF
Introduction to Kotlin coroutines
Roman Elizarov
 
PPTX
Jenkins presentation
Valentin Buryakov
 
PDF
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
Mario Heiderich
 
PPT
Shell Scripting
Gaurav Shinde
 
PPTX
Angular Unit Testing
Alessandro Giorgetti
 
PPTX
CICD Pipeline Using Github Actions
Kumar Shìvam
 
PDF
An introduction to Google test framework
Abner Chih Yi Huang
 
PDF
Unit testing best practices
nickokiss
 
PDF
Test Automation Using Python | Edureka
Edureka!
 
PPT
Introduction to Makefile
Tusharadri Sarkar
 
PPT
Cours JavaScript.ppt
PROFPROF11
 
PPTX
Js: master prototypes
Barak Drechsler
 
Python selenium
Ducat
 
Modern UI Development With Node.js
Ryan Anklam
 
Unit Testing with Python
MicroPyramid .
 
Selenium
Adam Goucher
 
An introduction to unit testing
Adam Stephensen
 
Introducing Playwright's New Test Runner
Applitools
 
Présentation de Django @ Orange Labs (FR)
Martin Latrille
 
Robot framework 을 이용한 기능 테스트 자동화
Jaehoon Oh
 
Introduction to Kotlin coroutines
Roman Elizarov
 
Jenkins presentation
Valentin Buryakov
 
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
Mario Heiderich
 
Shell Scripting
Gaurav Shinde
 
Angular Unit Testing
Alessandro Giorgetti
 
CICD Pipeline Using Github Actions
Kumar Shìvam
 
An introduction to Google test framework
Abner Chih Yi Huang
 
Unit testing best practices
nickokiss
 
Test Automation Using Python | Edureka
Edureka!
 
Introduction to Makefile
Tusharadri Sarkar
 
Cours JavaScript.ppt
PROFPROF11
 
Js: master prototypes
Barak Drechsler
 

Similar to Workshop: Unit Testing in Python (20)

PDF
Write unit test from scratch
Wen-Shih Chao
 
PDF
Writing Tests with the Unity Test Framework
Peter Kofler
 
PPTX
Unit Testing and TDD 2017
Xavi Hidalgo
 
PDF
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
PDF
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Igalia
 
PDF
Unit testing (eng)
Anatoliy Okhotnikov
 
PDF
UPC Plone Testing Talk
Timo Stollenwerk
 
PPTX
2016 10-04: tdd++: tdd made easier
Christian Hujer
 
PDF
Keeping code clean
Brett Child
 
PDF
Behaviour Driven Development and Thinking About Testing
dn
 
PDF
Bdd and-testing
malcolmt
 
PDF
Test-Driven Development (TDD) in Swift
Amey Tavkar
 
PDF
Tdd in swift
Javal Nanda
 
PDF
Demise of test scripts rise of test ideas
Richard Robinson
 
PDF
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
PDF
TDD in Python With Pytest
Eddy Reyes
 
PDF
Test Driven Development en Go con Ginkgo y Gomega
Software Guru
 
PDF
Working With Legacy Code
Andrea Polci
 
PDF
Introduction to Continuous Delivery
Giovanni Toraldo
 
PDF
Code Retreat
Igor Popov
 
Write unit test from scratch
Wen-Shih Chao
 
Writing Tests with the Unity Test Framework
Peter Kofler
 
Unit Testing and TDD 2017
Xavi Hidalgo
 
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Igalia
 
Unit testing (eng)
Anatoliy Okhotnikov
 
UPC Plone Testing Talk
Timo Stollenwerk
 
2016 10-04: tdd++: tdd made easier
Christian Hujer
 
Keeping code clean
Brett Child
 
Behaviour Driven Development and Thinking About Testing
dn
 
Bdd and-testing
malcolmt
 
Test-Driven Development (TDD) in Swift
Amey Tavkar
 
Tdd in swift
Javal Nanda
 
Demise of test scripts rise of test ideas
Richard Robinson
 
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
TDD in Python With Pytest
Eddy Reyes
 
Test Driven Development en Go con Ginkgo y Gomega
Software Guru
 
Working With Legacy Code
Andrea Polci
 
Introduction to Continuous Delivery
Giovanni Toraldo
 
Code Retreat
Igor Popov
 
Ad

Recently uploaded (20)

PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PPTX
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PDF
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
PDF
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
DOCX
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PDF
Next level data operations using Power Automate magic
Andries den Haan
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
Mastering Authorization: Integrating Authentication and Authorization Data in...
Hitachi, Ltd. OSS Solution Center.
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
How to Comply With Saudi Arabia’s National Cybersecurity Regulations.pdf
Bluechip Advanced Technologies
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
Next level data operations using Power Automate magic
Andries den Haan
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Ad

Workshop: Unit Testing in Python

  • 2. 2 BEFORE THE WORKSHOP ● Download a code editor if you don’t have one ○ https://code.visualstudio.com/, or ○ https://www.jetbrains.com/pycharm/download/ ● git clone https://github.com/davified/unit-testing-workshop Windows users: ● docker run -it -v C:pathtounit-testing-workshop:/code -p 8888:8888 unit-testing-workshop ● Run all commands in the README up until: ○ nosetests --with-watch ● Configure your IDE (we’ll do this together)
  • 4. ©ThoughtWorks 2019 Commercial in Confidence 4 Feedback Time Unit tests Jupyter notebooks IT’S ALL ABOUT FEEDBACK
  • 5. 5 TEST PYRAMID Unit tests ML metrics tests Any other automated tests Manual tests Automate d Time required
  • 6. How do we unit test?
  • 7. 7 ANATOMY OF A UNIT TEST assert_that(do_something(input) => expected_output)
  • 8. 8 ANATOMY OF A UNIT TEST assert_that(do_something(input) => expected_output) 1. Think about what your function is doing 2. Write the simplest possible test case to assert that
  • 9. 9 ANATOMY OF A UNIT TEST def add(n1, n2): return n1 + n2 self.assertEqual(2, add(1,1))
  • 10. 10 EXERCISE 1: UNIT TESTING A CALCULATOR 1. Code walkthrough: src/test_calculator.py and src/calculator.py
  • 11. 11 EXERCISE 1: UNIT TESTING A CALCULATOR ● unittest module (built-in python module) ● How to write a unit test ○ File name must start with Test____ ○ Define a class that extends unittest.TestCase ○ Method name must start with test____(self) ● Assertions ○ self.assertEqual(expected, actual()) ● How to run tests ○ nosetests --with-watch
  • 12. 12 EXERCISE 1: UNIT TESTING A CALCULATOR - YOUR TURN! ● Implement ○ subtract(a, b) ○ multiply(a, b) ○ divide(a, b) ● Challenge: write the tests first!
  • 13. 13 GOOD TESTING PRACTICES ● Do the simplest thing possible ● Red green refactor ● Descriptive test names ● Pair program (+ ping pong)
  • 14. 14 ANTI-PATTERNS / BAD TESTING HABITS ● Redundant tests ● Bad test names ● Empty tests (no assertions) ● Unspecific tests (e.g. Asserting that add(2, 3) isNotNone) ● Non-deterministic tests (causes flaky tests) ● Tautological tests (i.e. repeating implementation details in test cases)
  • 15. 15 EXERCISE 2: UNIT TESTING + REFACTORING A JUPYTER NOTEBOOK notebooks/sklearn-nlp-pipeline-before-refactoring.ipynb
  • 16. 16 EXERCISE 2: UNIT TESTING + REFACTORING A JUPYTER NOTEBOOK Instructions ● Read the notebook to get a sense of what it’s doing (it’s training a simple NLP model for sentiment classification) ● Sit back and relax
  • 17. 17 ● Readable notebooks ● Automated tests -- no more visual eyeballing of long notebooks ● Smaller units → Separation of concerns ● Unit tests == living documentation ● Unit tests == safety harness ● Partition complexity (esp. if you TDD) ● Lesser bugs in production ● Possibility of refactoring → Ability to evolve to adapt to changing needs BENEFITS
  • 18. 18 NEXT STEPS ● Learn by doing ○ http://codewars.com ○ Start with 1 unit test in your project codebase ○ Explore unittest docs: https://docs.python.org/3/library/unittest.html (they’re good) ● Resources ○ Unit Testing for Data Scientists - Hanna Torrence ○ Lots of tutorials on the internet

Editor's Notes

  • #2: Add caveat on TDD
  • #4: Enemy number 1 of software: complexity What adds to complexity? Long methods Cyclomatic complexity Etc. etc. Change We can’t refactor without unit tests Living documentation about our code Partition complexity Discover bugs early
  • #5: Jupyter notebooks hit a roadblock at some point Unit tests can scale linearly
  • #7: Let me share ThoughtWorks’ approach to machine learning
  • #9: What to test: our functions What not to test: methods from a library
  • #10: What to test: our functions What not to test: methods from a library
  • #11: The goal of this exercise is to get you to familiarize yourself with the syntax; and see that it’s really not that scary
  • #12: Demo for them. Delete add and go through this slide