Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4e70c41
change: refactoring self->cls
Apr 25, 2016
070c2cf
change: refactor (work -> talk)
May 13, 2016
ee428bb
merge with faif/master
May 16, 2016
b4993f3
BF(PY2): use mock module if no unittest.mock is available
yarikoptic May 17, 2016
74fc693
BF: test_strategy -- use OS specific os.linesep + shebang
yarikoptic May 17, 2016
ebbacb4
ENH: have shebangs consistently in every file with __name__ == "__mai…
yarikoptic May 17, 2016
a0d3711
BF: fixing docstring to pass doctest in adapter.py and import print_f…
yarikoptic May 17, 2016
29dc431
rudimentary .travis.yml which also ignores flake8 failures for now
yarikoptic May 17, 2016
ef3dbe3
for uniformity -- no exec bit on delegation_pattern.py
yarikoptic May 17, 2016
8cc5924
BF: minor typo unit[t]est
yarikoptic May 17, 2016
c5ce565
BF/ENH: assure that foo.txt exists and no conflicts for demonstration
yarikoptic May 17, 2016
b36e630
BF: descriptors must be bound to class, not instance -- Revert "Adjus…
yarikoptic May 17, 2016
187c3bc
ENH: reduce sleep to 0.1 for consistency
yarikoptic May 17, 2016
6b2d7d1
ENH(TST): actually run all the scripts while testing on travis
yarikoptic May 17, 2016
63b9759
BF: moved running all the scripts via coverage into a separate helper…
yarikoptic May 17, 2016
1e82c2d
BF(PY3): use next() instead of .next() (PY3 only)
yarikoptic May 17, 2016
9a65401
TEMP workaround: flyweight is not compatible with Python3
yarikoptic May 17, 2016
e2a12b4
BF(TEMP): Disabled pypy for now -- gets stuck
yarikoptic May 17, 2016
8edfdcd
ENH: pragma: no cover for conditioning of mock imports
yarikoptic May 17, 2016
2893a03
BF: dedent few assertions out of with assertRaises cm
yarikoptic May 17, 2016
b3d6693
Merge branch 'pr-139'
yarikoptic May 17, 2016
126bbd9
BF(TST): fixing test_proxy for recent decrease of sleep, but also py …
yarikoptic May 17, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# vim ft=yaml
# travis-ci.org definition for python-patterns build
language: python

sudo: false

python:
- "2.7"
- "3.3"
- "3.4"
- "3.5"
# Disabled for now since cause more pain than gain
# - "pypy"
# - "pypy3"

cache:
- pip

install:
- travis_retry pip install -q coveralls codecov
- pip install flake8 # eventually worth

script:
# Run tests
- PYTHONPATH=. nosetests -s -v --with-doctest --with-cov --cover-package . --logging-level=INFO -v .
# Actually run all the scripts, contributing to coverage
- ./run_all.sh
# for now failure in flaking is ignored
- flake8 *py || echo "PEP8 the code"

after_success:
- coveralls
- codecov
13 changes: 5 additions & 8 deletions 3-tier.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ def __get__(self, obj, klas):
class BusinessLogic(object):
""" Business logic holding data store instances """

def __init__(self, data):
self.data = data
data = Data()

def product_list(self):
return self.data['products'].keys()
Expand All @@ -32,8 +31,8 @@ def product_information(self, product):
class Ui(object):
""" UI interaction class """

def __init__(self, logic):
self.business_logic = logic
def __init__(self):
self.business_logic = BusinessLogic()

def get_product_list(self):
print('PRODUCT LIST:')
Expand All @@ -54,9 +53,7 @@ def get_product_information(self, product):


def main():
data = Data()
logic = BusinessLogic(data)
ui = Ui(logic)
ui = Ui()
ui.get_product_list()
ui.get_product_information('cheese')
ui.get_product_information('eggs')
Expand All @@ -72,7 +69,7 @@ def main():
# cheese
# eggs
# milk
#
#
# (Fetching from Data Store)
# PRODUCT INFORMATION:
# Name: Cheese, Price: 2.00, Quantity: 10
Expand Down
2 changes: 2 additions & 0 deletions adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ class Adapter(object):
>>> objects = []
>>> dog = Dog()
>>> print(dog.__dict__)
{'name': 'Dog'}
>>> objects.append(Adapter(dog, make_noise=dog.bark))
>>> print(objects[0].original_dict())
{'name': 'Dog'}
>>> cat = Cat()
>>> objects.append(Adapter(cat, make_noise=cat.meow))
>>> human = Human()
Expand Down
2 changes: 1 addition & 1 deletion chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def delegate(self, requests):
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
cr.next()
next(cr)
return cr
return start

Expand Down
2 changes: 2 additions & 0 deletions chaining_method.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function

class Person(object):

def __init__(self, name, action):
Expand Down
26 changes: 18 additions & 8 deletions command.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-

import os

from os.path import lexists

class MoveFileCommand(object):

Expand All @@ -28,13 +28,23 @@ def main():
command_stack.append(MoveFileCommand('foo.txt', 'bar.txt'))
command_stack.append(MoveFileCommand('bar.txt', 'baz.txt'))

# they can be executed later on
for cmd in command_stack:
cmd.execute()

# and can also be undone at will
for cmd in reversed(command_stack):
cmd.undo()
# verify that none of the target files exist
assert(not lexists("foo.txt"))
assert(not lexists("bar.txt"))
assert(not lexists("baz.txt"))
try:
with open("foo.txt", "w"): # Creating the file
pass

