Implemented Proxy design pattern.
This commit is contained in:
18
pypatterns/structural/proxy.py
Normal file
18
pypatterns/structural/proxy.py
Normal file
@@ -0,0 +1,18 @@
|
||||
class Proxy(object):
|
||||
"""
|
||||
Base Proxy class as part of the Proxy design pattern.
|
||||
"""
|
||||
def __init__(self, subject):
|
||||
"""
|
||||
Initialize a new proxy instance.
|
||||
|
||||
@param subject: The real subject this proxy calls upon.
|
||||
"""
|
||||
self._subject = subject
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
45
tests/structural_tests/test_proxy.py
Normal file
45
tests/structural_tests/test_proxy.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from unittest import TestCase
|
||||
from pypatterns.structural.proxy import Proxy
|
||||
|
||||
|
||||
class ProxyTestCase(TestCase):
|
||||
"""
|
||||
Unit testing class for the Proxy class.
|
||||
"""
|
||||
def setUp(self):
|
||||
"""
|
||||
Initialize testing data.
|
||||
"""
|
||||
class Car(object):
|
||||
|
||||
def drive_car(self):
|
||||
return 'drive car'
|
||||
|
||||
class Driver(object):
|
||||
|
||||
def __init__(self, age):
|
||||
self.age = age
|
||||
|
||||
class ProxyCar(Proxy):
|
||||
|
||||
def __init__(self, subject, driver):
|
||||
super().__init__(subject)
|
||||
self.driver = driver
|
||||
|
||||
def drive_car(self):
|
||||
if self.driver.age > 16:
|
||||
return self._subject.drive_car()
|
||||
else:
|
||||
return 'Driver is too young to drive'
|
||||
|
||||
self.proxy = ProxyCar(Car(), Driver(17))
|
||||
|
||||
def test_drive_car(self):
|
||||
"""
|
||||
Test the proxy with the drive car method.
|
||||
|
||||
@raise AssertionError: If the test fails.
|
||||
"""
|
||||
self.assertEqual('drive car', self.proxy.drive_car())
|
||||
self.proxy.driver.age = 15
|
||||
self.assertEqual('Driver is too young to drive', self.proxy.drive_car())
|
||||
Reference in New Issue
Block a user