• Mémo Pytest : la base

  • Pytest basics

pytest.ini:

[pytest]
addopts = -vv --capture=no --showlocals --exitfirst
norecursedirs = dev venv

.coveragerc

[run]
omit = venv/*, dev/*

machin.py

import uuid
import hashlib


class Machin:
    def __init__(self):
        self.uuid = uuid.uuid4()

    def revert(self):
        return self.uuid[::-1]

    def sha1(self):
        return hashlib.sha1(str(self.uuid).encode()).hexdigest()

    def throws_exception(self):
        raise ValueError("Hey Ho !")

test_machin.py

import pytest
import hashlib
import uuid
from unittest.mock import patch
from machin import Machin


# Fixtures

@pytest.fixture
def mocked_uuid():
    return "55b80b9e-0e18-4f94-b565-0755bbd42c31"


@pytest.fixture
def mocked_sha1():
    return "8c46aaa34d40112cd26872e4d5cd8d47ba71e3d4"


# L'objet mock est passé dans un context manager

def test_with_mocks_as_context_manager(mocked_uuid):
    with patch.object(uuid, 'uuid4', return_value=mocked_uuid):
        truc = Machin()
        assert truc.revert() == "13c24dbb5570-565b-49f4-81e0-e9b08b55"


# Le module mocké est passé dans un décorateur

@patch.object(uuid, "uuid4")
def test_with_mocks(uuid, mocked_uuid):
    uuid.return_value = mocked_uuid
    truc = Machin()
    assert truc.uuid == mocked_uuid


@patch.object(hashlib, 'sha1')
def test_sha1_is_mocked(mock, mocked_sha1):
    mock.return_value = mocked_sha1
    truc = Machin()
    assert truc.sha1() == "8c46aaa34d40112cd26872e4d5cd8d47ba71e3d4"


# Gestion des exceptions avec Pytest

def test_throws_exception():
    with pytest.raises(ValueError):
        truc = Machin()
        truc.throws_exception()


16 septembre 2019 16:23