# they can be executed later on
for cmd in command_stack:
cmd.execute()

# and can also be undone at will
for cmd in reversed(command_stack):
cmd.undo()
finally:
os.unlink("foo.txt")

if __name__ == "__main__":
main()
Expand Down
1 change: 1 addition & 0 deletions decorator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python
"""https://docs.python.org/2/library/functools.html#functools.wraps"""
"""https://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/739665#739665"""

Expand Down
Empty file modified delegation_pattern.py
100755 → 100644
Empty file.
2 changes: 1 addition & 1 deletion facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import time

SLEEP = 0.5
SLEEP = 0.1


# Complex Parts
Expand Down
5 changes: 5 additions & 0 deletions flyweight.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ def __init__(self, *args, **kwargs):


if __name__ == '__main__':
import sys
if sys.version_info[0] > 2:
sys.stderr.write("!!! This example is compatible only with Python 2 ATM !!!\n")
raise SystemExit(0)

# comment __new__ and uncomment __init__ to see the difference
c1 = Card('9', 'h')
c2 = Card('9', 'h')
Expand Down
6 changes: 3 additions & 3 deletions proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ def talk(self):
print("Proxy checking for Sales Manager availability")
if self.busy == 'No':
self.sales = SalesManager()
time.sleep(2)
time.sleep(0.1)
self.sales.talk()
else:
time.sleep(2)
time.sleep(0.1)
print("Sales Manager is busy")


class NoTalkProxy(Proxy):
def talk(self):
print("Proxy checking for Sales Manager availability")
time.sleep(2)
time.sleep(0.1)
print("This Sales Manager will not talk to you whether he/she is busy or not")


Expand Down
22 changes: 22 additions & 0 deletions run_all.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/bin/bash
#
# Little helper to run all the scripts, under python coverage if coverage is available
#

set -eu
failed=""

if which coverage > /dev/null; then
COVERAGE="`which coverage` run -a"
else
COVERAGE=''
fi
for f in [^_]*py; do
python $COVERAGE $f || failed+=" $f"
echo "I: done $f. Exit code $?"
done;

if [ ! -z "$failed" ]; then
echo "Failed: $failed";
exit 1
fi
1 change: 1 addition & 0 deletions state.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python
"""Implementation of the state pattern"""

# http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
Expand Down
1 change: 1 addition & 0 deletions strategy.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python
# http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern
# -written-in-python-the-sample-in-wikipedia
"""
Expand Down
5 changes: 4 additions & 1 deletion test_abstract_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
else:
import unittest

from unittest.mock import patch
try:
from unittest.mock import patch
except ImportError:
from mock import patch


class TestPetShop(unittest.TestCase):
Expand Down
1 change: 1 addition & 0 deletions test_adapter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python
from adapter import Dog, Cat, Human, Car, Adapter
import sys

Expand Down
1 change: 1 addition & 0 deletions test_borg.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python
from borg import Borg, YourBorg
import sys

Expand Down
8 changes: 6 additions & 2 deletions test_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
from bridge import DrawingAPI1, DrawingAPI2, CircleShape
from sys import version_info

if version_info < (2, 7):
if version_info < (2, 7): # pragma: no cover
import unittest2 as unittest
else:
import unittest

from unittest.mock import patch
try:
from unittest.mock import patch
except ImportError:
from mock import patch


class BridgeTest(unittest.TestCase):

Expand Down
1 change: 1 addition & 0 deletions test_command.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env python
from command import MoveFileCommand
import os, shutil, subprocess, sys

Expand Down
2 changes: 1 addition & 1 deletion test_flyweight.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from flyweight import Card
from sys import version_info

if version_info < (2, 7):
if version_info < (2, 7): # pragma: no cover
import unittest2 as unittest
else:
import unittest
Expand Down
16 changes: 10 additions & 6 deletions test_hsm.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
#!/usr/bin/env python
from hsm import HierachicalStateMachine, UnsupportedMessageType,\
UnsupportedState, UnsupportedTransition, Active, Standby, Suspect, Failed
from sys import version_info

if version_info < (2, 7):
if version_info < (2, 7): # pragma: no cover
import unittest2 as unittest
else:
import unittest

from unittest.mock import patch
try:
from unittest.mock import patch
except ImportError:
from mock import patch


class HsmMethodTest(unittest.TestCase):
Expand Down Expand Up @@ -74,18 +78,18 @@ def test_given_standby_on_message_fault_trigger_shall_set_suspect(cls):
def test_given_standby_on_message_diagnostics_failed_shall_raise_exception_and_keep_in_state(cls):
with cls.assertRaises(UnsupportedTransition) as context:
cls.hsm.on_message('diagnostics failed')
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)

def test_given_standby_on_message_diagnostics_passed_shall_raise_exception_and_keep_in_state(cls):
with cls.assertRaises(UnsupportedTransition) as context:
cls.hsm.on_message('diagnostics passed')
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)

def test_given_standby_on_message_operator_inservice_shall_raise_exception_and_keep_in_state(cls):
with cls.assertRaises(UnsupportedTransition) as context:
cls.hsm.on_message('operator inservice')
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)


if __name__ == "__main__":
unittest.main()
unittest.main()
7 changes: 5 additions & 2 deletions test_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@

if sys.version_info < (2, 7):
import unittest2 as unittest

else:
import unittest

from unittest.mock import patch
try:
from unittest.mock import patch
except ImportError:
from mock import patch


class TestSubject(unittest.TestCase):

Expand Down
Loading