Skip to content

Instantly share code, notes, and snippets.

@bml1g12
Last active February 17, 2020 06:04
Show Gist options
  • Save bml1g12/347aae4df1db5cf06016a2da64d4617a to your computer and use it in GitHub Desktop.
Save bml1g12/347aae4df1db5cf06016a2da64d4617a to your computer and use it in GitHub Desktop.
TestingOveride
def _create_config():
return {"foo_key":0}
def create_foo_thing():
config = _create_config()
return config
from unittest.mock import patch
import foo
import pytest
@pytest.fixture()
def setup_test_A():
config = foo._create_config()
config['foo_key'] = 10
with patch.object(foo, '_create_config', return_value=config):
foo_thing = foo.create_foo_thing()
return foo_thing
def test_A_fixed(setup_test_A):
foo_thing = setup_test_A
# We have edited the config in this test to 10, so assert its 10
assert foo_thing['foo_key'] == 10
def test_B():
# As we are not editing the config, we expect foo_key to be 0, its default
foo_thing = foo.create_foo_thing()
assert foo_thing['foo_key'] == 0
@kinowarrior
Copy link

How about:

from importlib import reload

import pytest

import foo


@pytest.fixture(autouse=True)
def setup():
    reload(foo)


def test_A_fixed():

    foo._create_config = lambda: {"foo_key": 10}

    foo_thing = foo.create_foo_thing()

    assert foo_thing['foo_key'] == 10


def test_B_fixed():

    foo._create_config = lambda: {"foo_key": 5}

    foo_thing = foo.create_foo_thing()

    assert foo_thing['foo_key'] == 5

@bml1g12
Copy link
Author

bml1g12 commented Feb 17, 2020

Equivalent to above but in style of original gist entry

from unittest.mock import patch
import foo
import pytest

@pytest.fixture()
def setup_test_A():
    with patch.object(foo, '_create_config', return_value={"foo_key": 10}): 
        foo_thing = foo.create_foo_thing()
    return foo_thing

@pytest.fixture()
def setup_test_B():
    with patch.object(foo, '_create_config', return_value={"foo_key": 5}): 
        foo_thing = foo.create_foo_thing()
    return foo_thing
    
def test_A_fixed(setup_test_A):
    foo_thing = setup_test_A
    assert foo_thing['foo_key'] == 10
    
def test_B_fixed(setup_test_B):
    foo_thing = setup_test_B
    assert foo_thing['foo_key'] == 5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment