Skip to content

Commit b54cad9

Browse files
committed
Merge pull request faif#144 from yarikoptic/master
ENH+BF: fix up of some tests/docs to pass with python2.7, testing on travis, consistent shebanging,
2 parents ad59bd5 + 126bbd9 commit b54cad9

26 files changed

+252
-41
lines changed

.travis.yml

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# vim ft=yaml
2+
# travis-ci.org definition for python-patterns build
3+
language: python
4+
5+
sudo: false
6+
7+
python:
8+
- "2.7"
9+
- "3.3"
10+
- "3.4"
11+
- "3.5"
12+
# Disabled for now since cause more pain than gain
13+
# - "pypy"
14+
# - "pypy3"
15+
16+
cache:
17+
- pip
18+
19+
install:
20+
- travis_retry pip install -q coveralls codecov
21+
- pip install flake8 # eventually worth
22+
23+
script:
24+
# Run tests
25+
- PYTHONPATH=. nosetests -s -v --with-doctest --with-cov --cover-package . --logging-level=INFO -v .
26+
# Actually run all the scripts, contributing to coverage
27+
- ./run_all.sh
28+
# for now failure in flaking is ignored
29+
- flake8 *py || echo "PEP8 the code"
30+
31+
after_success:
32+
- coveralls
33+
- codecov

3-tier.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ def __get__(self, obj, klas):
1919
class BusinessLogic(object):
2020
""" Business logic holding data store instances """
2121

22-
def __init__(self, data):
23-
self.data = data
22+
data = Data()
2423

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

35-
def __init__(self, logic):
36-
self.business_logic = logic
34+
def __init__(self):
35+
self.business_logic = BusinessLogic()
3736

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

5554

5655
def main():
57-
data = Data()
58-
logic = BusinessLogic(data)
59-
ui = Ui(logic)
56+
ui = Ui()
6057
ui.get_product_list()
6158
ui.get_product_information('cheese')
6259
ui.get_product_information('eggs')
@@ -72,7 +69,7 @@ def main():
7269
# cheese
7370
# eggs
7471
# milk
75-
#
72+
#
7673
# (Fetching from Data Store)
7774
# PRODUCT INFORMATION:
7875
# Name: Cheese, Price: 2.00, Quantity: 10

adapter.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,10 @@ class Adapter(object):
4646
>>> objects = []
4747
>>> dog = Dog()
4848
>>> print(dog.__dict__)
49+
{'name': 'Dog'}
4950
>>> objects.append(Adapter(dog, make_noise=dog.bark))
5051
>>> print(objects[0].original_dict())
52+
{'name': 'Dog'}
5153
>>> cat = Cat()
5254
>>> objects.append(Adapter(cat, make_noise=cat.meow))
5355
>>> human = Human()

chain.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def delegate(self, requests):
5757
def coroutine(func):
5858
def start(*args, **kwargs):
5959
cr = func(*args, **kwargs)
60-
cr.next()
60+
next(cr)
6161
return cr
6262
return start
6363

chaining_method.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
33

4+
from __future__ import print_function
5+
46
class Person(object):
57

68
def __init__(self, name, action):

command.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# -*- coding: utf-8 -*-
33

44
import os
5-
5+
from os.path import lexists
66

77
class MoveFileCommand(object):
88

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

31-
# they can be executed later on
32-
for cmd in command_stack:
33-
cmd.execute()
34-
35-
# and can also be undone at will
36-
for cmd in reversed(command_stack):
37-
cmd.undo()
31+
# verify that none of the target files exist
32+
assert(not lexists("foo.txt"))
33+
assert(not lexists("bar.txt"))
34+
assert(not lexists("baz.txt"))
35+
try:
36+
with open("foo.txt", "w"): # Creating the file
37+
pass
38+
39+
# they can be executed later on
40+
for cmd in command_stack:
41+
cmd.execute()
42+
43+
# and can also be undone at will
44+
for cmd in reversed(command_stack):
45+
cmd.undo()
46+
finally:
47+
os.unlink("foo.txt")
3848

3949
if __name__ == "__main__":
4050
main()

decorator.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#!/usr/bin/env python
12
"""https://docs.python.org/2/library/functools.html#functools.wraps"""
23
"""https://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/739665#739665"""
34

delegation_pattern.py

100755100644
File mode changed.

facade.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import time
55

6-
SLEEP = 0.5
6+
SLEEP = 0.1
77

88

99
# Complex Parts

flyweight.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ def __init__(self, *args, **kwargs):
7474

7575

7676
if __name__ == '__main__':
77+
import sys
78+
if sys.version_info[0] > 2:
79+
sys.stderr.write("!!! This example is compatible only with Python 2 ATM !!!\n")
80+
raise SystemExit(0)
81+
7782
# comment __new__ and uncomment __init__ to see the difference
7883
c1 = Card('9', 'h')
7984
c2 = Card('9', 'h')

