简体   繁体   中英

Python : How do you mock a the result of a dependant function call and specify what it returns

I'm trying to mock the return value from a nested function call. This should be simple, but it's not working. So I have a Car class that has a poweredBy() member function that returns an instance of the Engine class. The Engine class has a member getEngineType() that returns the string 'BigandFast'.

class Engine(object):
    def engineType(self):
        return 'BigandFast'

class Car(object):
     def poweredBy(self):
         return Engine()

so: Car().poweredBy().engineType() returns 'BigandFast'

I have a function getEngineType() that takes a car and returns the engine type:

def getEngineType(aCar):         
    return aCar.poweredBy().engineType()

I'd like to mock the getEngineType() function so I can change the result:

@mock.patch('testing.scratch.mock_test.Car')
def mockedCar(mockedCar):
 mockedCar.return_value.poweredBy.return_value.getEngineType.return_value = 'SmallAndSlow' 
 print getEngineType(mockedCar)

But this still returns 'BigandFast'. The line :

mockedCar.return_value.poweredBy.return_value.getEngineType.return_value = 'SmallAndSlow'

does not have any impact on the mocked object that I can see in the debugger. So my questions are:

  1. How do you specify the return value of engineType() in the mock

  2. How/Would the syntax be different if the Car was not passed into getEngineType() as a parameter but generated inside the function.

Since you start with a Car class mock and you set the return_value chain from there, you need to actually instantiate a Car:

import mock
class Engine(object):
    def engineType(self):
        return 'BigandFast'

class Car(object):
     def poweredBy(self):
         return Engine()

def getEngineType(aCar):
    return aCar.poweredBy().engineType()

@mock.patch('__main__.Car')
def mockedCar(mockedCar):
    mockedCar.return_value.poweredBy.return_value.engineType.return_value = 'SmallAndSlow'
    c = Car()
    print getEngineType(c)

mockedCar()

Output:

SmallAndSlow

So, you start with a Car class mock, then you get a return value of a Car object mock, then a poweredBy method mock, then an engineType method mock and finally the return value.

Unfortunately, I probably didn't use the right vocabulary here, but the gist is: mockedCar is a mock of the Car class , you need to instantiate it to access the return_value that you set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM