Skip to content

Instantly share code, notes, and snippets.

@Fluxx
Created February 1, 2013 22:02
Show Gist options
  • Select an option

  • Save Fluxx/4694459 to your computer and use it in GitHub Desktop.

Select an option

Save Fluxx/4694459 to your computer and use it in GitHub Desktop.
diff --git a/exam/objects.py b/exam/objects.py
index 7e6aaf1..7bedd18 100644
--- a/exam/objects.py
+++ b/exam/objects.py
@@ -5,3 +5,19 @@ def always(value):
return lambda *a, **k: value
noop = no_op = always(None)
+
+
+class call(tuple):
+
+ def __new__(cls, *args, **kwargs):
+ arguments = (args, tuple(sorted(kwargs.items())))
+ return tuple.__new__(cls, arguments)
+
+
+class effect(dict):
+
+ def __call__(self, *args, **kwargs):
+ try:
+ return self[call(*args, **kwargs)]
+ except KeyError:
+ raise TypeError('Unknown effect for: %s, %s' % (args, kwargs))
diff --git a/tests/test_objects.py b/tests/test_objects.py
index 2bddb54..d79eefb 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -2,7 +2,7 @@ from describe import expect
from mock import sentinel
from unittest2 import TestCase
-from exam.objects import always, noop
+from exam.objects import always, noop, call, effect
class TestAlways(TestCase):
@@ -22,3 +22,33 @@ class TestAlways(TestCase):
def test_returns_none(self):
expect(noop()).to == None
+
+
+class TestCall(TestCase):
+
+ def test_records_and_checks_equality_on_calls(self):
+ expect(call(1)).to == call(1)
+ expect(call(1)).to != call(2)
+ expect(call(1, 2)).to == call(1, 2)
+ expect(call(1, 2, a=5)).to == call(1, 2, a=5)
+
+
+class TestEffect(TestCase):
+
+ def test_creates_callable_mapped_to_config_dict(self):
+ config = {call(1): 2, call('a'): 3, call(1, b=2): 4, call(c=3): 6}
+ eff = effect(config)
+
+ expect(eff(1)).to == 2
+ expect(eff('a')).to == 3
+ expect(eff(1, b=2)).to == 4
+ expect(eff(c=3)).to == 6
+
+ def test_raises_type_error_when_called_with_unknown_args(self):
+ eff = effect({call(1): 2})
+ self.assertRaises(TypeError, eff, 'junk')
+
+ def test_can_be_used_with_mutable_data_structs(self):
+ eff = effect({call([1, 2, 3]): 'list'})
+ expect(eff([1, 2, 3])).to == 'list'
+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment