SlideShare a Scribd company logo
Writing Unit Test from
Scratch
Using Pytest
Wen-Shih Chao a.k.a Yen3
Overview
● What is unit test
● PyUnit (unittest) and pytest
● Pytest basic usage
● Some useful pytest usage and plugin
● How to start writing your own unit test ?
The talk would uncover
● Mock (because I still learn how to use it XD)
● Test-Driven Development
● Integration Test
● How to become a test master XD
What it unit test ?
● A unit test is a program to test your target program
● A program is possible to have wrong behaviour and so does unit test.
DEFINITION: A unit test is a piece of a code (usually a method) that
invokes another piece of code and checks the correctness of some
assumptions after- ward. If the assumptions turn out to be wrong, the unit
test has failed. A unit is a method or function.
Example
Real World
Example
Real World
Example
Real World
Example
Prepare
Run
Check
(Assert)
Unittest library
● Unittest (PyUnit) - python standard library
○ xUnit style
○ No need to install
○ Mock support (python version >= 3.3)
● Pytest
○ Need to install
○ Pythonic style
○ Mock support (through plugin)
Why pytest ?
● You can write `assert XXX == YYY` rather than `self.assertZZZ(XXX, YYY)`
○ For example, if you want to compare two dictionaries x and y are equal.
■ PyUnit: `self.assertDictEqual(x, y)`
■ Pytest: `assert x == y`
● You can write fixture (pytest term) to replace `setUp()` and `tearDown()`
function. A test case could use multiple fixtures.
● Use function notation `@` to mark attribute of each test case.
● You can define manual command line option to control the test flow.
● Some useful plugins can reduce the pain to write unit tests. You can also
write/maintain plugins for your requirement.
xUnit
style
test
case
Pytest
style
test
case
Pytest basic
1. Write the test function
2. Run `pytest`
3. Check the result
Pytest folder structure
● A test folder contains
○ `__init__.py`: Please write pytest as a python module
○ `conftest.py` (optional): config and settings for the pytest module (Only valid in pytest)
○ `test_xxx.py`: Test cases
● You can make submodule for tests.
○ The submodule can use upper modules config
Real
world
example
Pytest - Fixture
● The fixture provides resources which test cases need.
● 2 types fixture
○ A normal fixture - Just return
○ A yield fixture - Declare a resource and free it after finished
● The fixture concept is like context manager
● A test case can use multiple fixtures.
● A fixture can rely on other fixture
Pytest fixture
● Normal fixture
Other fixture
Pytest fixture
● Yield fixture
Pytest - monkeypatch
● A simple approach for mock
● You can replace any method to your method
Example
● `check_worker_alive` would call `ping_worker` to get the ping result. For avoiding to access
the real internet, the test fakes a function that always return true value to test the main
function part of `check_worker_alive`
Pytest - mark
● Mark is like a tag. Before starting the test, you can check the mark to do
what you want to do.
Mark example
● In the example, when you mark some test as slow `@pytest.makr.slow` and you run pytest
without `--slow` option (e.g. `pytest`). The pytest would ignore the test
Pytest - parametrize test
● Parameterize the argument
Pytest plugin
● pytest-tornado/pytest-tornado-yen3: The plugin lets you to test coroutine
function as native function and provides some useful fixture.
● pytest-mock: wrapper for unittest.mock
● pytest-cov: Generate test coverage report
● pytest-pep8: Generate pep8 style checking report
● pytest-selenium: I have no experience about the plugin, maybe sw2 needs
it
Pytest-tornado/Pytest-tornado-yen3
● Pytest-tornado provides some marks to run your test as a coroutine
○ It would start a new ioloop and use `IOLoop.run_sync` to run each test case
● The last update of pytest-tornado is 2 years ago. I have some needs and
change for the plugin so I maintain a patched version for my project. You
can get more details from https://github.com/yen3/pytest-tornado
Pytest-cov
● Generate coverage
● Usage is simple `pytest --cov=<module_name>`. You can use `--cov`
multiple time
Coverage
Example
docker-compose -f docker-compose-test.yml exec test-server sh -c "cd /app && pytest
--cov=common --cov=api_server --cov=worker --slow"
Coverage
example
docker-compose -f docker-compose-test.yml exec test-server sh -c 
"cp -r /app/* /app_cov && cd /app_cov && pytest -sv --cov-report=html --cov=common
--cov=api_server --cov=worker --slow --pep8 | tee htmlcov/test.log"
Should I write unit test for my program ?
● The answer is probably. In actually, some program is hard to test.
● If your program is easy to test, you should try to write some tests for it.
● Writing unit test would cost your extra time. If you have plan to write unit
test, remember to request more develop time to your manager.
● Unit test is also a program. It’s possible to go wrong.
● Unit test can not find all bugs. But it can find many bugs if you write
tests well.
Should I write unit test for my program ?
● How to write unit tests for existing program ?
○ It’s up-on your situation. If the time schedule of the project/program has no enough time,
maybe you have to quit the idea.
○ If you have enough time, there are several possible ways.
■ Start from easy function (e.g. utility functions). You can feel how to write unit tests.
■ Start from function that are easy to be buggy. It’s usually hard to test. If you can
finish, maybe you can get rid of the buggy function (for a while)
■ Start from the interface.
● I take the policy for middleware-network. The policy is like to write integration
tests. It can make sure your program works after each modification.
My experience about unit test
● If you are a front-end developer, I am sorry that I have no experience
about it.
● If you are a back-end developer and use python, you could write test with
pytest.
● Consider writing unit test to replace testing function/module manually
● Run test in docker container is very important. It can avoid reset the
testing environment every time.
● Take the advantage of fixture to initial/release resource for test cases
My experience about unit test
● The textbook says writing unit test is easy. In fact, a lot of problems need
to be resolve.
○ It costs lots of effort to maintain a good unit test.
○ Resource problems
■ Interactive/Isolate with real world environment like database, file system … etc
■ Resource initialize and restore
● I also write tests for third-party packages (e.g. tornadis, sqlalchemy … etc)
○ learn how to use these packages and avoid the unexpected behaviour when it updates.
○ The type of test is also called learning test.
My experience about unit test
● Prepare test environment. The test environment must isolate the
production environment. The straightforward way is to use docker to
achieve the effect.
● If you have multiple service need to start, you can
○ Use docker-compose to start several containers
○ User docker with supervisor to start several services in a container
○ Mock all services
○ … etc. It’s upon your requirement and situation
Questions ?
Reference
● Software test concept
a. Software Testing - https://en.wikipedia.org/wiki/Software_testing#The_box_approach
b. The Art of unit testing with C# 2nd edition, ISBN: 9781617290893 (中譯: 單元測試的藝術 2/e,
ISBN: 9789864342471)
● Pytest
a. Pytest - https://docs.pytest.org/en/latest/
b. Pytest 還有他的快樂夥伴 - https://www.slideshare.net/excusemejoe/pytest-and-friends
c. Python Testing with pytest, ISBN: 9781680502404
● Practical test experience sharing
a. Clean code, ISBN: 9780132350884 (中譯: 無瑕的程式碼, ISBN: 9789862017050)
b. Code Complete 2/e, ISBN: 9780735619678

