user2081554
user2081554

Reputation:

Return as a function: return()

Is it possible to make function with the name return that will simulate normal python return.

Why: So that in unittesting we can break from the method that have infinity loop:

while True:
    ...
    time.sleep(x)

I want to do something like this...

def return(y):
    ...

self.mock_module['time'].sleep.side_effect = [return(z)]

Upvotes: 2

Views: 202

Answers (2)

Søren Løvborg
Søren Løvborg

Reputation: 8751

You can't have return as a function – because that function would simply return from itself. I think the solution you're looking for is an exception:

class StopTest(Exception):
    pass

def stopTest():
    raise StopTest()

...

    self.mock_module['time'].sleep.side_effect = [stopTest]

and then use assertRaises to expect the StopTest exception in your unit test.

Upvotes: 0

Jed Fox
Jed Fox

Reputation: 3025

No. That is not possible. However, you can do something like this:

condition = []
while not condition:
    ...

self.mock_module['time'].sleep.side_effect = [lambda:condition.append(1)]

Upvotes: 2

Related Questions