SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
py.test

git clone https://github.com/soasme/pytest_tutorial
• Basic: example / usage	

• Fixture: mechanism / builtin	

• Plugin: conftest / plugin / hook / 3-party	

• Scale
Basic
Getting start!
#	
  content	
  of	
  test_sample.py	
  
def	
  func(x):	
  
	
  	
  	
  	
  return	
  x	
  +	
  1	
  
!

def	
  test_answer():	
  
	
  	
  	
  	
  assert	
  func(3)	
  ==	
  5	
  
#	
  content	
  of	
  test_sysexit.py	
  
import	
  pytest	
  
def	
  f():	
  
	
  	
  	
  	
  raise	
  SystemExit(1)	
  
!

def	
  test_mytest():	
  
	
  	
  	
  	
  with	
  pytest.raises(SystemExit):	
  
	
  	
  	
  	
  	
  	
  	
  	
  f()	
  
class	
  TestClass:	
  
	
  	
  	
  	
  def	
  test_one(self):	
  
	
  	
  	
  	
  	
  	
  	
  	
  x	
  =	
  "this"	
  
	
  	
  	
  	
  	
  	
  	
  	
  assert	
  'h'	
  in	
  x	
  
!

	
  	
  	
  	
  def	
  test_two(self):	
  
	
  	
  	
  	
  	
  	
  	
  	
  x	
  =	
  "hello"	
  
	
  	
  	
  	
  	
  	
  	
  	
  assert	
  hasattr(x,	
  'check')	
  
How to run cases?
• py.test tests/test_mod.py	

• py.test tests/	

• py.test -k match # def test_match():
How to run cases?
• py.test --showlocals # trace context	

• py.test -x # stop on first failure case	

• py.test --maxfail=2 # on the second	

• py.test -s # enable `print` output	

• py.test --durations=10 # list top10 slowest
cases
How to run cases?
• py.test --tb=long # default traceback	

• py.test --tb=line # oneline	

• py.test --tb=short	

• py.test --tb=native # Python default traceback
/tmp % py.test test_a.py --tb=line --pdb	

>>>> traceback >>>>	

E assert 1 != 1	

>>>>> entering PDB >>>>	

> /private/tmp/test_a.py(10)test_one()	

-> assert num != 1	

(Pdb) num	

1	

(Pdb) exit
How to run cases?
import	
  pytest	
  
def	
  test_function():	
  
	
  	
  	
  	
  ...	
  
	
  	
  	
  	
  pytest.set_trace()	
  
py.test -h
What to test?
• folder, file.	

• recursive	

• test_xxx.py, xxx_test.py	

• TestClass (without __init__ method)	

• all the function or method with prefix `test_`
What to test?
#	
  setup.cfg	
  /	
  tox.ini	
  /	
  pytest.ini	
  
[pytest]	
  
python_files=check_*.py	
  
python_classes=Check	
  
python_functions=check	
  
What to test?
#	
  content	
  of	
  check_myapp.py	
  
class	
  CheckMyApp:	
  
	
  	
  	
  	
  def	
  check_simple(self):	
  
	
  	
  	
  	
  	
  	
  	
  	
  pass	
  
	
  	
  	
  	
  def	
  check_complex(self):	
  
	
  	
  	
  	
  	
  	
  	
  	
  pass	
  
Basic configuration
INI-style

• pytest.ini	

• tox.ini	

• setup.cfg
Basic configuration
Path

• Current dir	

• Parent dir	

• ...
Basic configuration
#	
  content	
  of	
  pytest.ini	
  
#	
  (or	
  tox.ini	
  or	
  setup.cfg)	
  
[pytest]	
  
addopts	
  =	
  -­‐-­‐tb=short	
  -­‐x

py.test test_module.py -k test_func
Assertions
• assert expr	

• assert a == b	

• self.assertEqual(a, b)	

• assert expr, “Expected message”	

• pytest.raises
Assertions
• Why `assert`?	

• simple	

• nice output	

• http://pytest.org/latest/example/
reportingdemo.html
Assertions
Define Own Comparison
#	
  content	
  of	
  conftest.py	
  
def	
  pytest_assertrepr_compare(op,	
  left,	
  right):	
  
	
  	
  	
  	
  if	
  (isinstance(left,	
  Foo)	
  
and	
  isinstance(right,	
  Foo)	
  
and	
  op	
  ==	
  "=="):	
  
	
  	
  	
  	
  	
  return	
  ['Comparing	
  Foo	
  instances:',	
  
	
  'vals:	
  {0.val}	
  !=	
  {1.val}'.format(left,	
  right)]	
  

