Skip to content

Instantly share code, notes, and snippets.

@romainx
Created May 15, 2020 05:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainx/6cfe532e177234fc9028b69206433650 to your computer and use it in GitHub Desktop.
Save romainx/6cfe532e177234fc9028b69206433650 to your computer and use it in GitHub Desktop.
[pytest best practices] Some pytest best practices #python #pytest
[pytest]
# Default options:
# - `--tb=line` stand for shorter traceback format (only one line per failure)
# - `-rfEPpxX` Select the short summary info to display
# See https://docs.pytest.org/en/latest/usage.html#modifying-python-traceback-printing
addopts = --tb=line -rfEPpxX
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S
# content of test_sample.py
import logging
import pytest
logger = logging.getLogger(__name__)
# using arguments to be able to identify them easily
# ease parametrization in a second step
def test_eval_operation(operation="3 + 4", expected=6):
# instead of commenting logging a clear message saying what is tested
test_that = f"{operation} = {expected}"
logger.info(f"Test that {test_that}")
actual = eval(operation)
# actual left, expected right
# proper error message with error left and what we got right
assert actual == expected, f"{test_that} failed, got {actual}"
# More information on parametrize -> https://docs.pytest.org/en/latest/parametrize.html
@pytest.mark.parametrize(
"operation,expected",
[("2 + 4", 6), pytest.param("3 + 4", 6, marks=pytest.mark.xfail)],
)
def test_eval_operation_param(operation, expected):
test_that = f"{operation} = {expected}"
logger.info(f"Test that {test_that}")
actual = eval(operation)
assert actual == expected, f"{test_that} failed, got {actual}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment