Skip to content

Instantly share code, notes, and snippets.

@anaved
Last active February 21, 2018 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anaved/437ed10fa2c2a4f3252e715aa2f2b006 to your computer and use it in GitHub Desktop.
Save anaved/437ed10fa2c2a4f3252e715aa2f2b006 to your computer and use it in GitHub Desktop.
Mock implementation using context manager
import mock
class Patchee(object):
def name(self):
return "Patchee"
class MyContextPatcher(object):
def __init__(self, newName):
self.newName = newName
def __enter__(self):
self.patcher = mock.patch.object(Patchee, 'name', return_value=self.newName)
self.patcher.start()
return self
def __exit__(self, *args, **kwargs):
self.patcher.stop()
with MyContextPatcher('Apatchee') as p:
# This shall return mocked value Apatchee
print Patchee().name()
# This shall return the original value Patchee
print Patchee().name()
#Below is a sample of operation flow with exceptions in context manager.
class ExceptionRaiserContext(object):
def __init__(self, raiseException ):
self.raiseException = raiseException
def __enter__(self):
print "Enter called"
if self.raiseException:
raise Exception("Exception raised in enter")
def __exit__(self, exc_type, exc_val, exc_tb):
print "Exit called with exception", exc_type
#Example of no exception ( All blocks are executed )
with ExceptionRaiserContext(False):
print "Operation performed"
#Example of exception at __enter__ ( Enter executed till exception )
with ExceptionRaiserContext(True):
print "Operation performed"
#Example of exception at operation ( All blocks are executed )
with ExceptionRaiserContext(False):
print "Operation performed"
raise Exception("Exception raised in operation")
# 1.
myFile = open('test.txt')
print myFile.read()
# 2.
with open('test.txt') as myFile:
print myFile.read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment