Skip to content

Instantly share code, notes, and snippets.

@RWJMurphy
Last active April 27, 2016 17:44
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 RWJMurphy/153c231f07ff232129fc92dc9457c11c to your computer and use it in GitHub Desktop.
Save RWJMurphy/153c231f07ff232129fc92dc9457c11c to your computer and use it in GitHub Desktop.
class Composed:
"""Composable class."""
def __init__(self, components=None):
self.__components = []
if components:
self.register_components(components)
def register_components(self, components):
for component in components:
self.register_component(component)
def register_component(self, component):
self.__components.append(component)
for name in dir(component):
if name.startswith('__'):
continue
assert name not in self.__dict__
setattr(self, name, getattr(component, name))
import pytest
from .composed import Composed
class SimpleAttributeComponent:
def __init__(self):
self.attribute = True
class SimpleFunctionComponent:
def function(self):
return True
class ClassMethodComponent():
@classmethod
def classmethod(cls):
return 'classmethod'
class StaticMethodComponent():
@staticmethod
def staticmethod():
return 'staticmethod'
class AttributeConflictComponent:
def __init__(self):
self.attribute = False
class FunctionConflictComponent:
def function(self):
return False
class SimpleComposed(Composed):
def __init__(self):
super().__init__()
self.register_components([
SimpleAttributeComponent(), SimpleFunctionComponent(),
ClassMethodComponent(), StaticMethodComponent()
])
class AttributeComponent():
def __init__(self):
self.attribute = "component"
def get_attribute(self):
return self.attribute
class ComposedState(Composed):
def __init__(self):
super().__init__([AttributeComponent()])
self.attribute = "composed"
class ConflictedAttributeComposed(SimpleComposed):
def __init__(self):
super().__init__()
self.register_component(AttributeConflictComponent())
class ConflictedFunctionComposed(SimpleComposed):
def __init__(self):
super().__init__()
self.register_component(FunctionConflictComponent())
def test_simple_atrribute():
composed = SimpleComposed()
assert composed.attribute
with pytest.raises(AttributeError):
composed.not_attribute
def test_simple_function():
composed = SimpleComposed()
assert composed.function()
with pytest.raises(AttributeError):
composed.not_function()
def test_simple_classmethod():
assert SimpleComposed().classmethod() == 'classmethod'
def test_simple_staticmethod():
assert SimpleComposed().staticmethod() == 'staticmethod'
def test_attribute_conflict():
with pytest.raises(AssertionError):
ConflictedAttributeComposed()
def test_function_conflict():
with pytest.raises(AssertionError):
ConflictedFunctionComposed()
def test_component_state():
composed = ComposedState()
assert composed.get_attribute() == "component"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment