Skip to content

Instantly share code, notes, and snippets.

@JeroenDeDauw
Last active December 8, 2016 15:10
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 JeroenDeDauw/d051a09fb7d8f1f3dcb852aa84076714 to your computer and use it in GitHub Desktop.
Save JeroenDeDauw/d051a09fb7d8f1f3dcb852aa84076714 to your computer and use it in GitHub Desktop.
Python Value Object using namedtuple
# Tested with Python 3.5
from unittest import TestCase, main
from collections import namedtuple
import math
class Point(namedtuple('Point', 'x, y')):
def get_distance_from_origin(self):
return math.sqrt(self.x**2 + self.y**2)
def set_x(self, new_x):
self.x = new_x
class TestValueObject(TestCase):
def test_can_construct(self):
point = Point(y=2, x=4)
self.assertEqual(point.x, 4)
self.assertEqual(point.y, 2)
def test_cannot_modify_fields(self):
point = Point(y=2, x=4)
with self.assertRaises(AttributeError):
point.x = 32202
with self.assertRaises(AttributeError):
point.y = 32202
def test_cannot_construct_without_constructor_arguments(self):
with self.assertRaises(TypeError):
Point()
def test_can_call_method(self):
point = Point(x=3, y=4)
self.assertEqual(point.get_distance_from_origin(), 5)
def test_cannot_modify_fields_from_the_inside(self):
point = Point(x=4, y=2)
with self.assertRaises(AttributeError):
point.set_x(32202)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment