Skip to content

Instantly share code, notes, and snippets.

@markgreene74
Created November 21, 2019 22:44
Show Gist options
  • Select an option

  • Save markgreene74/3fbde02fc5a4685612f7ef34268ac6f0 to your computer and use it in GitHub Desktop.

Select an option

Save markgreene74/3fbde02fc5a4685612f7ef34268ac6f0 to your computer and use it in GitHub Desktop.
simple mock.patch
(env) [lon1-01 tmp]$ cat something.py
def afunction(arg=None):
    counter = 0
    try:
        arg += 1
    except:
        # do nothing, increase the counter
        counter += 1
    return counter

print(afunction(1))
print(afunction())
(env) [lon1-01 tmp]$ cat test_something.py
import pytest
import mock
import something

def test_afunction_ok():
    test_counter = something.afunction(1)
    print(test_counter)
    assert test_counter == 0

@mock.patch("something.afunction", mock.MagicMock(return_value=1))
def test_afunction_not_ok():
    test_counter = something.afunction()
    print(test_counter)
    assert test_counter == 1
(env) [lon1-01 tmp]$ pytest test_something.py
============================= test session starts ==============================
platform linux -- Python 3.6.8, pytest-5.1.2, py-1.8.0, pluggy-0.13.0
rootdir: /tmp
plugins: env-0.6.2
collected 2 items

test_something.py ..                                                     [100%]

============================== 2 passed in 0.02s ===============================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment