Introduction
Pytest is used to test python project. This article will introduce how to basically use pytest.
Installation
First, we should read the file pytest.ini,
[pytest]
addopts=--verbose --cov-append --cov-report term --cov tinydb
Therefore, we should install pytest and pytest-cov. Then, run
pytest
This command will first initialize the test from pytest.ini.
conftest.py
In confest.py, it defines the test objects, for example
@pytest.ficture(params=['memory', 'json'])
def db(request, tmp_path: Path):
if request.param == 'json':
db_ =TinyDB(tmp_path / 'test.db', storage=JSONStorage)
else:
db_ = TinyDB(storage=MemoryStorage)
db_.drop_tables()
db_.insert_multiple({'int': 1, 'char': c} for c in 'abc')
yield db_
In this example, we defined a test object, db. When using db, it will go over all the params: 'memory' and 'json'
test_filename.py
The default test files' name should be named as this, else the pytest.ini should claim the regular for the test files' name. In these files, there should be test fuctions written as
def test_all(db: TinyDB):
db.drop_tables()
for i in range(10):
db.insert({})
assert len(db.all()) == 10
With assert, the test function will try the equation after it and record it in the test results.