More Related Content

What's hot

NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features Presentation
Shir Brass
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
Anatoliy Okhotnikov
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
dn
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
Amila Paranawithana
 
Unit testing (eng)
Unit testing (eng)Unit testing (eng)
Unit testing (eng)
Anatoliy Okhotnikov
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
Lars Thorup
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
Eugenio Lentini
 
05 junit
05 junit05 junit
05 junit
mha4
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
Valerio Maggio
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unitOlga Extone
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentals
cbcunc
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
Ravikiran J
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockitoMathieu Carbou
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Pokpitch Patcharadamrongkul
 
Introduction to unit testing in python
Introduction to unit testing in pythonIntroduction to unit testing in python
Introduction to unit testing in python
Anirudh
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
Kiki Ahmadi
 
J Unit
J UnitJ Unit
Junit
JunitJunit

What's hot (20)

NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features Presentation
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
 
Nunit
NunitNunit
Nunit
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Unit testing (eng)
Unit testing (eng)Unit testing (eng)
Unit testing (eng)
 
Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++Automated Testing for Embedded Software in C or C++
Automated Testing for Embedded Software in C or C++
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
05 junit
05 junit05 junit
05 junit
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unit
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentals
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Introduction to unit testing in python
Introduction to unit testing in pythonIntroduction to unit testing in python
Introduction to unit testing in python
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
J Unit
J UnitJ Unit
J Unit
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Junit
JunitJunit
Junit
 

Similar to Write unit test from scratch

Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8
Sam Becker
 