Lesson 4
Assertions
Define Own Comparison
def	
  test_compare():	
  
	
  	
  	
  	
  assert	
  Foo(1)	
  ==	
  Foo(2)

>	
  	
  	
  	
  	
  	
  	
  assert	
  f1	
  ==	
  f2	
  
E	
  	
  	
  	
  	
  	
  	
  assert	
  Comparing	
  Foo	
  instances:	
  
E	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  vals:	
  1	
  !=	
  2	
  
Assertions
• Py.test refined `assert` statement	

• Note: `assert expr, msg` won't output
traceback
Fixtures
• Better than setUp / tearDown:	

• Explicit name	

• Call only when needed	

• Scope: module, class, session, function	

• Cascade, fixture A => fixture B => ...	

• Scalability
Fixtures as func args
import	
  pytest	
  
!

@pytest.fixture	
  
def	
  bookmark(app):	
  
	
  	
  	
  	
  return	
  Bookmark.create(	
  
user_id=1,	
  
works_id=1)
Fixtures as func args
def	
  test_get_by_relation(bookmark):	
  
	
  	
  	
  	
  bookmarks	
  =	
  Bookmark.get(	
  
user_id=1,	
  
works_id=1	
  
)	
  
	
  	
  	
  	
  assert	
  bookmarks	
  
	
  	
  	
  	
  assert	
  bookmarks[0].id	
  ==	
  
bookmark.id
Lesson 01
Fixtures as func args
• Testcase only care about fixture, no import,
no setup, no teardown.	


• IoC
Fixtures - scope
@pytest.fixture(scope="module")	
  
def	
  smtp():	
  
	
  	
  	
  	
  return	
  smtplib.SMTP("dou.bz")
Fixtures - finalization
@pytest.fixture(scope="session")	
  
def	
  database(request):	
  
	
  	
  	
  	
  db_name	
  =	
  "{}.db".format(time())	
  
	
  	
  	
  	
  deferred_db.init(db_name)	
  
	
  	
  	
  	
  def	
  finalizer():	
  
	
  	
  	
  	
  	
  	
  	
  	
  if	
  os.path.exists(db_name):	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  os.remove(db_name)	
  
	
  	
  	
  	
  request.addfinalizer(finalizer)	
  
	
  	
  	
  	
  return	
  deferred_db	
  

Lesson 2
Fixtures - parametrizing
@pytest.fixture(params=[	
  
	
  	
  	
  	
  '/',	
  
	
  	
  	
  	
  '/reader/',	
  
])	
  
def	
  signed_page(request):	
  
	
  	
  	
  	
  return	
  requests.get(request.param)	
  
!

def	
  test_fetch_pages_success_in_signed(signed_page):	
  
	
  	
  	
  	
  assert	
  signed_page.status_code	
  <	
  300

Lesson 3.1
Fixtures - modular
class	
  App(object):	
  
!

	
  	
  	
  	
  def	
  __init__(self,	
  request):	
  
	
  	
  	
  	
  	
  	
  	
  	
  self.request	
  =	
  request	
  
!

@pytest.fixture	
  
def	
  app(request,	
  
	
  	
  	
  	
  	
  	
  	
  	
  mc_logger,	
  
	
  	
  	
  	
  	
  	
  	
  	
  db_logger	
  
	
  	
  	
  	
  	
  	
  	
  	
  ):	
  
	
  	
  	
  	
  return	
  App(request)	
  
Fixtures - autouse
class	
  TestClass:	
  
	
  	
  	
  	
  @pytest.fixture(autouse=True)	
  
	
  	
  	
  	
  def	
  table(self,	
  database):	
  
	
  	
  	
  	
  	
  	
  	
  	
  Table.create_table()	
  
!

	
  	
  	
  	
  def	
  test_select(self):	
  
	
  	
  	
  	
  	
  	
  	
  	
  assert	
  not	
  Table.get(id=1)
Fixtures - autouse
@pytest.fixture	
  
def	
  table(request,	
  database):	
  
	
  	
  	
  	
  Table.create_table()	
  
	
  	
  	
  	
  request.addfinilizer(	
  
Table.drop_table)	
  
