Commit ed87506a authored by Hanno Schlichting's avatar Hanno Schlichting

flake8

parent 036d773a
......@@ -27,58 +27,65 @@ from DateTime.DateTime import DateTime
from ExtensionClass import Base
from zExceptions import Redirect
class TemporalParadox(Exception):
pass
class HistorySelectionError(Exception):
pass
class HystoryJar:
"""A ZODB Connection-like object that provides access to data
but prevents history from being changed."""
def __init__(self, base):
self.__base__=base
self.__base__ = base
def __getattr__(self, name):
return getattr(self.__base__, name)
def commit(self, object, transaction):
if object._p_changed:
raise TemporalParadox, "You can't change history!"
raise TemporalParadox("You can't change history!")
def abort(*args, **kw): pass
def abort(*args, **kw):
pass
tpc_begin = tpc_finish = abort
def historicalRevision(self, serial):
state=self._p_jar.oldstate(self, serial)
rev=self.__class__.__basicnew__()
rev._p_jar=HystoryJar(self._p_jar)
rev._p_oid=self._p_oid
rev._p_serial=serial
state = self._p_jar.oldstate(self, serial)
rev = self.__class__.__basicnew__()
rev._p_jar = HystoryJar(self._p_jar)
rev._p_oid = self._p_oid
rev._p_serial = serial
rev.__setstate__(state)
rev._p_changed=0
rev._p_changed = 0
return rev
class Historian(Implicit):
"""An Historian's job is to find hysterical revisions of
objects, given a time."""
def __getitem__(self, key):
self=self.aq_parent
self = self.aq_parent
serial=apply(pack, ('>HHHH',)+tuple(map(int, key.split('.'))))
serial = pack(*('>HHHH',) + tuple(map(int, key.split('.'))))
if serial == self._p_serial:
return self
if serial == self._p_serial: return self
rev=historicalRevision(self, serial)
rev = historicalRevision(self, serial)
return rev.__of__(self.aq_parent)
def manage_workspace(self, REQUEST):
"We aren't real, so we delegate to that that spawned us!"
raise Redirect, REQUEST['URL2']+'/manage_change_history_page'
raise Redirect(REQUEST['URL2'] + '/manage_change_history_page')
class Historical(Base):
"""Mix-in class to provide a veiw that shows hystorical changes
......@@ -94,10 +101,10 @@ class Historical(Base):
security = ClassSecurityInfo()
HistoricalRevisions=Historian()
HistoricalRevisions = Historian()
manage_options=(
{'label':'History', 'action':'manage_change_history_page'},
manage_options = (
{'label': 'History', 'action': 'manage_change_history_page'},
)
security.declareProtected(view_history, 'manage_change_history_page')
......@@ -108,63 +115,65 @@ class Historical(Base):
security.declareProtected(view_history, 'manage_change_history')
def manage_change_history(self):
first=0
last=20
request=getattr(self, 'REQUEST', None)
first = 0
last = 20
request = getattr(self, 'REQUEST', None)
if request is not None:
first=request.get('first_transaction', first)
last=request.get('last_transaction',last)
first = request.get('first_transaction', first)
last = request.get('last_transaction', last)
r=self._p_jar.db().history(self._p_oid, size=last)
r = self._p_jar.db().history(self._p_oid, size=last)
if r is None:
# storage doesn't support history
return ()
r=r[first:]
r = r[first:]
for d in r:
d['time']=DateTime(d['time'])
d['key']='.'.join(map(str, unpack(">HHHH", d['tid'])))
d['time'] = DateTime(d['time'])
d['key'] = '.'.join(map(str, unpack(">HHHH", d['tid'])))
return r
def manage_beforeHistoryCopy(self): pass # ? (Hook)
def manage_beforeHistoryCopy(self):
pass # ? (Hook)
def manage_historyCopy(self, keys=[], RESPONSE=None, URL1=None):
"Copy a selected revision to the present"
if not keys:
raise HistorySelectionError, (
raise HistorySelectionError(
"No historical revision was selected.<p>")
if len(keys) > 1:
raise HistorySelectionError, (
raise HistorySelectionError(
"Only one historical revision can be "
"copied to the present.<p>")
key=keys[0]
serial=apply(pack, ('>HHHH',)+tuple(map(int, key.split('.'))))
key = keys[0]
serial = pack(*('>HHHH',) + tuple(map(int, key.split('.'))))
if serial != self._p_serial:
self.manage_beforeHistoryCopy()
state=self._p_jar.oldstate(self, serial)
state = self._p_jar.oldstate(self, serial)
base = aq_base(self)
base._p_activate() # make sure we're not a ghost
base.__setstate__(state) # change the state
base._p_changed = True # marke object as dirty
base._p_changed = True # mark object as dirty
self.manage_afterHistoryCopy()
if RESPONSE is not None and URL1 is not None:
RESPONSE.redirect(URL1+'/manage_workspace')
def manage_afterHistoryCopy(self): pass # ? (Hook)
RESPONSE.redirect(URL1 + '/manage_workspace')
def manage_afterHistoryCopy(self):
pass # ? (Hook)
_manage_historyComparePage = DTMLFile(
'dtml/historyCompare', globals(), management_view='History')
security.declareProtected(view_history, 'manage_historyCompare')
def manage_historyCompare(self, rev1, rev2, REQUEST,
historyComparisonResults=''):
dt1=DateTime(rev1._p_mtime)
dt2=DateTime(rev2._p_mtime)
dt1 = DateTime(rev1._p_mtime)
dt2 = DateTime(rev2._p_mtime)
return self._manage_historyComparePage(
self, REQUEST,
dt1=dt1, dt2=dt2,
......@@ -174,31 +183,31 @@ class Historical(Base):
def manage_historicalComparison(self, REQUEST, keys=[]):
"Compare two selected revisions"
if not keys:
raise HistorySelectionError, (
raise HistorySelectionError(
"No historical revision was selected.<p>")
if len(keys) > 2:
raise HistorySelectionError, (
raise HistorySelectionError(
"Only two historical revision can be compared<p>")
serial=apply(pack, ('>HHHH',)+tuple(map(int, keys[-1].split('.'))))
rev1=historicalRevision(self, serial)
serial = pack(*('>HHHH',) + tuple(map(int, keys[-1].split('.'))))
rev1 = historicalRevision(self, serial)
if len(keys)==2:
serial=apply(pack,
('>HHHH',)+tuple(map(int, keys[0].split('.'))))
if len(keys) == 2:
serial = pack(*('>HHHH',) + tuple(map(int, keys[0].split('.'))))
rev2=historicalRevision(self, serial)
rev2 = historicalRevision(self, serial)
else:
rev2=self
rev2 = self
return self.manage_historyCompare(rev1, rev2, REQUEST)
InitializeClass(Historical)
def dump(tag, x, lo, hi, r):
r1=[]
r2=[]
for i in xrange(lo, hi):
r1 = []
r2 = []
for i in range(lo, hi):
r1.append(tag)
r2.append(x[i])
r.append("<tr>\n"
......@@ -207,21 +216,20 @@ def dump(tag, x, lo, hi, r):
"</tr>\n"
% ('\n'.join(r1), escape('\n'.join(r2))))
def replace(x, xlo, xhi, y, ylo, yhi, r):
rx1=[]
rx2=[]
for i in xrange(xlo, xhi):
def replace(x, xlo, xhi, y, ylo, yhi, r):
rx1 = []
rx2 = []
for i in range(xlo, xhi):
rx1.append('-')
rx2.append(x[i])
ry1=[]
ry2=[]
for i in xrange(ylo, yhi):
ry1 = []
ry2 = []
for i in range(ylo, yhi):
ry1.append('+')
ry2.append(y[i])
r.append("<tr>\n"
"<td><pre>\n%s\n%s\n</pre></td>\n"
"<td><pre>\n%s\n%s\n</pre></td>\n"
......@@ -229,13 +237,14 @@ def replace(x, xlo, xhi, y, ylo, yhi, r):
% ('\n'.join(rx1), '\n'.join(ry1),
escape('\n'.join(rx2)), escape('\n'.join(ry2))))
def html_diff(s1, s2):
a=s1.split('\n')
b=s2.split('\n')
cruncher=difflib.SequenceMatcher()
cruncher.set_seqs(a,b)
a = s1.split('\n')
b = s2.split('\n')
cruncher = difflib.SequenceMatcher()
cruncher.set_seqs(a, b)
r=['<table border=1>']
r = ['<table border=1>']
for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
if tag == 'replace':
replace(a, alo, ahi, b, blo, bhi, r)
......@@ -246,7 +255,7 @@ def html_diff(s1, s2):
elif tag == 'equal':
dump(' ', a, alo, ahi, r)
else:
raise ValueError, 'unknown tag ' + `tag`
raise ValueError('unknown tag %r' % tag)
r.append('</table>')
return '\n'.join(r)
......@@ -95,20 +95,21 @@ See module comments for details and programmatic interface.
# is sent to stdout. Or you can call main(args), passing what would
# have been in sys.argv[1:] had the cmd-line form been used.
import re
TRACE = 0
# define what "junk" means
import re
def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
return pat(line) is not None
def IS_CHARACTER_JUNK(ch, ws=" \t"):
return ch in ws
del re
class SequenceMatcher:
class SequenceMatcher(object):
def __init__(self, isjunk=None, a='', b=''):
# Members:
# a
......@@ -277,9 +278,9 @@ class SequenceMatcher:
continue
if j >= bhi:
break
k = newj2len[j] = j2lenget(j-1, 0) + 1
k = newj2len[j] = j2lenget(j - 1, 0) + 1
if k > bestsize:
besti, bestj, bestsize = i-k+1, j-k+1, k
besti, bestj, bestsize = i - k + 1, j - k + 1, k
j2len = newj2len
# Now that we have a wholly interesting match (albeit possibly
......@@ -290,17 +291,14 @@ class SequenceMatcher:
# interesting match, this is clearly the right thing to do,
# because no other kind of match is possible in the regions.
while besti > alo and bestj > blo and \
isbjunk(b[bestj-1]) and \
a[besti-1] == b[bestj-1]:
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
while besti+bestsize < ahi and bestj+bestsize < bhi and \
isbjunk(b[bestj+bestsize]) and \
a[besti+bestsize] == b[bestj+bestsize]:
isbjunk(b[bestj - 1]) and \
a[besti - 1] == b[bestj - 1]:
besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1
while besti + bestsize < ahi and bestj + bestsize < bhi and \
isbjunk(b[bestj + bestsize]) and \
a[besti + bestsize] == b[bestj + bestsize]:
bestsize = bestsize + 1
if TRACE:
print "get_matching_blocks", alo, ahi, blo, bhi
print " returns", besti, bestj, bestsize
return besti, bestj, bestsize
def get_matching_blocks(self):
......@@ -309,9 +307,7 @@ class SequenceMatcher:
self.matching_blocks = []
la, lb = len(self.a), len(self.b)
self.__helper(0, la, 0, lb, self.matching_blocks)
self.matching_blocks.append( (la, lb, 0) )
if TRACE:
print '*** matching blocks', self.matching_blocks
self.matching_blocks.append((la, lb, 0))
return self.matching_blocks
# builds list of matching blocks covering a[alo:ahi] and
......@@ -326,8 +322,8 @@ class SequenceMatcher:
if alo < i and blo < j:
self.__helper(alo, i, blo, j, answer)
answer.append(x)
if i+k < ahi and j+k < bhi:
self.__helper(i+k, ahi, j+k, bhi, answer)
if i + k < ahi and j + k < bhi:
self.__helper(i + k, ahi, j + k, bhi, answer)
def ratio(self):
"""Return a measure of the sequences' similarity (float in [0,1]).
......@@ -392,25 +388,29 @@ class SequenceMatcher:
elif j < bj:
tag = 'insert'
if tag:
answer.append( (tag, i, ai, j, bj) )
i, j = ai+size, bj+size
answer.append((tag, i, ai, j, bj))
i, j = ai + size, bj + size
# the list of matching blocks is terminated by a
# sentinel with size 0
if size:
answer.append( ('equal', ai, i, bj, j) )
answer.append(('equal', ai, i, bj, j))
return answer
# meant for dumping lines
def dump(tag, x, lo, hi):
# meant for dumping lines
for i in xrange(lo, hi):
print tag, x[i],
print(tag, x[i])
# figure out which mark to stick under characters in lines that
# have changed (blank = same, - = deleted, + = inserted, ^ = replaced)
_combine = { ' ': ' ',
_combine = {
' ': ' ',
'. ': '-',
' .': '+',
'..': '^' }
'..': '^',
}
def plain_replace(a, alo, ahi, b, blo, bhi):
assert alo < ahi and blo < bhi
......@@ -428,12 +428,8 @@ def plain_replace(a, alo, ahi, b, blo, bhi):
# used as a synch point, and intraline difference marking is done on
# the similar pair. Lots of work, but often worth it.
def fancy_replace(a, alo, ahi, b, blo, bhi):
if TRACE:
print '*** fancy_replace', alo, ahi, blo, bhi
dump('>', a, alo, ahi)
dump('<', b, blo, bhi)
def fancy_replace(a, alo, ahi, b, blo, bhi):
# don't synch up unless the lines have a similarity score of at
# least cutoff; best_ratio tracks the best score seen so far
best_ratio, cutoff = 0.74, 0.75
......@@ -475,13 +471,6 @@ def fancy_replace(a, alo, ahi, b, blo, bhi):
# there's a close pair, so forget the identical pair (if any)
eqi = None
# a[best_i] very similar to b[best_j]; eqi is None iff they're not
# identical
if TRACE:
print '*** best_ratio', best_ratio, best_i, best_j
dump('>', a, best_i, best_i+1)
dump('<', b, best_j, best_j+1)
# pump out diffs from before the synch point
fancy_helper(a, alo, best_i, b, blo, best_j)
......@@ -504,13 +493,13 @@ def fancy_replace(a, alo, ahi, b, blo, bhi):
atags = atags + ' ' * la
btags = btags + ' ' * lb
else:
raise ValueError, 'unknown tag ' + `tag`
raise ValueError('unknown tag %r' % tag)
la, lb = len(atags), len(btags)
if la < lb:
atags = atags + ' ' * (lb - la)
elif lb < la:
btags = btags + ' ' * (la - lb)
combined = map(lambda x,y: _combine[x+y], atags, btags)
combined = map(lambda x, y: _combine[x + y], atags, btags)
print '-', aelt, '+', belt, '?', \
''.join(combined).rstrip()
else:
......@@ -518,7 +507,8 @@ def fancy_replace(a, alo, ahi, b, blo, bhi):
print ' ', aelt,
# pump out diffs from after the synch point
fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
fancy_helper(a, best_i + 1, ahi, b, best_j + 1, bhi)
def fancy_helper(a, alo, ahi, b, blo, bhi):
if alo < ahi:
......@@ -529,6 +519,7 @@ def fancy_helper(a, alo, ahi, b, blo, bhi):
elif blo < bhi:
dump('+', b, blo, bhi)
def fail(msg):
import sys
out = sys.stderr.write
......@@ -536,23 +527,27 @@ def fail(msg):
out(__doc__)
return 0
# open a file & return the file object; gripe and return 0 if it
# couldn't be opened
def fopen(fname):
# open a file & return the file object; gripe and return 0 if it
# couldn't be opened
try:
return open(fname, 'r')
except IOError, detail:
return fail("couldn't open " + fname + ": " + str(detail))
# open two files & spray the diff to stdout; return false iff a problem
def fcompare(f1name, f2name):
# open two files & spray the diff to stdout; return false iff a problem
f1 = fopen(f1name)
f2 = fopen(f2name)
if not f1 or not f2:
return 0
a = f1.readlines(); f1.close()
b = f2.readlines(); f2.close()
a = f1.readlines()
f1.close()
b = f2.readlines()
f2.close()
cruncher = SequenceMatcher(IS_LINE_JUNK, a, b)
for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
......@@ -565,62 +560,6 @@ def fcompare(f1name, f2name):
elif tag == 'equal':
dump(' ', a, alo, ahi)
else:
raise ValueError, 'unknown tag ' + `tag`
raise ValueError('unknown tag %r' + tag)
return 1
# crack args (sys.argv[1:] is normal) & compare;
# return false iff a problem
def main(args):
import getopt
try:
opts, args = getopt.getopt(args, "qr:")
except getopt.error, detail:
return fail(str(detail))
noisy = 1
qseen = rseen = 0
for opt, val in opts:
if opt == "-q":
qseen = 1
noisy = 0
elif opt == "-r":
rseen = 1
whichfile = val
if qseen and rseen:
return fail("can't specify both -q and -r")
if rseen:
if args:
return fail("no args allowed with -r option")
if whichfile in "12":
restore(whichfile)
return 1
return fail("-r value must be 1 or 2")
if len(args) != 2:
return fail("need 2 filename args")
f1name, f2name = args
if noisy:
print '-:', f1name
print '+:', f2name
return fcompare(f1name, f2name)
def restore(which):
import sys
tag = {"1": "- ", "2": "+ "}[which]
prefixes = (" ", tag)
for line in sys.stdin.readlines():
if line[:2] in prefixes:
print line[2:],
if __name__ == '__main__':
import sys
args = sys.argv[1:]
if "-profile" in args:
import profile, pstats
args.remove("-profile")
statf = "ndiff.pro"
profile.run("main(args)", statf)
stats = pstats.Stats(statf)
stats.strip_dirs().sort_stats('time').print_stats()
else:
main(args)
......@@ -10,12 +10,6 @@
# FOR A PARTICULAR PURPOSE
#
##############################################################################
"""Tests demonstrating consequences of guarded_getattr fix from 2004/08/07
http://mail.zope.org/pipermail/zope-checkins/2004-August/028152.html
http://zope.org/Collectors/CMF/259
"""
import unittest
......@@ -41,6 +35,7 @@ class AllowedItem(SimpleItem):
InitializeClass(AllowedItem)
class DeniedItem(SimpleItem):
id = 'denied'
security = ClassSecurityInfo()
......@@ -48,6 +43,7 @@ class DeniedItem(SimpleItem):
InitializeClass(DeniedItem)
class ProtectedItem(SimpleItem):
id = 'protected'
security = ClassSecurityInfo()
......@@ -74,7 +70,8 @@ class TestGetAttr(unittest.TestCase):
self.app.manage_addFolder('plain_folder')
# We also want to be able to acquire simple attributes
self.app.manage_addProperty(id='simple_type', type='string', value='a string')
self.app.manage_addProperty(
id='simple_type', type='string', value='a string')
# Set up a subfolder and the objects we want to acquire from
self.app.manage_addFolder('subfolder')
......@@ -142,7 +139,6 @@ class TestGetAttr(unittest.TestCase):
class TestGetAttrAnonymous(TestGetAttr):
# Run all tests again as Anonymous User
def setUp(self):
......@@ -151,23 +147,15 @@ class TestGetAttrAnonymous(TestGetAttr):
noSecurityManager()
class TestGetAttr_c(TestGetAttr):
class TestGetAttrC(TestGetAttr):
def setUp(self):
TestGetAttr.setUp(self)
self.guarded_getattr = guarded_getattr_c
class TestGetAttrAnonymous_c(TestGetAttrAnonymous):
class TestGetAttrAnonymousC(TestGetAttrAnonymous):
def setUp(self):
TestGetAttrAnonymous.setUp(self)
self.guarded_getattr = guarded_getattr_c
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestGetAttr))
suite.addTest(unittest.makeSuite(TestGetAttrAnonymous))
suite.addTest(unittest.makeSuite(TestGetAttr_c))
suite.addTest(unittest.makeSuite(TestGetAttrAnonymous_c))
return suite
......@@ -47,27 +47,27 @@ class ApplicationTests(unittest.TestCase):
self.assertEqual(app.title_and_id(), 'Other')
self.assertEqual(app.title_or_id(), 'Other')
def test___bobo_traverse__attribute_hit(self):
def test_bobo_traverse_attribute_hit(self):
app = self._makeOne()
app.NAME = 'attribute'
app._getOb = lambda x, y: x
request = {}
self.assertEqual(app.__bobo_traverse__(request, 'NAME'), 'attribute')
def test___bobo_traverse__attribute_miss_key_hit(self):
def test_bobo_traverse_attribute_miss_key_hit(self):
app = self._makeOne()
app._getOb = lambda x, y: x
app._objects = [{'id': 'OTHER', 'meta_type': None}]
request = {}
self.assertEqual(app.__bobo_traverse__(request, 'OTHER'), 'OTHER')
def test___bobo_traverse__attribute_key_miss_R_M_default_real_request(self):
def test_bobo_traverse_attribute_key_miss_R_M_default_real_request(self):
from UserDict import UserDict
request = UserDict()
class _Response:
def notFoundError(self, msg):
1/0
1 / 0
request.RESPONSE = _Response()
app = self._makeOne()
......@@ -76,21 +76,21 @@ class ApplicationTests(unittest.TestCase):
self.assertRaises(ZeroDivisionError,
app.__bobo_traverse__, request, 'NONESUCH')
def test___bobo_traverse__attribute_key_miss_R_M_default_fake_request(self):
def test_bobo_traverse_attribute_key_miss_R_M_default_fake_request(self):
app = self._makeOne()
app._getOb = _noWay
request = {}
self.assertRaises(KeyError, app.__bobo_traverse__, request, 'NONESUCH')
def test___bobo_traverse__attribute_key_miss_R_M_is_GET(self):
def test_bobo_traverse_attribute_key_miss_R_M_is_GET(self):
app = self._makeOne()
app._getOb = _noWay
request = {'REQUEST_METHOD': 'GET'}
self.assertRaises(KeyError, app.__bobo_traverse__, request, 'NONESUCH')
def test___bobo_traverse__attribute_key_miss_R_M_not_GET_POST(self):
def test_bobo_traverse_attribute_key_miss_R_M_not_GET_POST(self):
from OFS import bbb
if bbb.HAS_ZSERVER:
from webdav.NullResource import NullResource
......
......@@ -32,9 +32,3 @@ class CacheTests(unittest.TestCase):
# The parent_cache should still trigger managersExist
self.assertTrue(managersExist(root.child.child_content))
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(CacheTests))
return suite
......@@ -14,6 +14,7 @@
import unittest
from Testing import ZopeTestCase
class TestRecursiveChangeOwnership(ZopeTestCase.ZopeTestCase):
user_name2 = "dumdidum"
user_pass2 = "dumdidum"
......@@ -27,10 +28,10 @@ class TestRecursiveChangeOwnership(ZopeTestCase.ZopeTestCase):
# remember user objects
# is the __of__() call correct? is it needed? without it ownerInfo in
# owner.py throws an AttributeError ...
self.user1 = self.folder['acl_users'].getUser(ZopeTestCase.user_name
).__of__(self.folder)
self.user2 = self.folder['acl_users'].getUser(self.user_name2
).__of__(self.folder)
self.user1 = self.folder['acl_users'].getUser(
ZopeTestCase.user_name).__of__(self.folder)
self.user2 = self.folder['acl_users'].getUser(
self.user_name2).__of__(self.folder)
self.folder.changeOwnership(self.user1)
......
This diff is collapsed.
......@@ -9,9 +9,3 @@ class TestFTPInterface(unittest.TestCase):
from zope.interface.verify import verifyClass
verifyClass(IFTPAccess, FTPInterface)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(TestFTPInterface),
))
......@@ -65,13 +65,13 @@ class HistoryTests(unittest.TestCase):
def test_manage_change_history(self):
r = self.hi.manage_change_history()
self.assertEqual(len(r),3) # three transactions
self.assertEqual(len(r), 3) # three transactions
for i in range(3):
entry = r[i]
# check no new keys show up without testing
self.assertEqual(len(entry.keys()),6)
self.assertEqual(len(entry.keys()), 6)
# the transactions are in newest-first order
self.assertEqual(entry['description'],'Change %i' % (3-i))
self.assertEqual(entry['description'], 'Change %i' % (3 - i))
self.assertTrue('key' in entry)
# lets not assume the size will stay the same forever
self.assertTrue('size' in entry)
......@@ -79,24 +79,18 @@ class HistoryTests(unittest.TestCase):
self.assertTrue('time' in entry)
if i:
# check times are increasing
self.assertTrue(entry['time']<r[i-1]['time'])
self.assertEqual(entry['user_name'],'')
self.assertTrue(entry['time'] < r[i - 1]['time'])
self.assertEqual(entry['user_name'], '')
def test_manage_historyCopy(self):
# we assume this works 'cos it's tested above
r = self.hi.manage_change_history()
# now we do the copy
self.hi.manage_historyCopy(
keys=[r[2]['key']]
)
self.hi.manage_historyCopy(keys=[r[2]['key']])
# do a commit, just like ZPublisher would
transaction.commit()
# check the body is as it should be, we assume (hopefully not foolishly)
# check the body is as it should be, we assume
# (hopefully not foolishly)
# that all other attributes will behave the same
self.assertEqual(self.hi.title,
'First title')
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(HistoryTests))
return suite
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -27,6 +27,7 @@ class TestItem(unittest.TestCase):
class RESPONSE(object):
handle_errors = True
item = self._makeOne()
def _raise_during_standard_error_message(*args, **kw):
raise ZeroDivisionError('testing')
item.standard_error_message = _raise_during_standard_error_message
......@@ -36,7 +37,7 @@ class TestItem(unittest.TestCase):
error_value='simple',
REQUEST=REQUEST(),
)
except:
except Exception:
import sys
self.assertEqual(sys.exc_info()[0], OverflowError)
value = sys.exc_info()[1]
......@@ -45,10 +46,12 @@ class TestItem(unittest.TestCase):
def test_raise_StandardErrorMessage_TaintedString_errorValue(self):
from AccessControl.tainted import TaintedString
class REQUEST(object):
class RESPONSE(object):
handle_errors = True
item = self._makeOne()
def _raise_during_standard_error_message(*args, **kw):
raise ZeroDivisionError('testing')
item.standard_error_message = _raise_during_standard_error_message
......@@ -58,7 +61,7 @@ class TestItem(unittest.TestCase):
error_value=TaintedString('<simple>'),
REQUEST=REQUEST(),
)
except:
except Exception:
import sys
self.assertEqual(sys.exc_info()[0], OverflowError)
value = sys.exc_info()[1]
......@@ -113,10 +116,3 @@ class TestSimpleItem(unittest.TestCase):
REQUEST=REQUEST())
self.assertEquals(sem.kw.get('error_type'), 'BadRequest')
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(TestItem),
unittest.makeSuite(TestItem_w__name__),
unittest.makeSuite(TestSimpleItem),
))
This diff is collapsed.
......@@ -91,23 +91,21 @@ class TestsOfBroken(unittest.TestCase):
"_p_mtime",
"_p_oid",
"_p_serial",
"_p_state",
]
"_p_state"]
PERSISTENCE_METHODS = ["_p_deactivate",
"_p_activate",
"_p_invalidate",
"_p_getattr",
"_p_setattr",
"_p_delattr",
]
"_p_delattr"]
inst = Broken(self, OID, ('Products.MyProduct.MyClass', 'MyClass'))
for attr_name in PERSISTENCE_ATTRS:
attr = getattr(inst, attr_name) # doesn't raise
getattr(inst, attr_name) # doesn't raise
for meth_name in PERSISTENCE_METHODS:
meth = getattr(inst, meth_name) # doesn't raise
getattr(inst, meth_name) # doesn't raise
class TestsIntegratedBroken(base.TestCase):
......@@ -146,7 +144,3 @@ def test_suite():
suite.addTest(unittest.makeSuite(TestsOfBroken))
suite.addTest(unittest.makeSuite(TestsIntegratedBroken))
return suite
def main():
unittest.main(defaultTest='test_suite')
......@@ -23,54 +23,70 @@ from OFS.OrderedFolder import OrderedFolder
from zope.component import testing, eventtesting
def setUp(test):
testing.setUp(test)
eventtesting.setUp(test)
class DontComplain(object):
def _verifyObjectPaste(self, object, validate_src=1):
pass
def cb_isMoveable(self):
return True
def cb_isCopyable(self):
return True
class NotifyBase(DontComplain):
def manage_afterAdd(self, item, container):
print 'old manage_afterAdd %s %s %s' % (self.getId(), item.getId(),
container.getId())
print('old manage_afterAdd %s %s %s' % (
self.getId(), item.getId(), container.getId()))
super(NotifyBase, self).manage_afterAdd(item, container)
manage_afterAdd.__five_method__ = True # Shut up deprecation warnings
def manage_beforeDelete(self, item, container):
super(NotifyBase, self).manage_beforeDelete(item, container)
print 'old manage_beforeDelete %s %s %s' % (self.getId(), item.getId(),
container.getId())
print('old manage_beforeDelete %s %s %s' % (
self.getId(), item.getId(), container.getId()))
manage_beforeDelete.__five_method__ = True # Shut up deprecation warnings
def manage_afterClone(self, item):
print 'old manage_afterClone %s %s' % (self.getId(), item.getId())
print('old manage_afterClone %s %s' % (self.getId(), item.getId()))
super(NotifyBase, self).manage_afterClone(item)
manage_afterClone.__five_method__ = True # Shut up deprecation warnings
class MyApp(Folder):
def getPhysicalRoot(self):
return self
class MyFolder(NotifyBase, Folder):
pass
class MyOrderedFolder(NotifyBase, OrderedFolder):
pass
class MyContent(NotifyBase, SimpleItem):
def __init__(self, id):
self._setId(id)
# These don't have manage_beforeDelete & co methods
class MyNewContent(DontComplain, SimpleItem):
def __init__(self, id):
self._setId(id)
class MyNewFolder(DontComplain, Folder):
pass
......
import unittest
_marker = object()
class Test__registerClass(unittest.TestCase):
class TestRegisterClass(unittest.TestCase):
def setUp(self):
from zope.component.testing import setUp
......@@ -45,6 +46,7 @@ class Test__registerClass(unittest.TestCase):
pass
else:
from zope.interface import implements
class Dummy(object):
implements(ifaces)
return Dummy
......@@ -53,10 +55,13 @@ class Test__registerClass(unittest.TestCase):
from zope.component import provideUtility
from zope.interface import implements
from zope.security.interfaces import IPermission
class Perm:
implements(IPermission)
def __init__(self, title):
self. title = title
if title is None:
title = name.capitalize()
provideUtility(Perm(title), name=name)
......@@ -66,8 +71,7 @@ class Test__registerClass(unittest.TestCase):
import Products
return (getattr(Products, 'meta_types', _marker),
OFS.metaconfigure._register_monkies,
OFS.metaconfigure._meta_type_regs,
)
OFS.metaconfigure._meta_type_regs)
def test_minimal(self):
klass = self._makeClass()
......@@ -80,7 +84,7 @@ class Test__registerClass(unittest.TestCase):
self.assertEqual(len(mt), 1)
self.assertEqual(mt[0]['name'], 'Dummy')
self.assertEqual(mt[0]['action'], '')
self.assertEqual(mt[0]['product'], 'OFS') # XXX why?
self.assertEqual(mt[0]['product'], 'OFS')
self.assertEqual(mt[0]['permission'], 'Perm')
self.assertEqual(mt[0]['visibility'], None)
self.assertEqual(mt[0]['interfaces'], ())
......@@ -109,8 +113,10 @@ class Test__registerClass(unittest.TestCase):
def test_w_interfaces(self):
from zope.interface import Interface
class IDummy(Interface):
pass
klass = self._makeClass((IDummy,))
self._registerPermission('perm')
......@@ -135,8 +141,3 @@ class Test__registerClass(unittest.TestCase):
self.assertEqual(klass.meta_type, 'Dummy')
mt, monkies, mt_regs = self._getRegistered()
self.assertEqual(len(mt), 1)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test__registerClass),
))
......@@ -167,6 +167,7 @@ def test_registerClass():
[]
"""
def test_suite():
from Testing.ZopeTestCase import ZopeDocTestSuite
return ZopeDocTestSuite()
......@@ -20,6 +20,7 @@ import sys
from Products.Five.tests import testing
sys.path.append(testing.__path__[0])
def test_registerPackage():
"""
Testing registerPackage
......
......@@ -66,8 +66,10 @@ class TestMaybeWarnDeprecated(unittest.TestCase):
class Deprecated(object):
def manage_afterAdd(self):
pass
class ASubClass(Deprecated):
pass
self.deprecatedManageAddDeleteClasses.append(Deprecated)
self.assertLog(ASubClass, '')
......
......@@ -176,11 +176,3 @@ class UserFolderTests(unittest.TestCase):
from AccessControl import Unauthorized
app = self._makeApp()
self.assertRaises(Unauthorized, app.restrictedTraverse, 'doc')
def test_suite():
suite = unittest.TestSuite((
unittest.makeSuite(BasicUserFolderTests),
unittest.makeSuite(UserFolderTests),
))
return suite
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment