SlideShare a Scribd company logo
TDD in Python
Shuhsi Lin
2017/6/16
Aganda
More info on how to use this template at
www.slidescarnival.com/help-use-presentation-template
Testing
○
○
○
○
Unit Test
○
○
○
○
TDD
○
○
Hello!
Testing
Software Testing
Why Software Testing
1. Deliver the best application we can.
2. Lots of different devices, browsers, and operating systems
3. User really will do that – no matter how silly it seems.
4. One person to hundreds of people, even more, are using it.
5. To ensure that what we create does what it’s supposed to do.
http://www.te52.com/testtalk/2014/08/07/5-reasons-we-need-software-testing/
Precision and Accuracy, Validation, Reliability, and Quality
Delivery of high quality product or software
application to customers
Test Principles
Principles are just for reference. I will not use them in practise.
http://istqbexamcertification.com/what-are-the-principles-of-testing/
http://www.guru99.com/software-testing-seven-principles.html
Testing methods and Types
○
○
○
Testing levels
Unit testing
Integration testing
System testing
Operational acceptance
testing
Developers
White box
Testers (QA, users)
Black box
“
Developers
S
Write test program to test
Write test
program to test
1. Instant Feedback
◦ ( Time (testing) << Time(debugging) )
2. Regression Testing and Refactoring
3. API design
4. (Unit) test is Document
Unit Test
What Is Unit test?
● Smallest testable part of an application like functions, classes, procedures, interfaces.
● Breaking your program into pieces, and subjecting each piece to a series of tests
● should be done by the developers.
http://istqbexamcertification.com/what-is-unit-testing/
Unit test is good, because
● Issues are found at early stage
● Unit testing helps in maintaining and changing the code
● Reducing the cost of bug fixes.
● Simplifying the debugging process
Assert
Telling the program to test that condition, and
trigger an error if the condition is false.
if not condition:
raise AssertionError()
>>> assert True
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
Assert =
https://docs.python.org/3/reference/simple_stmts.html#assert
class Calculator:
def mod(self, dividend, divisor):
remainder = dividend % divisor
quotient = (dividend - remainder) / divisor
return quotient, remainder
if __name__ == '__main__':
cal = Calculator()
assert cal.mod(5, 3) == (1, 2) # 5 / 3 = 1 ... 2
assert cal.mod(8, 4) == (1, 0) # 8 / 4 = 2 ... 0
Assert example
https://imsardine.wordpress.com/tech/unit-testing-in-python/
Traceback (most recent call last):
File "/Users/shuhsi/github/TDD-kata/test_calc.py", line 11,
in <module>
assert cal.mod(8, 4) == (1, 0) # 8 / 4 = 2 ... 0
AssertionError
https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks
xUnit Framework
● Architecture for unit testing frameworks that are code-driven
● By Kent Beck
● Prescribes testing the fundamental units of software
–examples: functions, methods, classes
● Distinguishes between failures and errors in a unit of software
Each Test case has four-phase:
● Setup
● Exercise
● Verify (assertion)
● Teardown (cleanup)
Python and test
Python Example
https://docs.python.org/3/library/unittest.html
import unittest
class 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 string
with self.assertRaises (TypeError) :
s. split(2)
if __name__ == '__main__':
unittest. main()
import unittest
class Calculator:
def mod(self, dividend, divisor):
remainder = dividend % divisor
quotient = (dividend - remainder) / divisor
return quotient, remainder
class CalculatorTest (unittest.TestCase):
def test_mod_with_remainder (self):
cal = Calculator()
self.assertEqual (cal.mod(5, 3), (1, 2))
def test_mod_without_remainder (self):
cal = Calculator()
self.assertEqual (cal.mod(8, 4), (1, 0))
def test_mod_divide_by_zero (self):
cal = Calculator()
assertRaises (ZeroDivisionError, cal.mod, 7, 1)
if __name__ == '__main__':
unittest. main()
Subclass of unittest
Prefix: test
assertEqual
Import unitest
Run all test cases
Raise error
======================================================================
ERROR: test_mod_divide_by_zero (__main__.CalculatorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/shuhsi/github/TDD-kata/test_calc.py", line 22, in test_mod_divide_by_zero
assertRaises(ZeroDivisionError, cal.mod, 7, 1)
NameError: global name 'assertRaises' is not defined
======================================================================
FAIL: test_mod_without_remainder (__main__.CalculatorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/shuhsi/github/TDD-kata/test_calc.py", line 18, in test_mod_without_remainder
self.assertEqual(cal.mod(8, 4), (1, 0))
AssertionError: Tuples differ: (2, 0) != (1, 0)
First differing element 0:
2
1
- (2, 0)
? ^
+ (1, 0)
? ^
----------------------------------------------------------------------
Ran 3 tests in 0.009s
FAILED (failures=1, errors=1)
Show difference
error
TDD
What Is TDD?
● Test-driven development
● A methodology of Implementing Software that relies on the
repetition of a very short development cycle
TDD is not
● a developing Tool
● a silver bullet for problems!
● the ONLY way to write good software!
○ But, if followed, will help you write solid software!
TDD cycles
http://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html
1. Create a unit tests that fails
2. Write production code that makes that
test pass
3. Clean up the mess you just made
Let’s Try it
"Write a program that prints the numbers from 1 to
100. But for multiples of three print “Fizz” instead of
the number and for the multiples of five print
“Buzz”. For numbers which are multiples of both
three and five print “FizzBuzz”
FizzBuzz
Problem
http://codingdojo.org/kata/FizzBuzz/
Sample output
import unittest
class TestFizzBuzz(unittest.TestCase):
def test_0_raise_value_error (self):
with self.assertRaises(ValueError):
FizzBuzz(0)
Write a test (will fail)
Not exist yet
fizzbuzz_test.py
import unittest
from fizzbuzz import FizzBuzz
class TestFizzBuzz(unittest.TestCase):
def test_0_raise_value_error (self):
with self.assertRaises(ValueError):
FizzBuzz(0)
Write a production code (will pass a test)
class FizzBuzz(object):
pass
class FizzBuzz(object):
pass
Refactor
class FizzBuzz(object):
def __init__(self, number):
raise ValueError()
import unittest
from fizzbuzz import FizzBuzz
class TestFizzBuzz(unittest.TestCase):
def test_0_raise_value_error (self):
with self.assertRaises(ValueError):
FizzBuzz(0)
def test_1_does_mot -raise_value_error (self):
assert FizzBuzz(1).number == 1
(iteration 2) Write a test (will fail)
(iteration 2)Write a production code (will
pass a test)
class FizzBuzz(object):
def __init__(self, number):
if number == 0:
raise ValueError()
self.number =1
https://youtu.be/JJk_HK2ZWGg
What TDD can help you?
https://www.madetech.com/blog/9-benefits-of-test-driven-development
1. Acceptance Criteria
2. Focus
3. Interfaces
4. Tidier Code
5. Dependencies
6. Safer Refactoring
7. Fewer Bugs
8. Increasing Returns
9. Living Documentation
Testing/coding is so hard!! How to do it?
https://www.youtube.com/watch?v=KijjEG_DQ34
Code Kata and Dojo
http://blog.agilepartner.net/code-kata-improve-your-coding-skills/
http://codingdojo.org/dojo/
http://www.skfscotland.co.uk/katas/kushanku_kata.gif
More about
testing and xDD
○
○
○
○
○
FURTHER READING:
Uncle Bob Martin
◦ Clean code
◦ http://blog.8thlight.com/uncle-bob/archive.html
Kent Beck
◦ Extreme Programming Explained
◦ Test Driven Development: By Example
Is TDD Dead?
Test-Driven Development with Python
Essential TDD (Test-Driven Development) for
Pythoners, Pycontw 2016
RSpec & TDD Tutorial by ihower
Thanks!

More Related Content

What's hot (20)

PDF
Test Driven Development (TDD)
David Ehringer
 
PDF
Engaging IV&V Testing Services for Agile Projects
Ravi Kumar
 
PPTX
TDD - Agile
harinderpisces
 
PPT
Scrum and Test-driven development
toteb5
 
DOCX
Test driven development and unit testing with examples in C++
Hong Le Van
 
PDF
Agile Programming Systems # TDD intro
Vitaliy Kulikov
 
PPT
TDD (Test Driven Design)
nedirtv
 
PDF
Codeception Testing Framework -- English #phpkansai
Florent Batard
 
PPT
Test Driven Development
Sachithra Gayan
 
DOCX
TestDrivenDeveloment
Antonio Tapper
 
PPT
Unit Testing
François Camus
 
PPTX
Test-Driven Development (TDD)
Brian Rasmussen
 
PDF
Introduction to test automation in java and php
Tho Q Luong Luong
 
PPTX
Unit test
Tran Duc
 
PPTX
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
PDF
TDD Flow: The Mantra in Action
Dionatan default
 
PDF
Test driven development
Sharafat Ibn Mollah Mosharraf
 
PPTX
Test Driven Development (TDD) Preso 360|Flex 2010
guest5639fa9
 
PDF
Introduction to TDD (Test Driven development) - Ahmed Shreef
Ahmed Shreef
 
PPTX
TDD - Test Driven Development
Tung Nguyen Thanh
 
Test Driven Development (TDD)
David Ehringer
 
Engaging IV&V Testing Services for Agile Projects
Ravi Kumar
 
TDD - Agile
harinderpisces
 
Scrum and Test-driven development
toteb5
 
Test driven development and unit testing with examples in C++
Hong Le Van
 
Agile Programming Systems # TDD intro
Vitaliy Kulikov
 
TDD (Test Driven Design)
nedirtv
 
Codeception Testing Framework -- English #phpkansai
Florent Batard
 
Test Driven Development
Sachithra Gayan
 
TestDrivenDeveloment
Antonio Tapper
 
Unit Testing
François Camus
 
Test-Driven Development (TDD)
Brian Rasmussen
 
Introduction to test automation in java and php
Tho Q Luong Luong
 
Unit test
Tran Duc
 
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
TDD Flow: The Mantra in Action
Dionatan default
 
Test driven development
Sharafat Ibn Mollah Mosharraf
 
Test Driven Development (TDD) Preso 360|Flex 2010
guest5639fa9
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Ahmed Shreef
 
TDD - Test Driven Development
Tung Nguyen Thanh
 

Viewers also liked (8)

PPTX
Kafka Tutorial: Streaming Data Architecture
Jean-Paul Azar
 
PDF
London Apache Kafka Meetup (Jan 2017)
Landoop Ltd
 
PDF
Athens BigData Meetup - Sept 17
Landoop Ltd
 
PPTX
Kafka Tutorial - DevOps, Admin and Ops
Jean-Paul Azar
 
PDF
From Big to Fast Data. How #kafka and #kafka-connect can redefine you ETL and...
Landoop Ltd
 
PDF
Connect K of SMACK:pykafka, kafka-python or?
Micron Technology
 
PPTX
Kafka Tutorial Advanced Kafka Consumers
Jean-Paul Azar
 
PPTX
Kafka Tutorial: Advanced Producers
Jean-Paul Azar
 
Kafka Tutorial: Streaming Data Architecture
Jean-Paul Azar
 
London Apache Kafka Meetup (Jan 2017)
Landoop Ltd
 
Athens BigData Meetup - Sept 17
Landoop Ltd
 
Kafka Tutorial - DevOps, Admin and Ops
Jean-Paul Azar
 
From Big to Fast Data. How #kafka and #kafka-connect can redefine you ETL and...
Landoop Ltd
 
Connect K of SMACK:pykafka, kafka-python or?
Micron Technology
 
Kafka Tutorial Advanced Kafka Consumers
Jean-Paul Azar
 
Kafka Tutorial: Advanced Producers
Jean-Paul Azar
 
Ad

Similar to Python and test (20)

PPTX
Test-Driven Development In Action
Jon Kruger
 
PDF
How to complement TDD with static analysis
PVS-Studio
 
PDF
TDD Workshop UTN 2012
Facundo Farias
 
PPTX
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Elad Elrom
 
PPTX
TDD Best Practices
Attila Bertók
 
PDF
Writing Tests with the Unity Test Framework
Peter Kofler
 
PDF
Test Driven Development Introduction
Nguyen Hai
 
PDF
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
PDF
Test Driven Development
pmanvi
 
PDF
Test Driven Development
Kumaresh Chandra Baruri
 
PPTX
Unit Testing and TDD 2017
Xavi Hidalgo
 
PDF
Testing practicies not only in scala
Paweł Panasewicz
 
PDF
Test Driven iOS Development (TDD)
Babul Mirdha
 
PDF
Testing: the more you do it, the more you'll like it
Jeffrey McGuire
 
PPTX
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
PDF
Test driven development
lukaszkujawa
 
PPTX
Unit tests & TDD
Dror Helper
 
PPTX
Tdd is not about testing (C++ version)
Gianluca Padovani
 
PPTX
Test Driven Development
bhochhi
 
Test-Driven Development In Action
Jon Kruger
 
How to complement TDD with static analysis
PVS-Studio
 
TDD Workshop UTN 2012
Facundo Farias
 
Test Driven Development (TDD) with FlexUnit 4 - 360|Flex San Jose preso
Elad Elrom
 
TDD Best Practices
Attila Bertók
 
Writing Tests with the Unity Test Framework
Peter Kofler
 
Test Driven Development Introduction
Nguyen Hai
 
PresentationqwertyuiopasdfghUnittest.pdf
kndemo34
 
Test Driven Development
pmanvi
 
Test Driven Development
Kumaresh Chandra Baruri
 
Unit Testing and TDD 2017
Xavi Hidalgo
 
Testing practicies not only in scala
Paweł Panasewicz
 
Test Driven iOS Development (TDD)
Babul Mirdha
 
Testing: the more you do it, the more you'll like it
Jeffrey McGuire
 
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
Test driven development
lukaszkujawa
 
Unit tests & TDD
Dror Helper
 
Tdd is not about testing (C++ version)
Gianluca Padovani
 
Test Driven Development
bhochhi
 
Ad

Recently uploaded (20)

PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
smart lot access control system with eye
rasabzahra
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PDF
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
DOCX
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPTX
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
smart lot access control system with eye
rasabzahra
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
AI TECHNIQUES FOR IDENTIFYING ALTERATIONS IN THE HUMAN GUT MICROBIOME IN MULT...
vidyalalltv1
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 

Python and test

  • 1. TDD in Python Shuhsi Lin 2017/6/16
  • 2. Aganda More info on how to use this template at www.slidescarnival.com/help-use-presentation-template Testing ○ ○ ○ ○ Unit Test ○ ○ ○ ○ TDD ○ ○
  • 5. Why Software Testing 1. Deliver the best application we can. 2. Lots of different devices, browsers, and operating systems 3. User really will do that – no matter how silly it seems. 4. One person to hundreds of people, even more, are using it. 5. To ensure that what we create does what it’s supposed to do. http://www.te52.com/testtalk/2014/08/07/5-reasons-we-need-software-testing/ Precision and Accuracy, Validation, Reliability, and Quality Delivery of high quality product or software application to customers
  • 6. Test Principles Principles are just for reference. I will not use them in practise. http://istqbexamcertification.com/what-are-the-principles-of-testing/ http://www.guru99.com/software-testing-seven-principles.html
  • 7. Testing methods and Types ○ ○ ○
  • 8. Testing levels Unit testing Integration testing System testing Operational acceptance testing Developers White box Testers (QA, users) Black box
  • 11. Write test program to test 1. Instant Feedback ◦ ( Time (testing) << Time(debugging) ) 2. Regression Testing and Refactoring 3. API design 4. (Unit) test is Document
  • 13. What Is Unit test? ● Smallest testable part of an application like functions, classes, procedures, interfaces. ● Breaking your program into pieces, and subjecting each piece to a series of tests ● should be done by the developers. http://istqbexamcertification.com/what-is-unit-testing/ Unit test is good, because ● Issues are found at early stage ● Unit testing helps in maintaining and changing the code ● Reducing the cost of bug fixes. ● Simplifying the debugging process
  • 14. Assert Telling the program to test that condition, and trigger an error if the condition is false. if not condition: raise AssertionError() >>> assert True >>> assert False Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError Assert = https://docs.python.org/3/reference/simple_stmts.html#assert
  • 15. class Calculator: def mod(self, dividend, divisor): remainder = dividend % divisor quotient = (dividend - remainder) / divisor return quotient, remainder if __name__ == '__main__': cal = Calculator() assert cal.mod(5, 3) == (1, 2) # 5 / 3 = 1 ... 2 assert cal.mod(8, 4) == (1, 0) # 8 / 4 = 2 ... 0 Assert example https://imsardine.wordpress.com/tech/unit-testing-in-python/ Traceback (most recent call last): File "/Users/shuhsi/github/TDD-kata/test_calc.py", line 11, in <module> assert cal.mod(8, 4) == (1, 0) # 8 / 4 = 2 ... 0 AssertionError
  • 16. https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks xUnit Framework ● Architecture for unit testing frameworks that are code-driven ● By Kent Beck ● Prescribes testing the fundamental units of software –examples: functions, methods, classes ● Distinguishes between failures and errors in a unit of software Each Test case has four-phase: ● Setup ● Exercise ● Verify (assertion) ● Teardown (cleanup)
  • 18. Python Example https://docs.python.org/3/library/unittest.html import unittest class 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 string with self.assertRaises (TypeError) : s. split(2) if __name__ == '__main__': unittest. main()
  • 19. import unittest class Calculator: def mod(self, dividend, divisor): remainder = dividend % divisor quotient = (dividend - remainder) / divisor return quotient, remainder class CalculatorTest (unittest.TestCase): def test_mod_with_remainder (self): cal = Calculator() self.assertEqual (cal.mod(5, 3), (1, 2)) def test_mod_without_remainder (self): cal = Calculator() self.assertEqual (cal.mod(8, 4), (1, 0)) def test_mod_divide_by_zero (self): cal = Calculator() assertRaises (ZeroDivisionError, cal.mod, 7, 1) if __name__ == '__main__': unittest. main() Subclass of unittest Prefix: test assertEqual Import unitest Run all test cases Raise error
  • 20. ====================================================================== ERROR: test_mod_divide_by_zero (__main__.CalculatorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/shuhsi/github/TDD-kata/test_calc.py", line 22, in test_mod_divide_by_zero assertRaises(ZeroDivisionError, cal.mod, 7, 1) NameError: global name 'assertRaises' is not defined ====================================================================== FAIL: test_mod_without_remainder (__main__.CalculatorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/shuhsi/github/TDD-kata/test_calc.py", line 18, in test_mod_without_remainder self.assertEqual(cal.mod(8, 4), (1, 0)) AssertionError: Tuples differ: (2, 0) != (1, 0) First differing element 0: 2 1 - (2, 0) ? ^ + (1, 0) ? ^ ---------------------------------------------------------------------- Ran 3 tests in 0.009s FAILED (failures=1, errors=1) Show difference error
  • 21. TDD
  • 22. What Is TDD? ● Test-driven development ● A methodology of Implementing Software that relies on the repetition of a very short development cycle TDD is not ● a developing Tool ● a silver bullet for problems! ● the ONLY way to write good software! ○ But, if followed, will help you write solid software!
  • 23. TDD cycles http://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html 1. Create a unit tests that fails 2. Write production code that makes that test pass 3. Clean up the mess you just made
  • 25. "Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz” FizzBuzz Problem http://codingdojo.org/kata/FizzBuzz/ Sample output
  • 26. import unittest class TestFizzBuzz(unittest.TestCase): def test_0_raise_value_error (self): with self.assertRaises(ValueError): FizzBuzz(0) Write a test (will fail) Not exist yet fizzbuzz_test.py
  • 27. import unittest from fizzbuzz import FizzBuzz class TestFizzBuzz(unittest.TestCase): def test_0_raise_value_error (self): with self.assertRaises(ValueError): FizzBuzz(0) Write a production code (will pass a test) class FizzBuzz(object): pass
  • 28. class FizzBuzz(object): pass Refactor class FizzBuzz(object): def __init__(self, number): raise ValueError()
  • 29. import unittest from fizzbuzz import FizzBuzz class TestFizzBuzz(unittest.TestCase): def test_0_raise_value_error (self): with self.assertRaises(ValueError): FizzBuzz(0) def test_1_does_mot -raise_value_error (self): assert FizzBuzz(1).number == 1 (iteration 2) Write a test (will fail)
  • 30. (iteration 2)Write a production code (will pass a test) class FizzBuzz(object): def __init__(self, number): if number == 0: raise ValueError() self.number =1
  • 32. What TDD can help you? https://www.madetech.com/blog/9-benefits-of-test-driven-development 1. Acceptance Criteria 2. Focus 3. Interfaces 4. Tidier Code 5. Dependencies 6. Safer Refactoring 7. Fewer Bugs 8. Increasing Returns 9. Living Documentation
  • 33. Testing/coding is so hard!! How to do it? https://www.youtube.com/watch?v=KijjEG_DQ34
  • 34. Code Kata and Dojo http://blog.agilepartner.net/code-kata-improve-your-coding-skills/
  • 36. More about testing and xDD ○ ○ ○ ○ ○
  • 37. FURTHER READING: Uncle Bob Martin ◦ Clean code ◦ http://blog.8thlight.com/uncle-bob/archive.html Kent Beck ◦ Extreme Programming Explained ◦ Test Driven Development: By Example Is TDD Dead? Test-Driven Development with Python Essential TDD (Test-Driven Development) for Pythoners, Pycontw 2016 RSpec & TDD Tutorial by ihower