Convenience methods in base model class
This change adds a BaseModel type which Plan inherits from along with implementations of __eq__ and __repr__ to assist with testing and debugging. The __repr__ is a compact yaml representation which starts with the class name. The __eq__ asserts the other is of the same type, and then compares the class __dict__ (which includes the class attributes) Change-Id: I3a6aafc680637b2ec379f206a731796c24d5c7bb
This commit is contained in:
@@ -14,8 +14,23 @@
|
||||
# under the License.
|
||||
import datetime
|
||||
|
||||
import yaml
|
||||
|
||||
class Plan(object):
|
||||
|
||||
class BaseModel(object):
|
||||
|
||||
def __repr__(self, *args, **kwargs):
|
||||
repr_ = {self.__class__.__name__: self.__dict__}
|
||||
return yaml.safe_dump(repr_, default_flow_style=True)
|
||||
|
||||
def __eq__(self, other):
|
||||
if not (isinstance(other, self.__class__) or
|
||||
isinstance(self, other.__class__)):
|
||||
return False
|
||||
return self.__dict__ == getattr(other, '__dict__')
|
||||
|
||||
|
||||
class Plan(BaseModel):
|
||||
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
@@ -16,6 +16,9 @@
|
||||
import datetime
|
||||
import time
|
||||
|
||||
import six
|
||||
import yaml
|
||||
|
||||
from tripleo_common.core.models import Plan
|
||||
from tripleo_common.tests import base
|
||||
|
||||
@@ -48,3 +51,20 @@ class ModelTest(base.TestCase):
|
||||
expected_date = datetime.datetime.fromtimestamp(
|
||||
float(self.timestamp))
|
||||
self.assertEqual(expected_date, plan.created_date(), "Date mismatch")
|
||||
|
||||
def test_eq(self):
|
||||
self.assertEqual(Plan('foo'), Plan('foo'))
|
||||
self.assertNotEqual(Plan('bar'), Plan('foo'))
|
||||
self.assertNotEqual(Plan('bar'), None)
|
||||
|
||||
class thing(object):
|
||||
pass
|
||||
|
||||
self.assertNotEqual(Plan('bar'), thing())
|
||||
|
||||
def test_repr(self):
|
||||
plan = Plan('foo')
|
||||
plan_str = six.text_type(plan)
|
||||
self.assertEqual({'Plan': {
|
||||
'files': {}, 'name': 'foo', 'metadata': {}
|
||||
}}, yaml.safe_load(plan_str))
|
||||
|
Reference in New Issue
Block a user