Last active
December 8, 2016 15:10
-
-
Save JeroenDeDauw/d051a09fb7d8f1f3dcb852aa84076714 to your computer and use it in GitHub Desktop.
Python Value Object using namedtuple
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
# 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