Commit ed87506a authored by Hanno Schlichting's avatar Hanno Schlichting

flake8

parent 036d773a
...@@ -27,58 +27,65 @@ from DateTime.DateTime import DateTime ...@@ -27,58 +27,65 @@ from DateTime.DateTime import DateTime
from ExtensionClass import Base from ExtensionClass import Base
from zExceptions import Redirect from zExceptions import Redirect
class TemporalParadox(Exception): class TemporalParadox(Exception):
pass pass
class HistorySelectionError(Exception): class HistorySelectionError(Exception):
pass pass
class HystoryJar: class HystoryJar:
"""A ZODB Connection-like object that provides access to data """A ZODB Connection-like object that provides access to data
but prevents history from being changed.""" but prevents history from being changed."""
def __init__(self, base): def __init__(self, base):
self.__base__=base self.__base__ = base
def __getattr__(self, name): def __getattr__(self, name):
return getattr(self.__base__, name) return getattr(self.__base__, name)
def commit(self, object, transaction): def commit(self, object, transaction):
if object._p_changed: 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 tpc_begin = tpc_finish = abort
def historicalRevision(self, serial): def historicalRevision(self, serial):
state=self._p_jar.oldstate(self, serial) state = self._p_jar.oldstate(self, serial)
rev=self.__class__.__basicnew__() rev = self.__class__.__basicnew__()
rev._p_jar=HystoryJar(self._p_jar) rev._p_jar = HystoryJar(self._p_jar)
rev._p_oid=self._p_oid rev._p_oid = self._p_oid
rev._p_serial=serial rev._p_serial = serial
rev.__setstate__(state) rev.__setstate__(state)
rev._p_changed=0 rev._p_changed = 0
return rev return rev
class Historian(Implicit): class Historian(Implicit):
"""An Historian's job is to find hysterical revisions of """An Historian's job is to find hysterical revisions of
objects, given a time.""" objects, given a time."""
def __getitem__(self, key): def __getitem__(self, key):
self=self.aq_parent self = self.aq_parent
serial=apply(pack, ('>HHHH',)+tuple(map(int, key.split('.'))))
if serial == self._p_serial: return self serial = pack(*('>HHHH',) + tuple(map(int, key.split('.'))))
if serial == self._p_serial:
return self
rev=historicalRevision(self, serial) rev = historicalRevision(self, serial)
return rev.__of__(self.aq_parent) return rev.__of__(self.aq_parent)
def manage_workspace(self, REQUEST): def manage_workspace(self, REQUEST):
"We aren't real, so we delegate to that that spawned us!" "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): class Historical(Base):
"""Mix-in class to provide a veiw that shows hystorical changes """Mix-in class to provide a veiw that shows hystorical changes
...@@ -94,11 +101,11 @@ class Historical(Base): ...@@ -94,11 +101,11 @@ class Historical(Base):
security = ClassSecurityInfo() security = ClassSecurityInfo()
HistoricalRevisions=Historian() HistoricalRevisions = Historian()
manage_options=( manage_options = (
{'label':'History', 'action':'manage_change_history_page'}, {'label': 'History', 'action': 'manage_change_history_page'},
) )
security.declareProtected(view_history, 'manage_change_history_page') security.declareProtected(view_history, 'manage_change_history_page')
manage_change_history_page = DTMLFile( manage_change_history_page = DTMLFile(
...@@ -108,63 +115,65 @@ class Historical(Base): ...@@ -108,63 +115,65 @@ class Historical(Base):
security.declareProtected(view_history, 'manage_change_history') security.declareProtected(view_history, 'manage_change_history')
def manage_change_history(self): def manage_change_history(self):
first=0 first = 0
last=20 last = 20
request=getattr(self, 'REQUEST', None) request = getattr(self, 'REQUEST', None)
if request is not None: if request is not None:
first=request.get('first_transaction', first) first = request.get('first_transaction', first)
last=request.get('last_transaction',last) 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: if r is None:
# storage doesn't support history # storage doesn't support history
return () return ()
r=r[first:] r = r[first:]
for d in r: for d in r:
d['time']=DateTime(d['time']) d['time'] = DateTime(d['time'])
d['key']='.'.join(map(str, unpack(">HHHH", d['tid']))) d['key'] = '.'.join(map(str, unpack(">HHHH", d['tid'])))
return r return r
def manage_beforeHistoryCopy(self): pass # ? (Hook) def manage_beforeHistoryCopy(self):
pass # ? (Hook)
def manage_historyCopy(self, keys=[], RESPONSE=None, URL1=None): def manage_historyCopy(self, keys=[], RESPONSE=None, URL1=None):
"Copy a selected revision to the present" "Copy a selected revision to the present"
if not keys: if not keys:
raise HistorySelectionError, ( raise HistorySelectionError(
"No historical revision was selected.<p>") "No historical revision was selected.<p>")
if len(keys) > 1: if len(keys) > 1:
raise HistorySelectionError, ( raise HistorySelectionError(
"Only one historical revision can be " "Only one historical revision can be "
"copied to the present.<p>") "copied to the present.<p>")
key=keys[0] key = keys[0]
serial=apply(pack, ('>HHHH',)+tuple(map(int, key.split('.')))) serial = pack(*('>HHHH',) + tuple(map(int, key.split('.'))))
if serial != self._p_serial: if serial != self._p_serial:
self.manage_beforeHistoryCopy() self.manage_beforeHistoryCopy()
state=self._p_jar.oldstate(self, serial) state = self._p_jar.oldstate(self, serial)
base = aq_base(self) base = aq_base(self)
base._p_activate() # make sure we're not a ghost base._p_activate() # make sure we're not a ghost
base.__setstate__(state) # change the state 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() self.manage_afterHistoryCopy()
if RESPONSE is not None and URL1 is not None:
RESPONSE.redirect(URL1+'/manage_workspace')
def manage_afterHistoryCopy(self): pass # ? (Hook) if RESPONSE is not None and URL1 is not None:
RESPONSE.redirect(URL1 + '/manage_workspace')
def manage_afterHistoryCopy(self):
pass # ? (Hook)
_manage_historyComparePage = DTMLFile( _manage_historyComparePage = DTMLFile(
'dtml/historyCompare', globals(), management_view='History') 'dtml/historyCompare', globals(), management_view='History')
security.declareProtected(view_history, 'manage_historyCompare') security.declareProtected(view_history, 'manage_historyCompare')
def manage_historyCompare(self, rev1, rev2, REQUEST, def manage_historyCompare(self, rev1, rev2, REQUEST,
historyComparisonResults=''): historyComparisonResults=''):
dt1=DateTime(rev1._p_mtime) dt1 = DateTime(rev1._p_mtime)
dt2=DateTime(rev2._p_mtime) dt2 = DateTime(rev2._p_mtime)
return self._manage_historyComparePage( return self._manage_historyComparePage(
self, REQUEST, self, REQUEST,
dt1=dt1, dt2=dt2, dt1=dt1, dt2=dt2,
...@@ -174,68 +183,68 @@ class Historical(Base): ...@@ -174,68 +183,68 @@ class Historical(Base):
def manage_historicalComparison(self, REQUEST, keys=[]): def manage_historicalComparison(self, REQUEST, keys=[]):
"Compare two selected revisions" "Compare two selected revisions"
if not keys: if not keys:
raise HistorySelectionError, ( raise HistorySelectionError(
"No historical revision was selected.<p>") "No historical revision was selected.<p>")
if len(keys) > 2: if len(keys) > 2:
raise HistorySelectionError, ( raise HistorySelectionError(
"Only two historical revision can be compared<p>") "Only two historical revision can be compared<p>")
serial=apply(pack, ('>HHHH',)+tuple(map(int, keys[-1].split('.')))) serial = pack(*('>HHHH',) + tuple(map(int, keys[-1].split('.'))))
rev1=historicalRevision(self, serial) rev1 = historicalRevision(self, serial)
if len(keys)==2: if len(keys) == 2:
serial=apply(pack, serial = pack(*('>HHHH',) + tuple(map(int, keys[0].split('.'))))
('>HHHH',)+tuple(map(int, keys[0].split('.'))))
rev2=historicalRevision(self, serial) rev2 = historicalRevision(self, serial)
else: else:
rev2=self rev2 = self
return self.manage_historyCompare(rev1, rev2, REQUEST) return self.manage_historyCompare(rev1, rev2, REQUEST)
InitializeClass(Historical) InitializeClass(Historical)
def dump(tag, x, lo, hi, r): def dump(tag, x, lo, hi, r):
r1=[] r1 = []
r2=[] r2 = []
for i in xrange(lo, hi): for i in range(lo, hi):
r1.append(tag) r1.append(tag)
r2.append(x[i]) r2.append(x[i])
r.append("<tr>\n" r.append("<tr>\n"
"<td><pre>\n%s\n</pre></td>\n" "<td><pre>\n%s\n</pre></td>\n"
"<td><pre>\n%s\n</pre></td>\n" "<td><pre>\n%s\n</pre></td>\n"
"</tr>\n" "</tr>\n"
% ('\n'.join(r1), escape('\n'.join(r2)))) % ('\n'.join(r1), escape('\n'.join(r2))))
def replace(x, xlo, xhi, y, ylo, yhi, r):
rx1=[] def replace(x, xlo, xhi, y, ylo, yhi, r):
rx2=[] rx1 = []
for i in xrange(xlo, xhi): rx2 = []
for i in range(xlo, xhi):
rx1.append('-') rx1.append('-')
rx2.append(x[i]) rx2.append(x[i])
ry1=[] ry1 = []
ry2=[] ry2 = []
for i in xrange(ylo, yhi): for i in range(ylo, yhi):
ry1.append('+') ry1.append('+')
ry2.append(y[i]) ry2.append(y[i])
r.append("<tr>\n" r.append("<tr>\n"
"<td><pre>\n%s\n%s\n</pre></td>\n" "<td><pre>\n%s\n%s\n</pre></td>\n"
"<td><pre>\n%s\n%s\n</pre></td>\n" "<td><pre>\n%s\n%s\n</pre></td>\n"
"</tr>\n" "</tr>\n"
% ('\n'.join(rx1), '\n'.join(ry1), % ('\n'.join(rx1), '\n'.join(ry1),
escape('\n'.join(rx2)), escape('\n'.join(ry2)))) escape('\n'.join(rx2)), escape('\n'.join(ry2))))
def html_diff(s1, s2): def html_diff(s1, s2):
a=s1.split('\n') a = s1.split('\n')
b=s2.split('\n') b = s2.split('\n')
cruncher=difflib.SequenceMatcher() cruncher = difflib.SequenceMatcher()
cruncher.set_seqs(a,b) cruncher.set_seqs(a, b)
r=['<table border=1>'] r = ['<table border=1>']
for tag, alo, ahi, blo, bhi in cruncher.get_opcodes(): for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
if tag == 'replace': if tag == 'replace':
replace(a, alo, ahi, b, blo, bhi, r) replace(a, alo, ahi, b, blo, bhi, r)
...@@ -246,7 +255,7 @@ def html_diff(s1, s2): ...@@ -246,7 +255,7 @@ def html_diff(s1, s2):
elif tag == 'equal': elif tag == 'equal':
dump(' ', a, alo, ahi, r) dump(' ', a, alo, ahi, r)
else: else:
raise ValueError, 'unknown tag ' + `tag` raise ValueError('unknown tag %r' % tag)
r.append('</table>') r.append('</table>')
return '\n'.join(r) return '\n'.join(r)
...@@ -95,20 +95,21 @@ See module comments for details and programmatic interface. ...@@ -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 # 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. # have been in sys.argv[1:] had the cmd-line form been used.
import re
TRACE = 0 TRACE = 0
# define what "junk" means
import re
def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match): def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
return pat(line) is not None return pat(line) is not None
def IS_CHARACTER_JUNK(ch, ws=" \t"): def IS_CHARACTER_JUNK(ch, ws=" \t"):
return ch in ws return ch in ws
del re
class SequenceMatcher: class SequenceMatcher(object):
def __init__(self, isjunk=None, a='', b=''): def __init__(self, isjunk=None, a='', b=''):
# Members: # Members:
# a # a
...@@ -277,9 +278,9 @@ class SequenceMatcher: ...@@ -277,9 +278,9 @@ class SequenceMatcher:
continue continue
if j >= bhi: if j >= bhi:
break break
k = newj2len[j] = j2lenget(j-1, 0) + 1 k = newj2len[j] = j2lenget(j - 1, 0) + 1
if k > bestsize: 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 j2len = newj2len
# Now that we have a wholly interesting match (albeit possibly # Now that we have a wholly interesting match (albeit possibly
...@@ -290,17 +291,14 @@ class SequenceMatcher: ...@@ -290,17 +291,14 @@ class SequenceMatcher:
# interesting match, this is clearly the right thing to do, # interesting match, this is clearly the right thing to do,
# because no other kind of match is possible in the regions. # because no other kind of match is possible in the regions.
while besti > alo and bestj > blo and \ while besti > alo and bestj > blo and \
isbjunk(b[bestj-1]) and \ isbjunk(b[bestj - 1]) and \
a[besti-1] == b[bestj-1]: a[besti - 1] == b[bestj - 1]:
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 besti, bestj, bestsize = besti - 1, bestj - 1, bestsize + 1
while besti+bestsize < ahi and bestj+bestsize < bhi and \ while besti + bestsize < ahi and bestj + bestsize < bhi and \
isbjunk(b[bestj+bestsize]) and \ isbjunk(b[bestj + bestsize]) and \
a[besti+bestsize] == b[bestj+bestsize]: a[besti + bestsize] == b[bestj + bestsize]:
bestsize = bestsize + 1 bestsize = bestsize + 1
if TRACE:
print "get_matching_blocks", alo, ahi, blo, bhi
print " returns", besti, bestj, bestsize
return besti, bestj, bestsize return besti, bestj, bestsize
def get_matching_blocks(self): def get_matching_blocks(self):
...@@ -309,9 +307,7 @@ class SequenceMatcher: ...@@ -309,9 +307,7 @@ class SequenceMatcher:
self.matching_blocks = [] self.matching_blocks = []
la, lb = len(self.a), len(self.b) la, lb = len(self.a), len(self.b)
self.__helper(0, la, 0, lb, self.matching_blocks) self.__helper(0, la, 0, lb, self.matching_blocks)
self.matching_blocks.append( (la, lb, 0) ) self.matching_blocks.append((la, lb, 0))
if TRACE:
print '*** matching blocks', self.matching_blocks
return self.matching_blocks return self.matching_blocks
# builds list of matching blocks covering a[alo:ahi] and # builds list of matching blocks covering a[alo:ahi] and
...@@ -326,8 +322,8 @@ class SequenceMatcher: ...@@ -326,8 +322,8 @@ class SequenceMatcher:
if alo < i and blo < j: if alo < i and blo < j:
self.__helper(alo, i, blo, j, answer) self.__helper(alo, i, blo, j, answer)
answer.append(x) answer.append(x)
if i+k < ahi and j+k < bhi: if i + k < ahi and j + k < bhi:
self.__helper(i+k, ahi, j+k, bhi, answer) self.__helper(i + k, ahi, j + k, bhi, answer)
def ratio(self): def ratio(self):
"""Return a measure of the sequences' similarity (float in [0,1]). """Return a measure of the sequences' similarity (float in [0,1]).
...@@ -392,25 +388,29 @@ class SequenceMatcher: ...@@ -392,25 +388,29 @@ class SequenceMatcher:
elif j < bj: elif j < bj:
tag = 'insert' tag = 'insert'
if tag: if tag:
answer.append( (tag, i, ai, j, bj) ) answer.append((tag, i, ai, j, bj))
i, j = ai+size, bj+size i, j = ai + size, bj + size
# the list of matching blocks is terminated by a # the list of matching blocks is terminated by a
# sentinel with size 0 # sentinel with size 0
if size: if size:
answer.append( ('equal', ai, i, bj, j) ) answer.append(('equal', ai, i, bj, j))
return answer return answer
# meant for dumping lines
def dump(tag, x, lo, hi): def dump(tag, x, lo, hi):
# meant for dumping lines
for i in xrange(lo, hi): 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 # figure out which mark to stick under characters in lines that
# have changed (blank = same, - = deleted, + = inserted, ^ = replaced) # have changed (blank = same, - = deleted, + = inserted, ^ = replaced)
_combine = { ' ': ' ', _combine = {
'. ': '-', ' ': ' ',
' .': '+', '. ': '-',
'..': '^' } ' .': '+',
'..': '^',
}
def plain_replace(a, alo, ahi, b, blo, bhi): def plain_replace(a, alo, ahi, b, blo, bhi):
assert alo < ahi and blo < bhi assert alo < ahi and blo < bhi
...@@ -428,12 +428,8 @@ def plain_replace(a, alo, ahi, b, 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 # used as a synch point, and intraline difference marking is done on
# the similar pair. Lots of work, but often worth it. # 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 # don't synch up unless the lines have a similarity score of at
# least cutoff; best_ratio tracks the best score seen so far # least cutoff; best_ratio tracks the best score seen so far
best_ratio, cutoff = 0.74, 0.75 best_ratio, cutoff = 0.74, 0.75
...@@ -460,8 +456,8 @@ def fancy_replace(a, alo, ahi, b, blo, bhi): ...@@ -460,8 +456,8 @@ def fancy_replace(a, alo, ahi, b, blo, bhi):
# time it's called on a sequence pair; the expensive part # time it's called on a sequence pair; the expensive part
# of the computation is cached by cruncher # of the computation is cached by cruncher
if cruncher.real_quick_ratio() > best_ratio and \ if cruncher.real_quick_ratio() > best_ratio and \
cruncher.quick_ratio() > best_ratio and \ cruncher.quick_ratio() > best_ratio and \
cruncher.ratio() > best_ratio: cruncher.ratio() > best_ratio:
best_ratio, best_i, best_j = cruncher.ratio(), i, j best_ratio, best_i, best_j = cruncher.ratio(), i, j
if best_ratio < cutoff: if best_ratio < cutoff:
# no non-identical "pretty close" pair # no non-identical "pretty close" pair
...@@ -475,13 +471,6 @@ def fancy_replace(a, alo, ahi, b, blo, bhi): ...@@ -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) # there's a close pair, so forget the identical pair (if any)
eqi = None 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 # pump out diffs from before the synch point
fancy_helper(a, alo, best_i, b, blo, best_j) fancy_helper(a, alo, best_i, b, blo, best_j)
...@@ -504,13 +493,13 @@ def fancy_replace(a, alo, ahi, b, blo, bhi): ...@@ -504,13 +493,13 @@ def fancy_replace(a, alo, ahi, b, blo, bhi):
atags = atags + ' ' * la atags = atags + ' ' * la
btags = btags + ' ' * lb btags = btags + ' ' * lb
else: else:
raise ValueError, 'unknown tag ' + `tag` raise ValueError('unknown tag %r' % tag)
la, lb = len(atags), len(btags) la, lb = len(atags), len(btags)
if la < lb: if la < lb:
atags = atags + ' ' * (lb - la) atags = atags + ' ' * (lb - la)
elif lb < la: elif lb < la:
btags = btags + ' ' * (la - lb) 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, '?', \ print '-', aelt, '+', belt, '?', \
''.join(combined).rstrip() ''.join(combined).rstrip()
else: else:
...@@ -518,7 +507,8 @@ def fancy_replace(a, alo, ahi, b, blo, bhi): ...@@ -518,7 +507,8 @@ def fancy_replace(a, alo, ahi, b, blo, bhi):
print ' ', aelt, print ' ', aelt,
# pump out diffs from after the synch point # 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): def fancy_helper(a, alo, ahi, b, blo, bhi):
if alo < ahi: if alo < ahi:
...@@ -529,6 +519,7 @@ def fancy_helper(a, alo, ahi, b, blo, bhi): ...@@ -529,6 +519,7 @@ def fancy_helper(a, alo, ahi, b, blo, bhi):
elif blo < bhi: elif blo < bhi:
dump('+', b, blo, bhi) dump('+', b, blo, bhi)
def fail(msg): def fail(msg):
import sys import sys
out = sys.stderr.write out = sys.stderr.write
...@@ -536,23 +527,27 @@ def fail(msg): ...@@ -536,23 +527,27 @@ def fail(msg):
out(__doc__) out(__doc__)
return 0 return 0
# open a file & return the file object; gripe and return 0 if it
# couldn't be opened
def fopen(fname): def fopen(fname):
# open a file & return the file object; gripe and return 0 if it
# couldn't be opened
try: try:
return open(fname, 'r') return open(fname, 'r')
except IOError, detail: except IOError, detail:
return fail("couldn't open " + fname + ": " + str(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): def fcompare(f1name, f2name):
# open two files & spray the diff to stdout; return false iff a problem
f1 = fopen(f1name) f1 = fopen(f1name)
f2 = fopen(f2name) f2 = fopen(f2name)
if not f1 or not f2: if not f1 or not f2:
return 0 return 0
a = f1.readlines(); f1.close() a = f1.readlines()
b = f2.readlines(); f2.close() f1.close()
b = f2.readlines()
f2.close()
cruncher = SequenceMatcher(IS_LINE_JUNK, a, b) cruncher = SequenceMatcher(IS_LINE_JUNK, a, b)
for tag, alo, ahi, blo, bhi in cruncher.get_opcodes(): for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
...@@ -565,62 +560,6 @@ def fcompare(f1name, f2name): ...@@ -565,62 +560,6 @@ def fcompare(f1name, f2name):
elif tag == 'equal': elif tag == 'equal':
dump(' ', a, alo, ahi) dump(' ', a, alo, ahi)
else: else:
raise ValueError, 'unknown tag ' + `tag` raise ValueError('unknown tag %r' + tag)
return 1 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 @@ ...@@ -10,12 +10,6 @@
# FOR A PARTICULAR PURPOSE # 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 import unittest
...@@ -41,6 +35,7 @@ class AllowedItem(SimpleItem): ...@@ -41,6 +35,7 @@ class AllowedItem(SimpleItem):
InitializeClass(AllowedItem) InitializeClass(AllowedItem)
class DeniedItem(SimpleItem): class DeniedItem(SimpleItem):
id = 'denied' id = 'denied'
security = ClassSecurityInfo() security = ClassSecurityInfo()
...@@ -48,6 +43,7 @@ class DeniedItem(SimpleItem): ...@@ -48,6 +43,7 @@ class DeniedItem(SimpleItem):
InitializeClass(DeniedItem) InitializeClass(DeniedItem)
class ProtectedItem(SimpleItem): class ProtectedItem(SimpleItem):
id = 'protected' id = 'protected'
security = ClassSecurityInfo() security = ClassSecurityInfo()
...@@ -74,7 +70,8 @@ class TestGetAttr(unittest.TestCase): ...@@ -74,7 +70,8 @@ class TestGetAttr(unittest.TestCase):
self.app.manage_addFolder('plain_folder') self.app.manage_addFolder('plain_folder')
# We also want to be able to acquire simple attributes # 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 # Set up a subfolder and the objects we want to acquire from
self.app.manage_addFolder('subfolder') self.app.manage_addFolder('subfolder')
...@@ -142,7 +139,6 @@ class TestGetAttr(unittest.TestCase): ...@@ -142,7 +139,6 @@ class TestGetAttr(unittest.TestCase):
class TestGetAttrAnonymous(TestGetAttr): class TestGetAttrAnonymous(TestGetAttr):
# Run all tests again as Anonymous User # Run all tests again as Anonymous User
def setUp(self): def setUp(self):
...@@ -151,23 +147,15 @@ class TestGetAttrAnonymous(TestGetAttr): ...@@ -151,23 +147,15 @@ class TestGetAttrAnonymous(TestGetAttr):
noSecurityManager() noSecurityManager()
class TestGetAttr_c(TestGetAttr): class TestGetAttrC(TestGetAttr):
def setUp(self): def setUp(self):
TestGetAttr.setUp(self) TestGetAttr.setUp(self)
self.guarded_getattr = guarded_getattr_c self.guarded_getattr = guarded_getattr_c
class TestGetAttrAnonymous_c(TestGetAttrAnonymous):
class TestGetAttrAnonymousC(TestGetAttrAnonymous):
def setUp(self): def setUp(self):
TestGetAttrAnonymous.setUp(self) TestGetAttrAnonymous.setUp(self)
self.guarded_getattr = guarded_getattr_c 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): ...@@ -47,27 +47,27 @@ class ApplicationTests(unittest.TestCase):
self.assertEqual(app.title_and_id(), 'Other') self.assertEqual(app.title_and_id(), 'Other')
self.assertEqual(app.title_or_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 = self._makeOne()
app.NAME = 'attribute' app.NAME = 'attribute'
app._getOb = lambda x, y: x app._getOb = lambda x, y: x
request = {} request = {}
self.assertEqual(app.__bobo_traverse__(request, 'NAME'), 'attribute') 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 = self._makeOne()
app._getOb = lambda x, y: x app._getOb = lambda x, y: x
app._objects = [{'id': 'OTHER', 'meta_type': None}] app._objects = [{'id': 'OTHER', 'meta_type': None}]
request = {} request = {}
self.assertEqual(app.__bobo_traverse__(request, 'OTHER'), 'OTHER') 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 from UserDict import UserDict
request = UserDict() request = UserDict()
class _Response: class _Response:
def notFoundError(self, msg): def notFoundError(self, msg):
1/0 1 / 0
request.RESPONSE = _Response() request.RESPONSE = _Response()
app = self._makeOne() app = self._makeOne()
...@@ -76,21 +76,21 @@ class ApplicationTests(unittest.TestCase): ...@@ -76,21 +76,21 @@ class ApplicationTests(unittest.TestCase):
self.assertRaises(ZeroDivisionError, self.assertRaises(ZeroDivisionError,
app.__bobo_traverse__, request, 'NONESUCH') 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 = self._makeOne()
app._getOb = _noWay app._getOb = _noWay
request = {} request = {}
self.assertRaises(KeyError, app.__bobo_traverse__, request, 'NONESUCH') 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 = self._makeOne()
app._getOb = _noWay app._getOb = _noWay
request = {'REQUEST_METHOD': 'GET'} request = {'REQUEST_METHOD': 'GET'}
self.assertRaises(KeyError, app.__bobo_traverse__, request, 'NONESUCH') 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 from OFS import bbb
if bbb.HAS_ZSERVER: if bbb.HAS_ZSERVER:
from webdav.NullResource import NullResource from webdav.NullResource import NullResource
......
...@@ -32,9 +32,3 @@ class CacheTests(unittest.TestCase): ...@@ -32,9 +32,3 @@ class CacheTests(unittest.TestCase):
# The parent_cache should still trigger managersExist # The parent_cache should still trigger managersExist
self.assertTrue(managersExist(root.child.child_content)) self.assertTrue(managersExist(root.child.child_content))
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(CacheTests))
return suite
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
import unittest import unittest
from Testing import ZopeTestCase from Testing import ZopeTestCase
class TestRecursiveChangeOwnership(ZopeTestCase.ZopeTestCase): class TestRecursiveChangeOwnership(ZopeTestCase.ZopeTestCase):
user_name2 = "dumdidum" user_name2 = "dumdidum"
user_pass2 = "dumdidum" user_pass2 = "dumdidum"
...@@ -27,10 +28,10 @@ class TestRecursiveChangeOwnership(ZopeTestCase.ZopeTestCase): ...@@ -27,10 +28,10 @@ class TestRecursiveChangeOwnership(ZopeTestCase.ZopeTestCase):
# remember user objects # remember user objects
# is the __of__() call correct? is it needed? without it ownerInfo in # is the __of__() call correct? is it needed? without it ownerInfo in
# owner.py throws an AttributeError ... # owner.py throws an AttributeError ...
self.user1 = self.folder['acl_users'].getUser(ZopeTestCase.user_name self.user1 = self.folder['acl_users'].getUser(
).__of__(self.folder) ZopeTestCase.user_name).__of__(self.folder)
self.user2 = self.folder['acl_users'].getUser(self.user_name2 self.user2 = self.folder['acl_users'].getUser(
).__of__(self.folder) self.user_name2).__of__(self.folder)
self.folder.changeOwnership(self.user1) self.folder.changeOwnership(self.user1)
......
This diff is collapsed.
...@@ -9,9 +9,3 @@ class TestFTPInterface(unittest.TestCase): ...@@ -9,9 +9,3 @@ class TestFTPInterface(unittest.TestCase):
from zope.interface.verify import verifyClass from zope.interface.verify import verifyClass
verifyClass(IFTPAccess, FTPInterface) verifyClass(IFTPAccess, FTPInterface)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(TestFTPInterface),
))
...@@ -42,12 +42,12 @@ class HistoryTests(unittest.TestCase): ...@@ -42,12 +42,12 @@ class HistoryTests(unittest.TestCase):
t.description = None t.description = None
t.note('Change 1') t.note('Change 1')
t.commit() t.commit()
time.sleep(0.02) # wait at least one Windows clock tick time.sleep(0.02) # wait at least one Windows clock tick
hi.title = 'Second title' hi.title = 'Second title'
t = transaction.get() t = transaction.get()
t.note('Change 2') t.note('Change 2')
t.commit() t.commit()
time.sleep(0.02) # wait at least one Windows clock tick time.sleep(0.02) # wait at least one Windows clock tick
hi.title = 'Third title' hi.title = 'Third title'
t = transaction.get() t = transaction.get()
t.note('Change 3') t.note('Change 3')
...@@ -65,13 +65,13 @@ class HistoryTests(unittest.TestCase): ...@@ -65,13 +65,13 @@ class HistoryTests(unittest.TestCase):
def test_manage_change_history(self): def test_manage_change_history(self):
r = self.hi.manage_change_history() 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): for i in range(3):
entry = r[i] entry = r[i]
# check no new keys show up without testing # 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 # 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) self.assertTrue('key' in entry)
# lets not assume the size will stay the same forever # lets not assume the size will stay the same forever
self.assertTrue('size' in entry) self.assertTrue('size' in entry)
...@@ -79,24 +79,18 @@ class HistoryTests(unittest.TestCase): ...@@ -79,24 +79,18 @@ class HistoryTests(unittest.TestCase):
self.assertTrue('time' in entry) self.assertTrue('time' in entry)
if i: if i:
# check times are increasing # check times are increasing
self.assertTrue(entry['time']<r[i-1]['time']) self.assertTrue(entry['time'] < r[i - 1]['time'])
self.assertEqual(entry['user_name'],'') self.assertEqual(entry['user_name'], '')
def test_manage_historyCopy(self): def test_manage_historyCopy(self):
# we assume this works 'cos it's tested above # we assume this works 'cos it's tested above
r = self.hi.manage_change_history() r = self.hi.manage_change_history()
# now we do the copy # now we do the copy
self.hi.manage_historyCopy( self.hi.manage_historyCopy(keys=[r[2]['key']])
keys=[r[2]['key']]
)
# do a commit, just like ZPublisher would # do a commit, just like ZPublisher would
transaction.commit() 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 # that all other attributes will behave the same
self.assertEqual(self.hi.title, self.assertEqual(self.hi.title,
'First 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,16 +27,17 @@ class TestItem(unittest.TestCase): ...@@ -27,16 +27,17 @@ class TestItem(unittest.TestCase):
class RESPONSE(object): class RESPONSE(object):
handle_errors = True handle_errors = True
item = self._makeOne() item = self._makeOne()
def _raise_during_standard_error_message(*args, **kw): def _raise_during_standard_error_message(*args, **kw):
raise ZeroDivisionError('testing') raise ZeroDivisionError('testing')
item.standard_error_message = _raise_during_standard_error_message item.standard_error_message = _raise_during_standard_error_message
try: try:
item.raise_standardErrorMessage( item.raise_standardErrorMessage(
error_type=OverflowError, error_type=OverflowError,
error_value='simple', error_value='simple',
REQUEST=REQUEST(), REQUEST=REQUEST(),
) )
except: except Exception:
import sys import sys
self.assertEqual(sys.exc_info()[0], OverflowError) self.assertEqual(sys.exc_info()[0], OverflowError)
value = sys.exc_info()[1] value = sys.exc_info()[1]
...@@ -45,20 +46,22 @@ class TestItem(unittest.TestCase): ...@@ -45,20 +46,22 @@ class TestItem(unittest.TestCase):
def test_raise_StandardErrorMessage_TaintedString_errorValue(self): def test_raise_StandardErrorMessage_TaintedString_errorValue(self):
from AccessControl.tainted import TaintedString from AccessControl.tainted import TaintedString
class REQUEST(object): class REQUEST(object):
class RESPONSE(object): class RESPONSE(object):
handle_errors = True handle_errors = True
item = self._makeOne() item = self._makeOne()
def _raise_during_standard_error_message(*args, **kw): def _raise_during_standard_error_message(*args, **kw):
raise ZeroDivisionError('testing') raise ZeroDivisionError('testing')
item.standard_error_message = _raise_during_standard_error_message item.standard_error_message = _raise_during_standard_error_message
try: try:
item.raise_standardErrorMessage( item.raise_standardErrorMessage(
error_type=OverflowError, error_type=OverflowError,
error_value=TaintedString('<simple>'), error_value=TaintedString('<simple>'),
REQUEST=REQUEST(), REQUEST=REQUEST(),
) )
except: except Exception:
import sys import sys
self.assertEqual(sys.exc_info()[0], OverflowError) self.assertEqual(sys.exc_info()[0], OverflowError)
value = sys.exc_info()[1] value = sys.exc_info()[1]
...@@ -113,10 +116,3 @@ class TestSimpleItem(unittest.TestCase): ...@@ -113,10 +116,3 @@ class TestSimpleItem(unittest.TestCase):
REQUEST=REQUEST()) REQUEST=REQUEST())
self.assertEquals(sem.kw.get('error_type'), 'BadRequest') 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): ...@@ -91,23 +91,21 @@ class TestsOfBroken(unittest.TestCase):
"_p_mtime", "_p_mtime",
"_p_oid", "_p_oid",
"_p_serial", "_p_serial",
"_p_state", "_p_state"]
]
PERSISTENCE_METHODS = ["_p_deactivate", PERSISTENCE_METHODS = ["_p_deactivate",
"_p_activate", "_p_activate",
"_p_invalidate", "_p_invalidate",
"_p_getattr", "_p_getattr",
"_p_setattr", "_p_setattr",
"_p_delattr", "_p_delattr"]
]
inst = Broken(self, OID, ('Products.MyProduct.MyClass', 'MyClass')) inst = Broken(self, OID, ('Products.MyProduct.MyClass', 'MyClass'))
for attr_name in PERSISTENCE_ATTRS: 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: 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): class TestsIntegratedBroken(base.TestCase):
...@@ -146,7 +144,3 @@ def test_suite(): ...@@ -146,7 +144,3 @@ def test_suite():
suite.addTest(unittest.makeSuite(TestsOfBroken)) suite.addTest(unittest.makeSuite(TestsOfBroken))
suite.addTest(unittest.makeSuite(TestsIntegratedBroken)) suite.addTest(unittest.makeSuite(TestsIntegratedBroken))
return suite return suite
def main():
unittest.main(defaultTest='test_suite')
...@@ -23,54 +23,70 @@ from OFS.OrderedFolder import OrderedFolder ...@@ -23,54 +23,70 @@ from OFS.OrderedFolder import OrderedFolder
from zope.component import testing, eventtesting from zope.component import testing, eventtesting
def setUp(test): def setUp(test):
testing.setUp(test) testing.setUp(test)
eventtesting.setUp(test) eventtesting.setUp(test)
class DontComplain(object): class DontComplain(object):
def _verifyObjectPaste(self, object, validate_src=1): def _verifyObjectPaste(self, object, validate_src=1):
pass pass
def cb_isMoveable(self): def cb_isMoveable(self):
return True return True
def cb_isCopyable(self): def cb_isCopyable(self):
return True return True
class NotifyBase(DontComplain): class NotifyBase(DontComplain):
def manage_afterAdd(self, item, container): def manage_afterAdd(self, item, container):
print 'old manage_afterAdd %s %s %s' % (self.getId(), item.getId(), print('old manage_afterAdd %s %s %s' % (
container.getId()) self.getId(), item.getId(), container.getId()))
super(NotifyBase, self).manage_afterAdd(item, container) super(NotifyBase, self).manage_afterAdd(item, container)
manage_afterAdd.__five_method__ = True # Shut up deprecation warnings
manage_afterAdd.__five_method__ = True # Shut up deprecation warnings
def manage_beforeDelete(self, item, container): def manage_beforeDelete(self, item, container):
super(NotifyBase, self).manage_beforeDelete(item, container) super(NotifyBase, self).manage_beforeDelete(item, container)
print 'old manage_beforeDelete %s %s %s' % (self.getId(), item.getId(), print('old manage_beforeDelete %s %s %s' % (
container.getId()) self.getId(), item.getId(), container.getId()))
manage_beforeDelete.__five_method__ = True # Shut up deprecation warnings manage_beforeDelete.__five_method__ = True # Shut up deprecation warnings
def manage_afterClone(self, item): 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) super(NotifyBase, self).manage_afterClone(item)
manage_afterClone.__five_method__ = True # Shut up deprecation warnings manage_afterClone.__five_method__ = True # Shut up deprecation warnings
class MyApp(Folder): class MyApp(Folder):
def getPhysicalRoot(self): def getPhysicalRoot(self):
return self return self
class MyFolder(NotifyBase, Folder): class MyFolder(NotifyBase, Folder):
pass pass
class MyOrderedFolder(NotifyBase, OrderedFolder): class MyOrderedFolder(NotifyBase, OrderedFolder):
pass pass
class MyContent(NotifyBase, SimpleItem): class MyContent(NotifyBase, SimpleItem):
def __init__(self, id): def __init__(self, id):
self._setId(id) self._setId(id)
# These don't have manage_beforeDelete & co methods # These don't have manage_beforeDelete & co methods
class MyNewContent(DontComplain, SimpleItem): class MyNewContent(DontComplain, SimpleItem):
def __init__(self, id): def __init__(self, id):
self._setId(id) self._setId(id)
class MyNewFolder(DontComplain, Folder): class MyNewFolder(DontComplain, Folder):
pass pass
......
import unittest import unittest
_marker = object() _marker = object()
class Test__registerClass(unittest.TestCase):
class TestRegisterClass(unittest.TestCase):
def setUp(self): def setUp(self):
from zope.component.testing import setUp from zope.component.testing import setUp
...@@ -22,8 +23,8 @@ class Test__registerClass(unittest.TestCase): ...@@ -22,8 +23,8 @@ class Test__registerClass(unittest.TestCase):
from zope.component.testing import tearDown from zope.component.testing import tearDown
import OFS.metaconfigure import OFS.metaconfigure
# restore registrations # restore registrations
OFS.metaconfigure._meta_type_regs[:] = self._old_mt_regs OFS.metaconfigure._meta_type_regs[:] = self._old_mt_regs
OFS.metaconfigure._register_monkies[:] = self._old_monkies OFS.metaconfigure._register_monkies[:] = self._old_monkies
if self._old_metatypes is not _marker: if self._old_metatypes is not _marker:
import Products import Products
Products.meta_types = self._old_metatypes Products.meta_types = self._old_metatypes
...@@ -35,7 +36,7 @@ class Test__registerClass(unittest.TestCase): ...@@ -35,7 +36,7 @@ class Test__registerClass(unittest.TestCase):
tearDown() tearDown()
def _callFUT(self, klass, meta_type, permission, def _callFUT(self, klass, meta_type, permission,
addview=None, icon=None, global_=False): addview=None, icon=None, global_=False):
from OFS.metaconfigure import _registerClass from OFS.metaconfigure import _registerClass
_registerClass(klass, meta_type, permission, addview, icon, global_) _registerClass(klass, meta_type, permission, addview, icon, global_)
...@@ -45,6 +46,7 @@ class Test__registerClass(unittest.TestCase): ...@@ -45,6 +46,7 @@ class Test__registerClass(unittest.TestCase):
pass pass
else: else:
from zope.interface import implements from zope.interface import implements
class Dummy(object): class Dummy(object):
implements(ifaces) implements(ifaces)
return Dummy return Dummy
...@@ -53,10 +55,13 @@ class Test__registerClass(unittest.TestCase): ...@@ -53,10 +55,13 @@ class Test__registerClass(unittest.TestCase):
from zope.component import provideUtility from zope.component import provideUtility
from zope.interface import implements from zope.interface import implements
from zope.security.interfaces import IPermission from zope.security.interfaces import IPermission
class Perm: class Perm:
implements(IPermission) implements(IPermission)
def __init__(self, title): def __init__(self, title):
self. title = title self. title = title
if title is None: if title is None:
title = name.capitalize() title = name.capitalize()
provideUtility(Perm(title), name=name) provideUtility(Perm(title), name=name)
...@@ -65,9 +70,8 @@ class Test__registerClass(unittest.TestCase): ...@@ -65,9 +70,8 @@ class Test__registerClass(unittest.TestCase):
import OFS.metaconfigure import OFS.metaconfigure
import Products import Products
return (getattr(Products, 'meta_types', _marker), return (getattr(Products, 'meta_types', _marker),
OFS.metaconfigure._register_monkies, OFS.metaconfigure._register_monkies,
OFS.metaconfigure._meta_type_regs, OFS.metaconfigure._meta_type_regs)
)
def test_minimal(self): def test_minimal(self):
klass = self._makeClass() klass = self._makeClass()
...@@ -80,7 +84,7 @@ class Test__registerClass(unittest.TestCase): ...@@ -80,7 +84,7 @@ class Test__registerClass(unittest.TestCase):
self.assertEqual(len(mt), 1) self.assertEqual(len(mt), 1)
self.assertEqual(mt[0]['name'], 'Dummy') self.assertEqual(mt[0]['name'], 'Dummy')
self.assertEqual(mt[0]['action'], '') 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]['permission'], 'Perm')
self.assertEqual(mt[0]['visibility'], None) self.assertEqual(mt[0]['visibility'], None)
self.assertEqual(mt[0]['interfaces'], ()) self.assertEqual(mt[0]['interfaces'], ())
...@@ -109,8 +113,10 @@ class Test__registerClass(unittest.TestCase): ...@@ -109,8 +113,10 @@ class Test__registerClass(unittest.TestCase):
def test_w_interfaces(self): def test_w_interfaces(self):
from zope.interface import Interface from zope.interface import Interface
class IDummy(Interface): class IDummy(Interface):
pass pass
klass = self._makeClass((IDummy,)) klass = self._makeClass((IDummy,))
self._registerPermission('perm') self._registerPermission('perm')
...@@ -135,8 +141,3 @@ class Test__registerClass(unittest.TestCase): ...@@ -135,8 +141,3 @@ class Test__registerClass(unittest.TestCase):
self.assertEqual(klass.meta_type, 'Dummy') self.assertEqual(klass.meta_type, 'Dummy')
mt, monkies, mt_regs = self._getRegistered() mt, monkies, mt_regs = self._getRegistered()
self.assertEqual(len(mt), 1) self.assertEqual(len(mt), 1)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(Test__registerClass),
))
...@@ -167,6 +167,7 @@ def test_registerClass(): ...@@ -167,6 +167,7 @@ def test_registerClass():
[] []
""" """
def test_suite(): def test_suite():
from Testing.ZopeTestCase import ZopeDocTestSuite from Testing.ZopeTestCase import ZopeDocTestSuite
return ZopeDocTestSuite() return ZopeDocTestSuite()
...@@ -20,6 +20,7 @@ import sys ...@@ -20,6 +20,7 @@ import sys
from Products.Five.tests import testing from Products.Five.tests import testing
sys.path.append(testing.__path__[0]) sys.path.append(testing.__path__[0])
def test_registerPackage(): def test_registerPackage():
""" """
Testing registerPackage Testing registerPackage
...@@ -33,7 +34,7 @@ def test_registerPackage(): ...@@ -33,7 +34,7 @@ def test_registerPackage():
Make sure a python package with a valid initialize gets its Make sure a python package with a valid initialize gets its
initialize function called:: initialize function called::
>>> configure_zcml = ''' >>> configure_zcml = '''
... <configure ... <configure
... xmlns="http://namespaces.zope.org/zope" ... xmlns="http://namespaces.zope.org/zope"
...@@ -45,8 +46,8 @@ def test_registerPackage(): ...@@ -45,8 +46,8 @@ def test_registerPackage():
... /> ... />
... </configure>''' ... </configure>'''
>>> zcml.load_string(configure_zcml) >>> zcml.load_string(configure_zcml)
We need to load the product as well. This would normally happen during We need to load the product as well. This would normally happen during
Zope startup, but in the test, we're already too late. Zope startup, but in the test, we're already too late.
>>> import Zope2 >>> import Zope2
......
...@@ -27,7 +27,7 @@ class TestMaybeWarnDeprecated(unittest.TestCase): ...@@ -27,7 +27,7 @@ class TestMaybeWarnDeprecated(unittest.TestCase):
deprecatedManageAddDeleteClasses[:]) deprecatedManageAddDeleteClasses[:])
self.deprecatedManageAddDeleteClasses = ( self.deprecatedManageAddDeleteClasses = (
deprecatedManageAddDeleteClasses) deprecatedManageAddDeleteClasses)
# Add a class to make sure there is at least one because an empty # Add a class to make sure there is at least one because an empty
# deprecatedManageAddDeleteClasses list is special cased # deprecatedManageAddDeleteClasses list is special cased
self.deprecatedManageAddDeleteClasses.append(int) self.deprecatedManageAddDeleteClasses.append(int)
# Pick up log messages # Pick up log messages
...@@ -66,8 +66,10 @@ class TestMaybeWarnDeprecated(unittest.TestCase): ...@@ -66,8 +66,10 @@ class TestMaybeWarnDeprecated(unittest.TestCase):
class Deprecated(object): class Deprecated(object):
def manage_afterAdd(self): def manage_afterAdd(self):
pass pass
class ASubClass(Deprecated): class ASubClass(Deprecated):
pass pass
self.deprecatedManageAddDeleteClasses.append(Deprecated) self.deprecatedManageAddDeleteClasses.append(Deprecated)
self.assertLog(ASubClass, '') self.assertLog(ASubClass, '')
......
...@@ -18,11 +18,11 @@ import unittest ...@@ -18,11 +18,11 @@ import unittest
class BasicUserFolderTests(unittest.TestCase): class BasicUserFolderTests(unittest.TestCase):
def _getTargetClass(self): def _getTargetClass(self):
from OFS.userfolder import BasicUserFolder from OFS.userfolder import BasicUserFolder
return BasicUserFolder return BasicUserFolder
def test_manage_users_security_initialized(self): def test_manage_users_security_initialized(self):
uf = self._getTargetClass()() uf = self._getTargetClass()()
self.assertTrue(hasattr(uf, 'manage_users__roles__')) self.assertTrue(hasattr(uf, 'manage_users__roles__'))
...@@ -119,7 +119,7 @@ class UserFolderTests(unittest.TestCase): ...@@ -119,7 +119,7 @@ class UserFolderTests(unittest.TestCase):
app.manage_role('Owner', ['Add Folders']) app.manage_role('Owner', ['Add Folders'])
app.manage_addLocalRoles('user1', ['Owner']) app.manage_addLocalRoles('user1', ['Owner'])
self.assertTrue(user.has_permission('Add Folders', app)) self.assertTrue(user.has_permission('Add Folders', app))
def testAuthenticate(self): def testAuthenticate(self):
app = self._makeApp() app = self._makeApp()
uf = self._makeOne(app) uf = self._makeOne(app)
...@@ -176,11 +176,3 @@ class UserFolderTests(unittest.TestCase): ...@@ -176,11 +176,3 @@ class UserFolderTests(unittest.TestCase):
from AccessControl import Unauthorized from AccessControl import Unauthorized
app = self._makeApp() app = self._makeApp()
self.assertRaises(Unauthorized, app.restrictedTraverse, 'doc') 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