Project Onion unit test environment
Project Onion unit test environmentProject Onion unit test environment
Project Onion unit test environment
Abhinav Jha
 
Unit testing in Unity
Unit testing in UnityUnit testing in Unity
Unit testing in Unity
Mikko McMenamin
 
Automation for developers
Automation for developersAutomation for developers
Automation for developers
Dharshana Kasun Warusavitharana
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test Framework
Peter Kofler
 
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
 
Test automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsTest automation principles, terminologies and implementations
Test automation principles, terminologies and implementations
Steven Li
 
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...Odoo
 
Pytest - testing tips and useful plugins
Pytest - testing tips and useful pluginsPytest - testing tips and useful plugins
Pytest - testing tips and useful plugins
Andreu Vallbona Plazas
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
David P. Moore
 
May 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflowMay 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflow
Adam Doyle
 
Test Automation
Test AutomationTest Automation
Test Automation
Rodrigo Paiva
 
DIY in 5 Minutes: Testing Django App with Pytest
DIY in 5 Minutes: Testing Django App with Pytest DIY in 5 Minutes: Testing Django App with Pytest
DIY in 5 Minutes: Testing Django App with Pytest
Inexture Solutions
 
TDD done right - tests immutable to refactor
TDD done right - tests immutable to refactorTDD done right - tests immutable to refactor
TDD done right - tests immutable to refactor
Grzegorz Miejski
 
Testing Django APIs
Testing Django APIsTesting Django APIs
Testing Django APIs
tyomo4ka
 
HKG18-TR12 - LAVA for LITE Platforms and Tests
HKG18-TR12 - LAVA for LITE Platforms and TestsHKG18-TR12 - LAVA for LITE Platforms and Tests
HKG18-TR12 - LAVA for LITE Platforms and Tests
Linaro
 
Software Testing
Software TestingSoftware Testing
Software Testing
AdroitLogic
 

Similar to Write unit test from scratch (20)

Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8
 
Pyunit
PyunitPyunit
Pyunit
 
Project Onion unit test environment
Project Onion unit test environmentProject Onion unit test environment
Project Onion unit test environment
 
Unit testing in Unity
Unit testing in UnityUnit testing in Unity
Unit testing in Unity
 
Automation for developers
Automation for developersAutomation for developers
Automation for developers
 
UPC Plone Testing Talk
UPC Plone Testing TalkUPC Plone Testing Talk
UPC Plone Testing Talk
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test Framework
 
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
 
