Created
December 18, 2009 19:53
-
-
Save jcsalterego/259719 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 unittest | |
| # regular ole object | |
| class Image: | |
| def __init__(self): | |
| self.os = 'centos' | |
| self.version = 5.3 | |
| self.region = 'us-east' | |
| self.size = 'floor' | |
| # syntactic sugar | |
| def pand(*args): | |
| return reduce(lambda x, y: x and y, args) | |
| def por(*args): | |
| return reduce(lambda x, y: x or y, args) | |
| def pnot(x): | |
| return not x | |
| def props(**conditions): | |
| if not conditions: | |
| raise Exception, "empty conditions" | |
| # convert conditions | |
| conditions = [lambda n: (lambda x: getattr(x, k) == v)(n) | |
| for (k, v) | |
| in conditions.items()] | |
| return reduce(lambda c1, c2: c1 and c2, conditions) | |
| class TestLogic(unittest.TestCase): | |
| def setUp(self): | |
| self.my_image = Image() | |
| def test_one_prop(self): | |
| c = props(os='centos') | |
| self.assertEqual(c(self.my_image), True) | |
| def test_pand(self): | |
| c = pand(props(os='centos'), props(version=5.3)) | |
| self.assertEqual(c(self.my_image), True) | |
| def test_por(self): | |
| c = por(props(os='centos'), False) | |
| self.assertEqual(c(self.my_image), True) | |
| def test_nested(self): | |
| filter_cond = pand(props(os='centos', version=5.3), | |
| props(region='us-east', size='floor')) | |
| self.assertEqual(filter_cond(self.my_image), True) | |
| if __name__ == '__main__': | |
| unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment