pytest#
Última modificación: Mayo 14, 2022
Ejemplo básico#
[1]:
%%writefile test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
Writing test_sample.py
[3]:
!pytest
============================= test session starts ==============================
platform linux -- Python 3.8.10, pytest-7.1.2, pluggy-1.0.0
rootdir: /workspace/pytest
plugins: anyio-3.5.0
collected 1 item
test_sample.py F [100%]
=================================== FAILURES ===================================
_________________________________ test_answer __________________________________
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:6: AssertionError
=========================== short test summary info ============================
FAILED test_sample.py::test_answer - assert 4 == 5
============================== 1 failed in 0.10s ===============================
Chequeo de una excepción#
[4]:
%%writefile test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
Writing test_sysexit.py
[5]:
!pytest -q test_sysexit.py
. [100%]
1 passed in 0.01s
Multiples tests en una clase#
[6]:
%%writefile test_class.py
class TestClass:
def test_one(self):
x = "this"
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, "check")
Writing test_class.py
[7]:
!pytest -q test_class.py
.F [100%]
=================================== FAILURES ===================================
______________________________ TestClass.test_two ______________________________
self = <test_class.TestClass object at 0x7f3afd8c0fa0>
def test_two(self):
x = "hello"
> assert hasattr(x, "check")
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:8: AssertionError
=========================== short test summary info ============================
FAILED test_class.py::TestClass::test_two - AssertionError: assert False
1 failed, 1 passed in 0.06s
[8]:
%%writefile test_class_demo.py
class TestClassDemoInstance:
def test_one(self):
assert 0
def test_two(self):
assert 0
Writing test_class_demo.py
[10]:
!pytest -k TestClassDemoInstance -q
FF [100%]
=================================== FAILURES ===================================
________________________ TestClassDemoInstance.test_one ________________________
self = <test_class_demo.TestClassDemoInstance object at 0x7f69f3d27370>
def test_one(self):
> assert 0
E assert 0
test_class_demo.py:3: AssertionError
________________________ TestClassDemoInstance.test_two ________________________
self = <test_class_demo.TestClassDemoInstance object at 0x7f69f3d27310>
def test_two(self):
> assert 0
E assert 0
test_class_demo.py:6: AssertionError
=========================== short test summary info ============================
FAILED test_class_demo.py::TestClassDemoInstance::test_one - assert 0
FAILED test_class_demo.py::TestClassDemoInstance::test_two - assert 0
2 failed, 4 deselected in 0.08s