python-tests
bởi nvidia
Các bài kiểm tra Python cho NeMo Fabric; dùng cái này khi viết bài kiểm tra
npx skills add https://github.com/nvidia/nemo-fabric --skill python-testsPython Test Style
- Pytest is used to run tests.
- Do not add
@pytest.mark.asyncioto any test. Async tests are automatically detected and run by the async runner; the decorator is unnecessary clutter. - Do not add a
-> Nonereturn type annotation to test functions. This is not a common convention in pytest and adds unnecessary verbosity. - When mocking a class, do not define a new class. Use
unittest.mock.MagicMockorunittest.mock.AsyncMock, with thespecconstructor argument when necessary. - The name of the mocked class should be prefixed with
mock, notfake. - Prefer pytest fixtures over helper methods.
- Do not repeat fixtures, if a fixture is needed in multiple test files, place it in a
conftest.pyfile. - When creating a fixture follow this pattern:
Only specify the scope argument when the value is something other than "function".@pytest.fixture(name="<fixture_name>"[, scope="<scope>"]) def <fixture_name>_fixture() -> <return_type>: ... - Prefer
pytest.mark.parametrizeover creating individual tests for different input types. - If a fixture is needed for a test, but either does not return a value or the value is not used in the test, use the
@pytest.mark.usefixturesdecorator. tests/conftest.pycontains arestore_environ_fixturefixture that restores the environment variables to their original state after each test, it is defined withautouse=Trueso it is automatically applied to all tests. If you need to modify the environment variables in a test, do so usingos.environand the fixture will restore them after the test completes. There is no need to usemonkeypatch.setenvto modify environment variables in tests.- Avoid defensive programming in tests. If a test fails, it should fail loudly and clearly, rather than silently passing due to defensive checks. For example
is preferred overdata = results["data"]
Simply allow the resulting KeyError to be raised if the "data" key is not present in the results dictionary, as this will provide a clear indication of what went wrong in the test.data = results.get("data")
Common Commands
# Focused test loop
uv run pytest -k "<pattern>"
# Run all tests
uv run pytest
Do Not Write Tests For
- Documentation.
- Test helper code under
tests/_utils/. - Package metadata or wheel installation behavior.
References
pyproject.tomltests/conftest.py