In the previous post, I wrote pytest in the tag but only "I'm using pytest", so it's a memorandum.
pip install pytest
pip install pytest-django
pip install pytest-pythonpath
After that, create a settings file for pytest.
Create a file called test_hoge.py
test_hoge.py
import pytest
@pytest.mark.django_db(transaction=True)
def test_hoge(self):
result = foo.get_money(id=1)
assert result == 100
And
py.test test_hoge.py --create-db (or--reuse-db)
Run the test on. If you specify a directory instead of a filename, all tests in that directory will be run. If you take the method name "test_", the test will not be executed.
This setup () is done before running all the tests described in the test file. I often do user creation and test preparation processing. setup()
def setup(self):
hoge()
teardown() Describes the process to be executed at the end of each test. If you replace the master data with the test data with setup () and test it, the process to restore it is included.
def teardown():
foo()
pytest.raises(Exception) It is used to check if an exception has occurred properly. If an Exception occurs, the test will return a normal result.
hoge.py
[Test target]
class Hoge():
def foo(id):
try:
return ItemMaster.get(id)
except DoesNotExist:
raise IllegalIdError
test_hoge.py
import pytest
import IllegalIdError
@pytest.mark.django_db(transaction=True)
def test_foo():
with pytest.raises(IllegalIdError):
Hoge.foo(-100000)
Specify conditions to skip the test. If it is skipped when the test is executed, "s" will be displayed in the result, so it is easier to understand that "the test was not performed" than taking the method name "test_" and not executing it.
test_hoge.py
@pytest.mark.skipif("True")
def test_hoge(self):
assert is_hoo(id=1)
↑ In this case, it will always be skipped.
Recommended Posts