!

@pytest.mark.usefixtures('table')	
  
class	
  TestClass:	
  
	
  	
  	
  	
  def	
  test_select(self):	
  
	
  	
  	
  	
  	
  	
  	
  	
  assert	
  not	
  Table.get(id=1)
Fixtures - parametrizing
@pytest.mark.parametrize(	
  
	
  	
  	
  	
  "input,expected",	
  [	
  
	
  	
  	
  	
  ("3+5",	
  8),	
  
	
  	
  	
  	
  ("2+4",	
  6),	
  
	
  	
  	
  	
  ("6*9",	
  42),	
  
	
  	
  	
  	
  pytest.mark.xfail(("6*9",	
  42))	
  
])	
  
def	
  test_eval(input,	
  expected):	
  
	
  	
  	
  	
  assert	
  eval(input)	
  ==	
  expected
Lesson 3.2
Fixtures - parametrizing
#	
  conftest.py	
  
import	
  pytest	
  
!

def	
  pytest_generate_tests(metafunc):	
  
	
  	
  	
  	
  if	
  'payload'	
  in	
  metafunc.fixturenames:	
  
	
  	
  	
  	
  	
  	
  	
  	
  metafunc.parametrize('payload',	
  
	
   	
   	
   	
   	
   	
   	
   	
   	
   	
   	
   ['/tmp/test.json',	
  ])	
  
!

#	
  test	
  file	
  
def	
  test_meta(payload):	
  
	
  	
  	
  	
  assert	
  payload	
  ==	
  '/tmp/test.json'	
  
	
  	
  	
  	
  ...
Fixtures - xUnit
def	
  setup_function(function):	
  
	
  	
  	
  	
  print	
  'setup'	
  
def	
  teardown_function(function):	
  
	
  	
  	
  	
  print	
  'teardown'	
  
def	
  test_func():	
  
	
  	
  	
  	
  print	
  'func'	
  
!

#	
  ==>	
  
"""	
  
setup	
  
func	
  
teardown	
  
"""
Fixtures - xUnit
class	
  TestBookmark:	
  	
  
	
  	
  	
  def	
  setup_method(self,	
  method):	
  
	
  	
  	
  	
  	
  	
  	
  	
  print	
  'setup'	
  
	
  	
  	
  	
  def	
  teardown_method(self,	
  method):	
  
	
  	
  	
  	
  	
  	
  	
  	
  print	
  'teardown'	
  
	
  	
  	
  	
  def	
  test_method(self):	
  
	
  	
  	
  	
  	
  	
  	
  	
  print	
  'method'	
  
!

#	
  ==>	
  
"""	
  
setup	
  
method	
  
teardown	
  
"""
Fixtures - xUnit
• setup_module / teardown_module	

• setup_class / teardown_class	

• setup_method / teardown_method	

• setup_function / teardown_function
Fixtures - builtin
import	
  datetime	
  
import	
  pytest	
  
!
FAKE_TIME	
  =	
  datetime.datetime(2020,	
  12,	
  25,	
  17,	
  05,	
  55)	
  
!
@pytest.fixture	
  
def	
  patch_datetime_now(monkeypatch):	
  
!
	
  	
  	
  	
  class	
  mydatetime:	
  
	
  	
  	
  	
  	
  	
  	
  	
  @classmethod	
  
	
  	
  	
  	
  	
  	
  	
  	
  def	
  now(cls):	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  FAKE_TIME	
  
!
	
  	
  	
  	
  monkeypatch.setattr(datetime,	
  'datetime',	
  mydatetime)	
  
!
!
def	
  test_patch_datetime(patch_datetime_now):	
  
	
  	
  	
  	
  assert	
  datetime.datetime.now()	
  ==	
  FAKE_TIME
Fixtures - builtin
• monkeypatch	

• tmpdir	

• capsys / capfd	

• `py.test --fixture`
Maker
• pytest.marker	

• py.test --marker	

• marker is like tag.	

• @pytest.mark.skipif(getenv('qaci'))	

• @pytest.mark.xfail('oooops')	

• @pytest.mark.skipif("config.getvalue('pass')")	

• @pytest.mark.ask_sunyi	

!
unittest.TestCase
• Compatible	

• But be careful. There is no funcargs
mechanism for unittest cases.
Plugin
• py.test supply many hooks.	