Test automation principles, terminologies and implementations
Test automation principles, terminologies and implementationsTest automation principles, terminologies and implementations
Test automation principles, terminologies and implementations
 
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
Why and how to develop OpenERP test scenarios (in python and using OERPScenar...
 
Pytest - testing tips and useful plugins
Pytest - testing tips and useful pluginsPytest - testing tips and useful plugins
Pytest - testing tips and useful plugins
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
May 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflowMay 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflow
 
Test Automation
Test AutomationTest Automation
Test Automation
 
DIY in 5 Minutes: Testing Django App with Pytest
DIY in 5 Minutes: Testing Django App with Pytest DIY in 5 Minutes: Testing Django App with Pytest
DIY in 5 Minutes: Testing Django App with Pytest
 
TDD done right - tests immutable to refactor
TDD done right - tests immutable to refactorTDD done right - tests immutable to refactor
TDD done right - tests immutable to refactor
 
Testing Django APIs
Testing Django APIsTesting Django APIs
Testing Django APIs
 
Quality for developers
Quality for developersQuality for developers
Quality for developers
 
HKG18-TR12 - LAVA for LITE Platforms and Tests
HKG18-TR12 - LAVA for LITE Platforms and TestsHKG18-TR12 - LAVA for LITE Platforms and Tests
HKG18-TR12 - LAVA for LITE Platforms and Tests
 
Software Testing
Software TestingSoftware Testing
Software Testing
 

More from Wen-Shih Chao

Programming with effects - Graham Hutton
Programming with effects - Graham HuttonProgramming with effects - Graham Hutton
Programming with effects - Graham Hutton
Wen-Shih Chao
 
近未來三人女子電音偶像團體 Perfume
近未來三人女子電音偶像團體 Perfume近未來三人女子電音偶像團體 Perfume
近未來三人女子電音偶像團體 PerfumeWen-Shih Chao
 
Matrix Chain Scheduling Algorithm
Matrix Chain Scheduling AlgorithmMatrix Chain Scheduling Algorithm
Matrix Chain Scheduling Algorithm
Wen-Shih Chao
 
Java Technicalities
Java TechnicalitiesJava Technicalities
Java Technicalities
Wen-Shih Chao
 
漫談 Source Control Management
漫談 Source Control Management漫談 Source Control Management
漫談 Source Control Management
Wen-Shih Chao
 
淺談排版系統 Typesetting System
淺談排版系統 Typesetting System淺談排版系統 Typesetting System
淺談排版系統 Typesetting System
Wen-Shih Chao
 

More from Wen-Shih Chao (6)

Programming with effects - Graham Hutton
Programming with effects - Graham HuttonProgramming with effects - Graham Hutton
Programming with effects - Graham Hutton
 
近未來三人女子電音偶像團體 Perfume
近未來三人女子電音偶像團體 Perfume近未來三人女子電音偶像團體 Perfume
近未來三人女子電音偶像團體 Perfume
 
Matrix Chain Scheduling Algorithm
Matrix Chain Scheduling AlgorithmMatrix Chain Scheduling Algorithm
Matrix Chain Scheduling Algorithm
 
Java Technicalities
Java TechnicalitiesJava Technicalities
Java Technicalities
 
漫談 Source Control Management
漫談 Source Control Management漫談 Source Control Management
漫談 Source Control Management
 
淺談排版系統 Typesetting System
淺談排版系統 Typesetting System淺談排版系統 Typesetting System
淺談排版系統 Typesetting System
 

Recently uploaded

一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 

Recently uploaded (20)

一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 

Write unit test from scratch

  • 1. Writing Unit Test from Scratch Using Pytest Wen-Shih Chao a.k.a Yen3
  • 2. Overview ● What is unit test ● PyUnit (unittest) and pytest ● Pytest basic usage ● Some useful pytest usage and plugin ● How to start writing your own unit test ?
  • 3. The talk would uncover ● Mock (because I still learn how to use it XD) ● Test-Driven Development ● Integration Test ● How to become a test master XD
  • 4. What it unit test ? ● A unit test is a program to test your target program ● A program is possible to have wrong behaviour and so does unit test. DEFINITION: A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions after- ward. If the assumptions turn out to be wrong, the unit test has failed. A unit is a method or function.
  • 9. Unittest library ● Unittest (PyUnit) - python standard library ○ xUnit style ○ No need to install ○ Mock support (python version >= 3.3) ● Pytest ○ Need to install ○ Pythonic style ○ Mock support (through plugin)
  • 10. Why pytest ? ● You can write `assert XXX == YYY` rather than `self.assertZZZ(XXX, YYY)` ○ For example, if you want to compare two dictionaries x and y are equal. ■ PyUnit: `self.assertDictEqual(x, y)` ■ Pytest: `assert x == y` ● You can write fixture (pytest term) to replace `setUp()` and `tearDown()` function. A test case could use multiple fixtures. ● Use function notation `@` to mark attribute of each test case. ● You can define manual command line option to control the test flow. ● Some useful plugins can reduce the pain to write unit tests. You can also write/maintain plugins for your requirement.
  • 13. Pytest basic 1. Write the test function 2. Run `pytest` 3. Check the result
  • 14. Pytest folder structure ● A test folder contains ○ `__init__.py`: Please write pytest as a python module ○ `conftest.py` (optional): config and settings for the pytest module (Only valid in pytest) ○ `test_xxx.py`: Test cases ● You can make submodule for tests. ○ The submodule can use upper modules config
  • 16. Pytest - Fixture ● The fixture provides resources which test cases need. ● 2 types fixture ○ A normal fixture - Just return ○ A yield fixture - Declare a resource and free it after finished ● The fixture concept is like context manager ● A test case can use multiple fixtures. ● A fixture can rely on other fixture
  • 17. Pytest fixture ● Normal fixture Other fixture
  • 19. Pytest - monkeypatch ● A simple approach for mock ● You can replace any method to your method
  • 20. Example ● `check_worker_alive` would call `ping_worker` to get the ping result. For avoiding to access the real internet, the test fakes a function that always return true value to test the main function part of `check_worker_alive`
  • 21. Pytest - mark ● Mark is like a tag. Before starting the test, you can check the mark to do what you want to do.
  • 22. Mark example ● In the example, when you mark some test as slow `@pytest.makr.slow` and you run pytest without `--slow` option (e.g. `pytest`). The pytest would ignore the test
  • 23. Pytest - parametrize test ● Parameterize the argument
  • 24. Pytest plugin ● pytest-tornado/pytest-tornado-yen3: The plugin lets you to test coroutine function as native function and provides some useful fixture. ● pytest-mock: wrapper for unittest.mock ● pytest-cov: Generate test coverage report ● pytest-pep8: Generate pep8 style checking report ● pytest-selenium: I have no experience about the plugin, maybe sw2 needs it
  • 25. Pytest-tornado/Pytest-tornado-yen3 ● Pytest-tornado provides some marks to run your test as a coroutine ○ It would start a new ioloop and use `IOLoop.run_sync` to run each test case ● The last update of pytest-tornado is 2 years ago. I have some needs and change for the plugin so I maintain a patched version for my project. You can get more details from https://github.com/yen3/pytest-tornado
  • 26. Pytest-cov ● Generate coverage ● Usage is simple `pytest --cov=<module_name>`. You can use `--cov` multiple time
  • 27. Coverage Example docker-compose -f docker-compose-test.yml exec test-server sh -c "cd /app && pytest --cov=common --cov=api_server --cov=worker --slow"
  • 28. Coverage example docker-compose -f docker-compose-test.yml exec test-server sh -c "cp -r /app/* /app_cov && cd /app_cov && pytest -sv --cov-report=html --cov=common --cov=api_server --cov=worker --slow --pep8 | tee htmlcov/test.log"
  • 29. Should I write unit test for my program ? ● The answer is probably. In actually, some program is hard to test. ● If your program is easy to test, you should try to write some tests for it. ● Writing unit test would cost your extra time. If you have plan to write unit test, remember to request more develop time to your manager. ● Unit test is also a program. It’s possible to go wrong. ● Unit test can not find all bugs. But it can find many bugs if you write tests well.
  • 30. Should I write unit test for my program ? ● How to write unit tests for existing program ? ○ It’s up-on your situation. If the time schedule of the project/program has no enough time, maybe you have to quit the idea. ○ If you have enough time, there are several possible ways. ■ Start from easy function (e.g. utility functions). You can feel how to write unit tests. ■ Start from function that are easy to be buggy. It’s usually hard to test. If you can finish, maybe you can get rid of the buggy function (for a while) ■ Start from the interface. ● I take the policy for middleware-network. The policy is like to write integration tests. It can make sure your program works after each modification.
  • 31. My experience about unit test ● If you are a front-end developer, I am sorry that I have no experience about it. ● If you are a back-end developer and use python, you could write test with pytest. ● Consider writing unit test to replace testing function/module manually ● Run test in docker container is very important. It can avoid reset the testing environment every time. ● Take the advantage of fixture to initial/release resource for test cases
  • 32. My experience about unit test ● The textbook says writing unit test is easy. In fact, a lot of problems need to be resolve. ○ It costs lots of effort to maintain a good unit test. ○ Resource problems ■ Interactive/Isolate with real world environment like database, file system … etc ■ Resource initialize and restore ● I also write tests for third-party packages (e.g. tornadis, sqlalchemy … etc) ○ learn how to use these packages and avoid the unexpected behaviour when it updates. ○ The type of test is also called learning test.
  • 33. My experience about unit test ● Prepare test environment. The test environment must isolate the production environment. The straightforward way is to use docker to achieve the effect. ● If you have multiple service need to start, you can ○ Use docker-compose to start several containers ○ User docker with supervisor to start several services in a container ○ Mock all services ○ … etc. It’s upon your requirement and situation
  • 35. Reference ● Software test concept a. Software Testing - https://en.wikipedia.org/wiki/Software_testing#The_box_approach b. The Art of unit testing with C# 2nd edition, ISBN: 9781617290893 (中譯: 單元測試的藝術 2/e, ISBN: 9789864342471) ● Pytest a. Pytest - https://docs.pytest.org/en/latest/ b. Pytest 還有他的快樂夥伴 - https://www.slideshare.net/excusemejoe/pytest-and-friends c. Python Testing with pytest, ISBN: 9781680502404 ● Practical test experience sharing a. Clean code, ISBN: 9780132350884 (中譯: 無瑕的程式碼, ISBN: 9789862017050) b. Code Complete 2/e, ISBN: 9780735619678