mardi 11 septembre 2018

Mocking a static function call with a long chain of calls in python 2.7

I'm trying to test a large legacy Django application, and I'm getting confused by Python mocking as I have never worked on large Python application.

Specifically, I have method has a long call chain inside that generates an array:

def update(self): # in some class X
    # ...
    for z in foo.models.Bar.objects.filter(x=1).select('xyz'):
        raise Exception("mocked successfully")

I'd like to mock the foo.models.Bar.objects.filter(x=1).select('xyz').

Attempt 1

I've tried several approaches gleaned from various questions, notably using a decorator:

@mock.patch('foo.models.Bar.objects.filter.select')
def test_update(self, mock_select):
    mock_select.return_value = [None]
    X().update()

I never hit the inside of the mocked call, however- the test should fail due to the exception being raised.

Attempt 2

@mock.patch('foo.models.Bar')
def test_update(self, mock_Bar):
    mock_Bar.objects.filter(x=1).select('xyz').return_value = [None]
    X().update()

Attempt 3

@mock.patch('foo.models.Bar')
def test_update(self, mock_Bar):
    mock_Bar.objects.filter().select().return_value = [None]
    X().update()

Attempt 4

I then tried something more basic, to see if I could get an NPE, which didn't work either.

@mock.patch('foo.models.Bar')
def test_update(self, mock_Bar):
    mock_Bar.return_value = None
    X().update()

It's late so I assume I must be overlooking something basic in the examples I've seen!?

Aucun commentaire:

Enregistrer un commentaire