• collection / configuration / run / output	

• Basic types:	

• builtin	

• 3-party plugins	

• conftest.py plugins
Plugin - find conftest.py
• recursive	

• `import conftest` X
Plugin - 3-party
• pip install pytest-xxxxx	

• pytest-random, pytest-cov	

• https://pypi.python.org/pypi?

%3Aaction=search&term=pytest&submit=s
earch
Plugin - load plugin
• py.test -p plugin_name	

• py.test -p no:plugin_name	

• pytest.ini	

• conftest.py `pytest_plugins`	

• pytest_plugins = "name1", "name2",	

• pytest_plugins = "suites.isolated_cases"
Plugin - hooks
• http://pytest.org/latest/plugins.html#hookspecification-and-validation	


• see source.
Plugin - example
#	
  content	
  of	
  suites.isolated_cases	
  
def	
  pytest_addoption(parser):	
  
	
  	
  	
  	
  group	
  =	
  parser.getgroup("isolated_cases",	
  "")	
  
	
  	
  	
  	
  group._addoption(	
  
	
  	
  	
  	
  	
  	
  	
  	
  '-­‐-­‐with-­‐data-­‐service',	
  
	
  	
  	
  	
  	
  	
  	
  	
  action="store_true",	
  
	
  	
  	
  	
  	
  	
  	
  	
  default=False,	
  
	
  	
  	
  	
  	
  	
  	
  	
  dest='with_data_service',	
  
	
  	
  	
  	
  	
  	
  	
  	
  help=(	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  "with	
  MySQL/beansdb/memcached	
  up	
  at	
  the	
  
beginning	
  of	
  session"	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  "and	
  down	
  at	
  the	
  end	
  of	
  session."	
  
	
  	
  	
  	
  	
  	
  	
  	
  )	
  
	
  	
  	
  	
  )
Plugin - example
#	
  content	
  of	
  isolated_cases	
  
def	
  pytest_configure(config):	
  
	
  	
  	
  	
  if	
  config.option.with_data_service:	
  
	
  	
  	
  	
  	
  	
  	
  	
  build_tables()	
  
	
  	
  	
  	
  	
  	
  	
  	
  stop_kvstore()	
  
	
  	
  	
  	
  	
  	
  	
  	
  sleep(1)	
  
	
  	
  	
  	
  	
  	
  	
  	
  start_kvstore()

$ py.test --with-data-service tests/
Plugin - example
#	
  content	
  of	
  tests/conftest.py	
  
pytest_plugins	
  =	
  "suites.isolated_cases"

$ py.test --with-data-service tests/
EOF

Contenu connexe

Tendances

Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해beom kyun choi
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented ProgrammingScott Wlaschin
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking frameworkPhat VU
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 

Tendances (20)

JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Junit
JunitJunit
Junit
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Selenium cheat sheet
Selenium cheat sheetSelenium cheat sheet
Selenium cheat sheet
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 

En vedette

TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With PytestEddy Reyes
 
Mocking in python
Mocking in pythonMocking in python
Mocking in pythonOoblioob
 
AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)Yuvaraja Ravi
 
Pytest: escreva menos, teste mais
Pytest: escreva menos, teste maisPytest: escreva menos, teste mais
Pytest: escreva menos, teste maisErick Wilder
 
Учим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTestУчим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTestRina Uzhevko
 
Amazon Aurora: The New Relational Database Engine from Amazon
Amazon Aurora: The New Relational Database Engine from AmazonAmazon Aurora: The New Relational Database Engine from Amazon
Amazon Aurora: The New Relational Database Engine from AmazonAmazon Web Services
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentalscbcunc
 
Deep Dive: Amazon Elastic MapReduce
Deep Dive: Amazon Elastic MapReduceDeep Dive: Amazon Elastic MapReduce
Deep Dive: Amazon Elastic MapReduceAmazon Web Services
 
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel AvivSelf Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel AvivAmazon Web Services
 
OAuth 2.0 refresher Talk
OAuth 2.0 refresher TalkOAuth 2.0 refresher Talk
OAuth 2.0 refresher Talkmarcwan
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland
 
Beyond Shuffling - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
Beyond Shuffling  - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...Beyond Shuffling  - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
Beyond Shuffling - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...Holden Karau
 
Нескучное тестирование с pytest
Нескучное тестирование с pytestНескучное тестирование с pytest
Нескучное тестирование с pytestRoman Imankulov
 
