Skip to content

Instantly share code, notes, and snippets.

@alecmunro
alecmunro / gist:1214536
Created September 13, 2011 18:06
Adapter Pattern example
class IPaintable(Interface):
def get_color():
pass
def paint(color):
pass
class BicyclePainter(object):
"""Adapts a Bicycle to the IPaintable interface."""
def __init__(self, context):
@alecmunro
alecmunro / gist:1214513
Created September 13, 2011 17:56
Strategy Pattern example
def not_empty_string(value):
assert(len(value) > 0)
def valid_email(value):
assert("@" in value)
def greater_than_zero(value):
assert(int(value) > 0)
FIELD_VALIDATORS = {
@alecmunro
alecmunro / gist:1214446
Created September 13, 2011 17:35
Mediator Pattern example
CarList = function(){
this.cars = [];
};
CarList.prototype.add_car = function(car){
this.cars.push(car);
this.render();
};
/*
Some code here for managing rendering of the list of cars.
*/
@alecmunro
alecmunro / gist:1214125
Created September 13, 2011 15:34
Template Method example
DEFAULT_EMAIL_TYPE = "text"
DEFAULT_RECIPIENT = "alecmunro@gmale.com"
DEFAULT_SUBJECT = "Good news, everyone!"
class EmailReporter(object):
email_type = DEFAULT_EMAIL_TYPE
def send_report(self, settings):
data = self.collect_data()
@alecmunro
alecmunro / gist:1203804
Created September 8, 2011 16:20
Chaining methods and attributes
"""Mocker:
Chaining attribute or method access in Mocker is trivial. During
the record phase, every mock operation returns a mock."""
from mocker import Mocker
def mocker_test():
mocker = Mocker()
a_mock = mocker.mock()
@alecmunro
alecmunro / gist:1198698
Created September 6, 2011 19:25
Partial mocks
#Need to create this because mocker.patch() and flexmock(object)
#don't work with builtins.
class Something(object):
def do_something(self):
pass
"""Mocker:
@alecmunro
alecmunro / gist:1150664
Created August 17, 2011 02:15
Verifying mock expectations
"""Mocker:
Setting expectations with Mocker is as simple as calling the
methods on the mocks, and then switching the mocker instance
into replay mode."""
from mocker import Mocker
def mocker_test():
mocker = Mocker()
@alecmunro
alecmunro / gist:1149878
Created August 16, 2011 19:09
Getting mock objects from different libraries
"""Mocker:
Mocks are obtained from a mocker instance, which is created
automatically if you create a test case that inherits from
MockerTestCase.
"""
from mocker import Mocker, MockerTestCase
class TestCaseForMocker(MockerTestCase):
@alecmunro
alecmunro / gist:1149773
Created August 16, 2011 18:22
Confusion when not everything is mocked
def delete_file(self, name):
path = os.path.join(BASE_DIR, name)
if self.os.path.exists(path):
os.remove(path)
@alecmunro
alecmunro / gist:1149767
Created August 16, 2011 18:19
Verbose dependency specification for mocking
import time
def __init__(self, time_mod=time):
self.time = time_mod
def some_method(self):
self.time.sleep(10)