Last active
February 21, 2018 20:43
-
-
Save anaved/437ed10fa2c2a4f3252e715aa2f2b006 to your computer and use it in GitHub Desktop.
Mock implementation using context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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