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
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
24. Fixtures
• Better than setUp / tearDown:
• Explicit name
• Call only when needed
• Scope: module, class, session, function
• Cascade, fixture A => fixture B => ...
• Scalability
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/