Architecting for Greater Security on AWS
Architecting for Greater Security on AWSArchitecting for Greater Security on AWS
Architecting for Greater Security on AWSAmazon Web Services
 
Mozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver frameworkMozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver frameworkdavehunt82
 
Masterless Puppet Using AWS S3 Buckets and IAM Roles
Masterless Puppet Using AWS S3 Buckets and IAM RolesMasterless Puppet Using AWS S3 Buckets and IAM Roles
Masterless Puppet Using AWS S3 Buckets and IAM RolesMalcolm Duncanson, CISSP
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Timo Stollenwerk
 

En vedette (20)

TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
Mocking in python
Mocking in pythonMocking in python
Mocking in python
 
AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)
 
Pytest: escreva menos, teste mais
Pytest: escreva menos, teste maisPytest: escreva menos, teste mais
Pytest: escreva menos, teste mais
 
Учим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTestУчим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTest
 
Amazon Aurora: The New Relational Database Engine from Amazon
Amazon Aurora: The New Relational Database Engine from AmazonAmazon Aurora: The New Relational Database Engine from Amazon
Amazon Aurora: The New Relational Database Engine from Amazon
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentals
 
Deep Dive: Amazon Elastic MapReduce
Deep Dive: Amazon Elastic MapReduceDeep Dive: Amazon Elastic MapReduce
Deep Dive: Amazon Elastic MapReduce
 
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel AvivSelf Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
 
OAuth 2.0 refresher Talk
OAuth 2.0 refresher TalkOAuth 2.0 refresher Talk
OAuth 2.0 refresher Talk
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
Beyond Shuffling - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
Beyond Shuffling  - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...Beyond Shuffling  - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
Beyond Shuffling - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
 
Нескучное тестирование с pytest
Нескучное тестирование с pytestНескучное тестирование с pytest
Нескучное тестирование с pytest
 
Architecting for Greater Security on AWS
Architecting for Greater Security on AWSArchitecting for Greater Security on AWS
Architecting for Greater Security on AWS
 
Mozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver frameworkMozilla Web QA - Evolution of our Python WebDriver framework
Mozilla Web QA - Evolution of our Python WebDriver framework
 
Survival Analysis of Web Users
Survival Analysis of Web UsersSurvival Analysis of Web Users
Survival Analysis of Web Users
 
Masterless Puppet Using AWS S3 Buckets and IAM Roles
Masterless Puppet Using AWS S3 Buckets and IAM RolesMasterless Puppet Using AWS S3 Buckets and IAM Roles
Masterless Puppet Using AWS S3 Buckets and IAM Roles
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
 

Similaire à Py.test

pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기Yeongseon Choe
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentationArthur Freyman
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksLohika_Odessa_TechTalks
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, PloneQuintagroup
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Fariz Darari
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittestFariz Darari
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentMark Niebergall
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicGraham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicNew Relic
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHPvinaikopp
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passageErik Rose
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic Peopledavismr
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Mark Niebergall
 

Similaire à Py.test (20)

pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
Unit testing presentation
Unit testing presentationUnit testing presentation
Unit testing presentation
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalksSelenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
Django Celery
Django Celery Django Celery
Django Celery
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
 
Python testing
Python  testingPython  testing
Python testing
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittestTesting in Python: doctest and unittest
Testing in Python: doctest and unittest
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
UPC Testing talk 2
UPC Testing talk 2UPC Testing talk 2
UPC Testing talk 2
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHP
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic People
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 

