Home


How to run setup and teardown functions

def setup_module(module):  
    pass  

def teardown_module(module):  
    pass  

But, I may not need setup and teardown anyway.

In other languages I would use them to set up state, but in pytest
there is a nice dependency injector…

How to do dependency injection of a fixture

import pytest  

@pytest.fixture  
def thing():  
    yield 'abc'  

def test_insert(thing):  
    assert thing == 'abc'  

How to stub

from unittest.mock import patch  

class Foo:  
    def bar(self):  
        return "You won't see me"  

def test_foo_bar():  
    with patch.object(Foo, "bar", return_value="stubbed result"):  
        foo = Foo()  
        assert foo.bar() == "stubbed result"  

How to mock

from unittest.mock import patch, MagicMock  

class Foo:  
    def bar(self, x):  
        return x * 2  

def test_foo_bar_mock():  
    with patch.object(Foo, "bar") as mock_method:  
        mock_method.return_value = 999  
        foo = Foo()  
        result = foo.bar(10)  
        assert result == 999  
        mock_method.assert_called_once_with(10)