proxy.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,17 @@ def talk(self):
1818
print("Proxy checking for Sales Manager availability")
1919
if self.busy == 'No':
2020
self.sales = SalesManager()
21-
time.sleep(2)
21+
time.sleep(0.1)
2222
self.sales.talk()
2323
else:
24-
time.sleep(2)
24+
time.sleep(0.1)
2525
print("Sales Manager is busy")
2626

2727

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

3434

run_all.sh

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/bin/bash
2+
#
3+
# Little helper to run all the scripts, under python coverage if coverage is available
4+
#
5+
6+
set -eu
7+
failed=""
8+
9+
if which coverage > /dev/null; then
10+
COVERAGE="`which coverage` run -a"
11+
else
12+
COVERAGE=''
13+
fi
14+
for f in [^_]*py; do
15+
python $COVERAGE $f || failed+=" $f"
16+
echo "I: done $f. Exit code $?"
17+
done;
18+
19+
if [ ! -z "$failed" ]; then
20+
echo "Failed: $failed";
21+
exit 1
22+
fi

state.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#!/usr/bin/env python
12
"""Implementation of the state pattern"""
23

34
# http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/

strategy.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#!/usr/bin/env python
12
# http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern
23
# -written-in-python-the-sample-in-wikipedia
34
"""

test_abstract_factory.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@
99
else:
1010
import unittest
1111

12-
from unittest.mock import patch
12+
try:
13+
from unittest.mock import patch
14+
except ImportError:
15+
from mock import patch
1316

1417

1518
class TestPetShop(unittest.TestCase):

test_adapter.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#!/usr/bin/env python
12
from adapter import Dog, Cat, Human, Car, Adapter
23
import sys
34

test_borg.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#!/usr/bin/env python
12
from borg import Borg, YourBorg
23
import sys
34

test_bridge.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,16 @@
44
from bridge import DrawingAPI1, DrawingAPI2, CircleShape
55
from sys import version_info
66

7-
if version_info < (2, 7):
7+
if version_info < (2, 7): # pragma: no cover
88
import unittest2 as unittest
99
else:
1010
import unittest
1111

12-
from unittest.mock import patch
12+
try:
13+
from unittest.mock import patch
14+
except ImportError:
15+
from mock import patch
16+
1317

1418
class BridgeTest(unittest.TestCase):
1519

test_command.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#!/usr/bin/env python
12
from command import MoveFileCommand
23
import os, shutil, subprocess, sys
34

test_flyweight.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from flyweight import Card
55
from sys import version_info
66

7-
if version_info < (2, 7):
7+
if version_info < (2, 7): # pragma: no cover
88
import unittest2 as unittest
99
else:
1010
import unittest

test_hsm.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
1+
#!/usr/bin/env python
12
from hsm import HierachicalStateMachine, UnsupportedMessageType,\
23
UnsupportedState, UnsupportedTransition, Active, Standby, Suspect, Failed
34
from sys import version_info
45

5-
if version_info < (2, 7):
6+
if version_info < (2, 7): # pragma: no cover
67
import unittest2 as unittest
78
else:
89
import unittest
910

10-
from unittest.mock import patch
11+
try:
12+
from unittest.mock import patch
13+
except ImportError:
14+
from mock import patch
1115

1216

1317
class HsmMethodTest(unittest.TestCase):
@@ -74,18 +78,18 @@ def test_given_standby_on_message_fault_trigger_shall_set_suspect(cls):
7478
def test_given_standby_on_message_diagnostics_failed_shall_raise_exception_and_keep_in_state(cls):
7579
with cls.assertRaises(UnsupportedTransition) as context:
7680
cls.hsm.on_message('diagnostics failed')
77-
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
81+
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
7882

7983
def test_given_standby_on_message_diagnostics_passed_shall_raise_exception_and_keep_in_state(cls):
8084
with cls.assertRaises(UnsupportedTransition) as context:
8185
cls.hsm.on_message('diagnostics passed')
82-
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
86+
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
8387

8488
def test_given_standby_on_message_operator_inservice_shall_raise_exception_and_keep_in_state(cls):
8589
with cls.assertRaises(UnsupportedTransition) as context:
8690
cls.hsm.on_message('operator inservice')
87-
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
91+
cls.assertEqual(isinstance(cls.hsm._current_state, Standby), True)
8892

8993

9094
if __name__ == "__main__":
91-
unittest.main()
95+
unittest.main()

test_observer.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@
77

88
if sys.version_info < (2, 7):
99
import unittest2 as unittest
10-
1110
else:
1211
import unittest
1312

14-
from unittest.mock import patch
13+
try:
14+
from unittest.mock import patch
15+
except ImportError:
16+
from mock import patch
17+
1518

1619
class TestSubject(unittest.TestCase):
1720

0 commit comments

Comments
 (0)