Dernier

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Dernier (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Py.test

  • 2. • Basic: example / usage • Fixture: mechanism / builtin • Plugin: conftest / plugin / hook / 3-party • Scale
  • 4. Getting start! #  content  of  test_sample.py   def  func(x):          return  x  +  1   ! def  test_answer():          assert  func(3)  ==  5  
  • 5. #  content  of  test_sysexit.py   import  pytest   def  f():          raise  SystemExit(1)   ! def  test_mytest():          with  pytest.raises(SystemExit):                  f()  
  • 6. class  TestClass:          def  test_one(self):                  x  =  "this"                  assert  'h'  in  x   !        def  test_two(self):                  x  =  "hello"                  assert  hasattr(x,  'check')  
  • 7. How to run cases? • py.test tests/test_mod.py • py.test tests/ • py.test -k match # def test_match():
  • 8. How to run cases? • py.test --showlocals # trace context • py.test -x # stop on first failure case • py.test --maxfail=2 # on the second • py.test -s # enable `print` output • py.test --durations=10 # list top10 slowest cases
  • 9. How to run cases? • py.test --tb=long # default traceback • py.test --tb=line # oneline • py.test --tb=short • py.test --tb=native # Python default traceback
  • 10. /tmp % py.test test_a.py --tb=line --pdb >>>> traceback >>>> E assert 1 != 1 >>>>> entering PDB >>>> > /private/tmp/test_a.py(10)test_one() -> assert num != 1 (Pdb) num 1 (Pdb) exit
  • 11. How to run cases? import  pytest   def  test_function():          ...          pytest.set_trace()  
  • 13. What to test? • folder, file. • recursive • test_xxx.py, xxx_test.py • TestClass (without __init__ method) • all the function or method with prefix `test_`
  • 14. What to test? #  setup.cfg  /  tox.ini  /  pytest.ini   [pytest]   python_files=check_*.py   python_classes=Check   python_functions=check  
  • 15. What to test? #  content  of  check_myapp.py   class  CheckMyApp:          def  check_simple(self):                  pass          def  check_complex(self):                  pass  
  • 17. Basic configuration Path • Current dir • Parent dir • ...
  • 18. Basic configuration #  content  of  pytest.ini   #  (or  tox.ini  or  setup.cfg)   [pytest]   addopts  =  -­‐-­‐tb=short  -­‐x py.test test_module.py -k test_func
  • 19. Assertions • assert expr • assert a == b • self.assertEqual(a, b) • assert expr, “Expected message” • pytest.raises
  • 20. Assertions • Why `assert`? • simple • nice output • http://pytest.org/latest/example/ reportingdemo.html
  • 21. Assertions Define Own Comparison #  content  of  conftest.py   def  pytest_assertrepr_compare(op,  left,  right):          if  (isinstance(left,  Foo)   and  isinstance(right,  Foo)   and  op  ==  "=="):            return  ['Comparing  Foo  instances:',    'vals:  {0.val}  !=  {1.val}'.format(left,  right)]   Lesson 4
  • 22. Assertions Define Own Comparison def  test_compare():          assert  Foo(1)  ==  Foo(2) >              assert  f1  ==  f2   E              assert  Comparing  Foo  instances:   E                        vals:  1  !=  2  
  • 23. Assertions • Py.test refined `assert` statement • Note: `assert expr, msg` won't output traceback
  • 24. Fixtures • Better than setUp / tearDown: • Explicit name • Call only when needed • Scope: module, class, session, function • Cascade, fixture A => fixture B => ... • Scalability
  • 25. Fixtures as func args import  pytest   ! @pytest.fixture   def  bookmark(app):          return  Bookmark.create(   user_id=1,   works_id=1)
  • 26. Fixtures as func args def  test_get_by_relation(bookmark):          bookmarks  =  Bookmark.get(   user_id=1,   works_id=1   )          assert  bookmarks          assert  bookmarks[0].id  ==   bookmark.id Lesson 01
  • 27. Fixtures as func args • Testcase only care about fixture, no import, no setup, no teardown. • IoC
  • 28. Fixtures - scope @pytest.fixture(scope="module")   def  smtp():          return  smtplib.SMTP("dou.bz")
  • 29. Fixtures - finalization @pytest.fixture(scope="session")   def  database(request):          db_name  =  "{}.db".format(time())          deferred_db.init(db_name)          def  finalizer():                  if  os.path.exists(db_name):                          os.remove(db_name)          request.addfinalizer(finalizer)          return  deferred_db   Lesson 2
  • 30. Fixtures - parametrizing @pytest.fixture(params=[          '/',          '/reader/',   ])   def  signed_page(request):          return  requests.get(request.param)   ! def  test_fetch_pages_success_in_signed(signed_page):          assert  signed_page.status_code  <  300 Lesson 3.1
  • 31. Fixtures - modular class  App(object):   !        def  __init__(self,  request):                  self.request  =  request   ! @pytest.fixture   def  app(request,                  mc_logger,                  db_logger                  ):          return  App(request)  
  • 32. Fixtures - autouse class  TestClass:          @pytest.fixture(autouse=True)          def  table(self,  database):                  Table.create_table()   !        def  test_select(self):                  assert  not  Table.get(id=1)
  • 33. Fixtures - autouse @pytest.fixture   def  table(request,  database):          Table.create_table()          request.addfinilizer(   Table.drop_table)   ! @pytest.mark.usefixtures('table')   class  TestClass:          def  test_select(self):                  assert  not  Table.get(id=1)
  • 34. Fixtures - parametrizing @pytest.mark.parametrize(          "input,expected",  [          ("3+5",  8),          ("2+4",  6),          ("6*9",  42),          pytest.mark.xfail(("6*9",  42))   ])   def  test_eval(input,  expected):          assert  eval(input)  ==  expected Lesson 3.2
  • 35. Fixtures - parametrizing #  conftest.py   import  pytest   ! def  pytest_generate_tests(metafunc):          if  'payload'  in  metafunc.fixturenames:                  metafunc.parametrize('payload',                         ['/tmp/test.json',  ])   ! #  test  file   def  test_meta(payload):          assert  payload  ==  '/tmp/test.json'          ...
  • 36. Fixtures - xUnit def  setup_function(function):          print  'setup'   def  teardown_function(function):          print  'teardown'   def  test_func():          print  'func'   ! #  ==>   """   setup   func   teardown   """
  • 37. Fixtures - xUnit class  TestBookmark:          def  setup_method(self,  method):                  print  'setup'          def  teardown_method(self,  method):                  print  'teardown'          def  test_method(self):                  print  'method'   ! #  ==>   """   setup   method   teardown   """
  • 38. Fixtures - xUnit • setup_module / teardown_module • setup_class / teardown_class • setup_method / teardown_method • setup_function / teardown_function
  • 39. Fixtures - builtin import  datetime   import  pytest   ! FAKE_TIME  =  datetime.datetime(2020,  12,  25,  17,  05,  55)   ! @pytest.fixture   def  patch_datetime_now(monkeypatch):   !        class  mydatetime:                  @classmethod                  def  now(cls):                          return  FAKE_TIME   !        monkeypatch.setattr(datetime,  'datetime',  mydatetime)   ! ! def  test_patch_datetime(patch_datetime_now):          assert  datetime.datetime.now()  ==  FAKE_TIME
  • 40. Fixtures - builtin • monkeypatch • tmpdir • capsys / capfd • `py.test --fixture`
  • 41. Maker • pytest.marker • py.test --marker • marker is like tag. • @pytest.mark.skipif(getenv('qaci')) • @pytest.mark.xfail('oooops') • @pytest.mark.skipif("config.getvalue('pass')") • @pytest.mark.ask_sunyi !
  • 42. unittest.TestCase • Compatible • But be careful. There is no funcargs mechanism for unittest cases.
  • 43. Plugin • py.test supply many hooks. • collection / configuration / run / output • Basic types: • builtin • 3-party plugins • conftest.py plugins
  • 44. Plugin - find conftest.py • recursive • `import conftest` X
  • 45. Plugin - 3-party • pip install pytest-xxxxx • pytest-random, pytest-cov • https://pypi.python.org/pypi? %3Aaction=search&term=pytest&submit=s earch
  • 46. Plugin - load plugin • py.test -p plugin_name • py.test -p no:plugin_name • pytest.ini • conftest.py `pytest_plugins` • pytest_plugins = "name1", "name2", • pytest_plugins = "suites.isolated_cases"
  • 47. Plugin - hooks • http://pytest.org/latest/plugins.html#hookspecification-and-validation • see source.
  • 48. Plugin - example #  content  of  suites.isolated_cases   def  pytest_addoption(parser):          group  =  parser.getgroup("isolated_cases",  "")          group._addoption(                  '-­‐-­‐with-­‐data-­‐service',                  action="store_true",                  default=False,                  dest='with_data_service',                  help=(                          "with  MySQL/beansdb/memcached  up  at  the   beginning  of  session"                          "and  down  at  the  end  of  session."                  )          )
  • 49. Plugin - example #  content  of  isolated_cases   def  pytest_configure(config):          if  config.option.with_data_service:                  build_tables()                  stop_kvstore()                  sleep(1)                  start_kvstore() $ py.test --with-data-service tests/
  • 50. Plugin - example #  content  of  tests/conftest.py   pytest_plugins  =  "suites.isolated_cases" $ py.test --with-data-service tests/
  • 51. EOF