Implemented Memento design pattern.
This commit is contained in:
41
pypatterns/structural/memento.py
Normal file
41
pypatterns/structural/memento.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from copy import deepcopy
|
||||
|
||||
|
||||
class Memento(object):
|
||||
"""
|
||||
Memento class as part of the Memento design pattern.
|
||||
"""
|
||||
def __init__(self, state):
|
||||
"""
|
||||
Initialize a new Memento instance.
|
||||
|
||||
@param state: The state to save in this Memento.
|
||||
@type state: dict
|
||||
"""
|
||||
self.__state = state
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
return self.__state
|
||||
|
||||
|
||||
class Originator(object):
|
||||
"""
|
||||
Originator base class as part of the Memento design pattern.
|
||||
"""
|
||||
def commit(self):
|
||||
"""
|
||||
Commit this objects state to a memento.
|
||||
|
||||
@return: A memento instance with this objects state.
|
||||
"""
|
||||
return Memento(deepcopy(self.__dict__))
|
||||
|
||||
def rollback(self, memento):
|
||||
"""
|
||||
Rollback this objects state to a previous state.
|
||||
|
||||
@param memento: The memento object holding the state to rollback to.
|
||||
@type memento: Memento
|
||||
"""
|
||||
self.__dict__ = memento.state
|
||||
64
tests/structural_tests/test_memento.py
Normal file
64
tests/structural_tests/test_memento.py
Normal file
@@ -0,0 +1,64 @@
|
||||
from unittest import TestCase
|
||||
from pypatterns.structural.memento import Memento, Originator
|
||||
|
||||
|
||||
class MementoTestCase(TestCase):
|
||||
"""
|
||||
Unit testing class for the Memento Class.
|
||||
"""
|
||||
def setUp(self):
|
||||
"""
|
||||
Initialize testing data.
|
||||
"""
|
||||
self.state = {'foo': 'bar'}
|
||||
|
||||
def test_init(self):
|
||||
"""
|
||||
Test the __init__ method.
|
||||
|
||||
@raise AssertionError: If the test fails.
|
||||
"""
|
||||
memento = Memento(self.state)
|
||||
|
||||
self.assertEqual(memento.state, self.state)
|
||||
|
||||
|
||||
class OriginatorTestCase(TestCase):
|
||||
"""
|
||||
Unit testing class for the Originator class.
|
||||
"""
|
||||
def setUp(self):
|
||||
"""
|
||||
Initialize testing data.
|
||||
"""
|
||||
class Cat(Originator):
|
||||
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
self.cat_class = Cat
|
||||
|
||||
def test_commit(self):
|
||||
"""
|
||||
Test the commit method.
|
||||
|
||||
@raise AssertionError: If the test fails.
|
||||
"""
|
||||
cat = self.cat_class('Tom')
|
||||
cat_memento = cat.commit()
|
||||
|
||||
self.assertDictEqual(cat.__dict__, cat_memento.state)
|
||||
|
||||
def test_rollback(self):
|
||||
"""
|
||||
Test the rollback method.
|
||||
|
||||
@raise AssertionError: If the test fails.
|
||||
"""
|
||||
cat = self.cat_class('Tom')
|
||||
cat_memento = cat.commit()
|
||||
|
||||
cat.name = 'jerry'
|
||||
cat.rollback(cat_memento)
|
||||
|
||||
self.assertEqual('Tom', cat.name)
|
||||
Reference in New Issue
Block a user