# How to Run Tests Using uv

If your project lists [pytest](https://pydevtools.com/handbook/reference/pytest.md) as a dev dependency, [uv](https://pydevtools.com/handbook/reference/uv.md) runs every test with a single command:

```bash
uv run pytest
```

`uv run` syncs the [virtual environment](https://pydevtools.com/handbook/explanation/what-is-a-virtual-environment.md) automatically, so the project and its dependencies are always installed before pytest starts.

If pytest is not in the project's dependencies and you don't want to add it, inject it at runtime:

```bash
uv run --with pytest pytest
```

## Run a Subset of Tests

Target a single file, a single function, or a keyword pattern:

```bash
uv run pytest tests/test_api.py
uv run pytest tests/test_api.py::test_login
uv run pytest -k "login or signup"
```

The `-k` flag matches against test names, so `-k "login or signup"` runs every test whose name contains either word.

Run only tests tagged with a [marker](https://docs.pytest.org/en/stable/how-to/mark.html):

```bash
uv run pytest -m slow
```

## Control Output

Show each test name instead of a dot:

```bash
uv run pytest -v
```

Show `print()` output as tests run by disabling stdout/stderr capture:

```bash
uv run pytest -s
```

To show log messages as tests run, enable live logging separately with `uv run pytest --log-cli-level=INFO`.

Shorten tracebacks to just the failing assertion:

```bash
uv run pytest --tb=short
```

## Stop Early on Failure

Stop after the first failure:

```bash
uv run pytest -x
```

Stop after _n_ failures:

```bash
uv run pytest --maxfail=3
```

## Re-run Only Failed Tests

pytest records failures in `.pytest_cache/`. Use `--last-failed` to rerun those tests:

```bash
uv run pytest --last-failed
```

If there are no cached failures, `--last-failed` runs all selected tests. After fixing failures, run the full suite to check for regressions.

Use `--failed-first` instead to run the previously failed tests first, then the rest:

```bash
uv run pytest --failed-first
```

## Set Persistent Defaults

Add flags to [pyproject.toml](https://pydevtools.com/handbook/reference/pyproject.toml.md) so they apply on every run without typing them:

```toml
[tool.pytest.ini_options]
addopts = "-x --tb=short"
```

Any flags passed on the command line are appended to `addopts`, so `uv run pytest -v` becomes `-x --tb=short -v`.
