Commit 908ef3be authored by kiilerix's avatar kiilerix

assert: try to show some relevant value when an assert fails

Debugging and print statements can tell more about failing asserts, but it is
nice to get *some* information up front, also to make it easier to reproduce.

General guidelines:

Try to avoid anything that must compute something and thus can fail - try to
just inspect local variables (or whatever assert looked at).

For type related asserts, try to add repr().

Sometimes, multiple variables are relevant - in that case use tuples.
parent f6a1b36aebad
......@@ -120,7 +120,7 @@ def test_makeannotatepalette_mindate_included():
for _color, fctxs in palette.items():
palfctxs.update(fctxs)
for fctx in filectxs[2:]:
assert fctx in palfctxs
assert fctx in palfctxs, (fctx, palfctxs)
def test_makeannotatepalette_mindate_earlier_than_rev0():
agestep = 50 * SECS_PER_DAY
......@@ -132,4 +132,4 @@ def test_makeannotatepalette_mindate_earlier_than_rev0():
for _color, fctxs in palette.items():
palfctxs.update(fctxs)
for fctx in filectxs:
assert fctx in palfctxs
assert fctx in palfctxs, (fctx, palfctxs)
......@@ -41,7 +41,7 @@ def loaddata(reponame, rev, path, prev=None):
def check_error(fd, message):
assert message in fd.error
assert message in fd.error, (message, fd.error)
# no data should be loaded
assert_false(fd.contents)
assert_false(fd.olddata)
......@@ -55,7 +55,7 @@ def test_error_added():
yield check_error, fd, msg
def check_flabel(fd, message):
assert message in fd.flabel
assert message in fd.flabel, (message, fd.flabel)
def test_flabel_added():
for path in ['text', 'binary', 'text-over1kb']:
......
......@@ -119,8 +119,11 @@ def test_undumpsubrepos(f):
"""<subrepo> element should be mapped to different classes"""
root = repotreemodel.readXml(f, 'reporegistry')
allgroup = root.child(0)
assert type(allgroup.child(0)) is repotreeitem.StandaloneSubrepoItem
assert type(allgroup.child(0)) is repotreeitem.StandaloneSubrepoItem, \
repr(allgroup.child(0))
subroot = allgroup.child(1)
assert type(subroot) is repotreeitem.RepoItem
assert type(subroot.child(0)) is repotreeitem.AlienSubrepoItem
assert type(subroot.child(1)) is repotreeitem.SubrepoItem
assert type(subroot) is repotreeitem.RepoItem, repr(subroot)
assert type(subroot.child(0)) is repotreeitem.AlienSubrepoItem, \
repr(subroot.child(0))
assert type(subroot.child(1)) is repotreeitem.SubrepoItem, \
repr(subroot.child(1))
......@@ -78,8 +78,8 @@ def check_copy():
@with_both
def check_contains():
c = newwconfig({'foo.bar': 'baz'})
assert 'foo' in c
assert 'bar' not in c
assert 'foo' in c, c
assert 'bar' not in c, c
@with_both
def check_getitem():
......@@ -91,7 +91,7 @@ def check_getitem():
def check_getitem_empty_then_set_no_effect():
c = newwconfig()
c['unknown']['bar'] = 'baz'
assert not c.get('unknown', 'bar')
assert not c.get('unknown', 'bar'), c.get('unknown', 'bar')
@with_both
def check_set_followed_by_getitem_empty():
......@@ -104,8 +104,8 @@ def check_set_followed_by_getitem_empty():
@with_both
def check_dict_contains():
c = newwconfig({'foo.bar': 'x'})
assert 'bar' in c['foo']
assert 'baz' not in c['foo']
assert 'bar' in c['foo'], c['foo']
assert 'baz' not in c['foo'], c['foo']
@with_both
def check_dict_getitem():
......@@ -149,7 +149,7 @@ def check_dict_update():
def check_dict_delitem():
c = newwconfig({'foo.bar': 'x'})
del c['foo']['bar']
assert 'bar' not in c['foo']
assert 'bar' not in c['foo'], c['foo']
@with_both
def check_iter():
......@@ -328,7 +328,7 @@ def check_write_conflict_set_del():
wconfig.writefile(c0, fname)
cr = wconfig.readfile(fname)
assert not cr.get('foo', 'bar')
assert not cr.get('foo', 'bar'), cr.get('foo', 'bar')
@with_wconfig
def check_write_conflict_del_del():
......@@ -341,7 +341,7 @@ def check_write_conflict_del_del():
wconfig.writefile(c0, fname) # shouldn't raise KeyError
cr = wconfig.readfile(fname)
assert not cr.get('foo', 'bar')
assert not cr.get('foo', 'bar'), cr.get('foo', 'bar')
@with_wconfig
def check_write_noconflict_set_set():
......@@ -356,7 +356,8 @@ def check_write_noconflict_set_set():
cr = wconfig.readfile(fname)
assert_equals('z', cr.get('foo', 'bar'))
assert_equals('y', cr.get('foo', 'baz'))
assert not c0.get('foo', 'baz') # don't reload c1's change implicitly
# don't reload c1's change implicitly
assert not c0.get('foo', 'baz'), c0.get('foo', 'baz')
@with_wconfig
def check_write_noconflict_del():
......@@ -368,8 +369,9 @@ def check_write_noconflict_del():
wconfig.writefile(c0, fname) # shouldn't override del foo.bar
cr = wconfig.readfile(fname)
assert not cr.get('foo', 'bar')
assert c0.get('foo', 'bar') # don't reload c1's change implicitly
assert not cr.get('foo', 'bar'), cr.get('foo', 'bar')
# don't reload c1's change implicitly
assert c0.get('foo', 'bar'), c0.get('foo', 'bar')
@with_wconfig
......
......@@ -375,7 +375,7 @@ class CmdServer(CmdWorker):
return self._readchtable is self._runcommandchtable
def startCommand(self, cmdline, uihandler):
assert self._servicestate == CmdWorker.Ready
assert self._servicestate == CmdWorker.Ready, self._servicestate
assert not self.isCommandRunning()
try:
data = hglib.fromunicode('\0'.join(cmdline))
......@@ -721,7 +721,7 @@ class CmdSession(QObject):
@pyqtSlot(int)
def _onWorkerStateChanged(self, state):
if state == CmdWorker.Ready:
assert self._qnextp == 0
assert self._qnextp == 0, self._qnextp
self._runNext()
elif state == CmdWorker.NotRunning:
# unexpected end of command execution
......
......@@ -1091,7 +1091,7 @@ class CommitWidget(QWidget, qtlib.TaskWidget):
if not self.files and canemptycommit and not merge:
# make sure to commit empty changeset by excluding all files
cmdline.extend(['--exclude', repo.root])
assert not self.stwidget.partials
assert not self.stwidget.partials, self.stwidget.partials
cmdline.append('--')
cmdline.extend(pycompat.maplist(hglib.escapepath, self.files))
......
......@@ -97,7 +97,7 @@ class Factory(object):
if 'type' not in style:
raise _("must be specified 'type' in style")
type = style['type']
assert type in ('panel', 'label')
assert type in ('panel', 'label'), type
# create widget
args = (target, style, custom, repo, self.info)
......@@ -458,7 +458,7 @@ class SummaryPanel(SummaryBase, QWidget):
if 'margin' in self.csstyle:
margin = self.csstyle['margin']
assert isinstance(margin, (int, pycompat.long))
assert isinstance(margin, (int, pycompat.long)), repr(margin)
buf = '<table style="margin: %spx">' % margin
else:
buf = '<table>'
......
......@@ -201,7 +201,7 @@ class FilectxActions(QObject):
return self._actions[name][0]
def _addAction(self, name, action, fdfilters):
assert name not in self._actions
assert name not in self._actions, name
self._actions[name] = action, fdfilters
def _runCommand(self, cmdline):
......@@ -717,7 +717,7 @@ class WctxActions(FilectxActions):
@pyqtSlot()
def _updateRenameFileMenu(self):
menu = self.sender()
assert isinstance(menu, QMenu)
assert isinstance(menu, QMenu), repr(menu)
menu.clear()
fds = self.fileDataListForAction('renameFileMenu')
if not fds:
......@@ -748,7 +748,7 @@ class WctxActions(FilectxActions):
@pyqtSlot()
def _populateRemergeFileMenu(self):
menu = self.sender()
assert isinstance(menu, QMenu)
assert isinstance(menu, QMenu), repr(menu)
menu.aboutToShow.disconnect(self._populateRemergeFileMenu)
for tool in hglib.mergetools(self._ui):
menu.addAction(hglib.tounicode(tool))
......
......@@ -444,7 +444,7 @@ class FileData(_AbstractFileData):
return _trimdiffheader(udiff)
def setChunkExcluded(self, chunk, exclude):
assert chunk in self.changes.hunks
assert chunk in self.changes.hunks, repr(chunk)
if chunk.excluded == exclude:
return
if exclude:
......@@ -563,7 +563,8 @@ class SubrepoData(_AbstractFileData):
def createRebased(self, pctx):
# new status should be unknown, but currently it is 'S'
assert self._status == 'S' # TODO: replace 'S' by subrepo's status
# TODO: replace 'S' by subrepo's status
assert self._status == 'S', self._status
return self.__class__(self._ctx, pctx, self._wfile, status=self._status,
rpath=self._rpath, subkind=self._subkind)
......
......@@ -168,7 +168,7 @@ class _AbstractFileDialog(QMainWindow):
self.setupUi()
self._show_rev = None
assert not isinstance(filename, pycompat.unicode)
assert not isinstance(filename, pycompat.unicode), repr(filename)
self.filename = filename
self.setWindowTitle(_('Hg file log viewer [%s] - %s')
......
......@@ -286,7 +286,7 @@ class StandardDag(object):
"""
def __init__(self, repo, start_rev, stop_rev, branch, allparents,
showgraftsource, visiblerev):
assert start_rev is None or start_rev >= stop_rev
assert start_rev is None or start_rev >= stop_rev, (start_rev, stop_rev)
self.repo = repo
self.start_rev = start_rev
self.stop_rev = stop_rev
......@@ -536,7 +536,7 @@ class FamilyLineDag(StandardDag):
self._append_graft_source(rctx, parents)
yield rctx, parents
assert not queue
assert not queue, queue
def revision_grapher(repo, opts):
......
......@@ -266,7 +266,7 @@ class InfoBarPlaceholder(QWidget):
repoagent.busyChanged.connect(self._clearStaleInfo)
def setView(self, view):
assert isinstance(view, QTableView)
assert isinstance(view, QTableView), repr(view)
lay = self.layout()
if self._view:
lay.removeWidget(self._view)
......
......@@ -77,7 +77,7 @@ class ManifestModel(QAbstractItemModel):
self._repoagent = repoagent
self._namefilter = pycompat.unicode(namefilter or '')
assert all(c in 'MARSC' for c in statusfilter)
assert all(c in 'MARSC' for c in statusfilter), repr(statusfilter)
self._statusfilter = statusfilter
self._changedfilesonly = False
self._nodeop = _nodeopmap[bool(flat)]
......@@ -332,7 +332,7 @@ class ManifestModel(QAbstractItemModel):
def setStatusFilter(self, status):
"""Filter file tree by change status 'MARSC'"""
status = str(status)
assert all(c in 'MARSC' for c in status)
assert all(c in 'MARSC' for c in status), repr(status)
if self._statusfilter == status:
return # for performance reason
self._statusfilter = status
......@@ -372,7 +372,7 @@ class ManifestModel(QAbstractItemModel):
def fetchMore(self, parent):
if parent.isValid() or self._rootpopulated:
return
assert len(self._rootentry) == 0
assert len(self._rootentry) == 0, self._rootentry
newroote = self._rootentry.copyskel()
self._populateNodes(newroote)
last = len(newroote) - 1
......@@ -497,7 +497,7 @@ class _Entry(object):
return e
def putchild(self, name, e):
assert not e.name and not e.parent
assert not e.name and not e.parent, (e.name, e.parent)
e._name = name
e._parent = self
if name not in self._child:
......
......@@ -55,7 +55,7 @@ class MergeDialog(QWizard):
def __init__(self, repoagent, otherrev, parent=None):
super(MergeDialog, self).__init__(parent)
assert isinstance(otherrev, int)
assert isinstance(otherrev, int), repr(otherrev)
self._repoagent = repoagent
f = self.windowFlags()
self.setWindowFlags(f & ~Qt.WindowContextHelpButtonHint)
......
......@@ -87,7 +87,7 @@ class QueueManagementActions(QObject):
def __init__(self, parent=None):
super(QueueManagementActions, self).__init__(parent)
assert parent is None or isinstance(parent, QWidget)
assert parent is None or isinstance(parent, QWidget), repr(parent)
self._repoagent = None
self._cmdsession = cmdcore.nullCmdSession()
......@@ -267,7 +267,7 @@ class PatchQueueActions(QObject):
def __init__(self, parent=None):
super(PatchQueueActions, self).__init__(parent)
assert parent is None or isinstance(parent, QWidget)
assert parent is None or isinstance(parent, QWidget), repr(parent)
self._repoagent = None
self._cmdsession = cmdcore.nullCmdSession()
self._opts = {'force': False, 'keep_changes': False}
......
......@@ -172,7 +172,7 @@ def editfiles(repo, files, lineno=None, search=None, parent=None):
return
files = [procutil.shellquote(util.localpath(f)) for f in files]
assert len(files) == 1 or lineno == None
assert len(files) == 1 or lineno == None, (files, lineno)
cmdline = None
if search:
......@@ -781,7 +781,7 @@ def initfontcache(ui):
_fontcache[name] = ThgFont(hglib.tounicode(fname))
def getfont(name):
assert name in _fontdefaults
assert name in _fontdefaults, (name, _fontdefaults)
return _fontcache[name]
def CommonMsgBox(icon, title, main, text='', buttons=QMessageBox.Ok,
......@@ -1266,7 +1266,7 @@ class DialogKeeper(QObject):
def _preparedlg(self, key, args, kwargs):
if key in self._keytodlgs:
assert len(self._keytodlgs[key]) > 0
assert len(self._keytodlgs[key]) > 0, key
return self._keytodlgs[key][-1] # prefer latest
else:
return self._populatedlg(key, args, kwargs)
......
......@@ -180,7 +180,7 @@ class QuickOpDialog(QDialog):
if files:
cmdlines.append(hglib.buildcmdargs(self.command, *files, **opts))
if lfiles:
assert self.command == 'add'
assert self.command == 'add', self.command
lopts = opts.copy()
lopts['large'] = True
cmdlines.append(hglib.buildcmdargs(self.command, *lfiles, **lopts))
......
......@@ -421,7 +421,7 @@ class RepoTabWidget(QWidget):
@pyqtSlot(str, object, str, str, object)
def _mapProgressReceived(self, topic, pos, item, unit, total):
rw = self.sender()
assert isinstance(rw, repowidget.RepoWidget)
assert isinstance(rw, repowidget.RepoWidget), repr(rw)
progress = cmdcore.ProgressMessage(
pycompat.unicode(topic), pos, pycompat.unicode(item),
pycompat.unicode(unit), total)
......
......@@ -44,7 +44,7 @@ def _dumpChild(xw, parent):
def undumpObject(xr):
xmltagname = str(xr.name())
obj = _xmlUndumpMap[xmltagname](xr)
assert obj.xmltagname == xmltagname
assert obj.xmltagname == xmltagname, (obj.xmltagname, xmltagname)
return obj
def _undumpChild(xr, parent, undump=undumpObject):
......
......@@ -1971,7 +1971,7 @@ class RepoWidget(QWidget):
command = 'diff'
else:
command = 'export'
assert command in ('export', 'diff')
assert command in ('export', 'diff'), command
if command == 'export':
# patches should be in chronological order
revs = sorted(self.menuselection)
......
......@@ -318,7 +318,7 @@ class FontEntry(QWidget):
self.clearButton.clicked.connect(self.onClearClicked)
cpath = self.opts['cpath']
assert cpath.startswith('tortoisehg.')
assert cpath.startswith('tortoisehg.'), cpath
self.fname = cpath[11:]
self.setMinimumWidth(ENTRY_WIDTH)
......
......@@ -307,7 +307,7 @@ class StatusWidget(QWidget):
# selections, in order to simplify refresh.
dels = []
for file, oldchanges in self.partials.items():
assert file in self.tv.model().checked
assert file in self.tv.model().checked, file
if oldchanges.excludecount == 0:
self.tv.model().checked[file] = True
dels.append(file)
......@@ -1135,7 +1135,7 @@ class StatusFilterActionGroup(QObject):
@pyqtSlot(str)
def setStatus(self, text):
"""Set the status text"""
assert all(c in self._TYPES for c in text)
assert all(c in self._TYPES for c in text), repr(text)
for c in self._TYPES:
self._actions[c].setChecked(c in text)
......
......@@ -79,11 +79,11 @@ from . import (
)
def parseurl(url):
assert isinstance(url, pycompat.unicode)
assert isinstance(url, pycompat.unicode), repr(url)
return util.url(hglib.fromunicode(url))
def linkify(url):
assert isinstance(url, pycompat.unicode)
assert isinstance(url, pycompat.unicode), repr(url)
u = util.url(hglib.fromunicode(url))
if u.scheme in ('local', 'http', 'https'):
safe = util.hidepassword(hglib.fromunicode(url))
......@@ -1328,7 +1328,7 @@ class SecureDialog(QDialog):
repo = repoagent.rawRepo()
self._url = urlu
u = parseurl(urlu)
assert u.host
assert u.host, repr(u)
uhost = hglib.tounicode(u.host)
self.setWindowTitle(_('Security: ') + uhost)
self.setWindowFlags(self.windowFlags() & \
......
......@@ -599,7 +599,7 @@ class RepoAgent(QObject):
manager = self.parent()
if not manager:
raise RuntimeError('cannot open sub agent of unmanaged repo')
assert isinstance(manager, RepoManager)
assert isinstance(manager, RepoManager), manager
self._subrepoagents[path] = agent = manager.openRepoAgent(path)
return agent
......@@ -611,7 +611,7 @@ class RepoAgent(QObject):
manager = self.parent()
if not manager:
raise RuntimeError('cannot release sub agents of unmanaged repo')
assert isinstance(manager, RepoManager)
assert isinstance(manager, RepoManager), manager
for path in self._subrepoagents:
manager.releaseRepoAgent(path)
self._subrepoagents.clear()
......@@ -724,7 +724,7 @@ class RepoManager(QObject):
@pyqtSlot(int)
def _mapRepositoryChanged(self, flags):
agent = self.sender()
assert isinstance(agent, RepoAgent)
assert isinstance(agent, RepoAgent), agent
self.repositoryChanged.emit(agent.rootPath(), flags)
@pyqtSlot(str)
......@@ -735,7 +735,7 @@ class RepoManager(QObject):
@pyqtSlot(cmdcore.ProgressMessage)
def _mapProgressReceived(self, progress):
agent = self.sender()
assert isinstance(agent, RepoAgent)
assert isinstance(agent, RepoAgent), agent
self.progressReceived.emit(agent.rootPath(), progress)
......
......@@ -63,7 +63,7 @@ class UpdateWidget(cmdui.AbstractCmdWidget):
# always include integer revision
if rev:
assert not isinstance(rev, pycompat.unicode)
assert not isinstance(rev, pycompat.unicode), repr(rev)
try:
ctx = scmutil.revsymbol(self.repo, rev)
if isinstance(ctx.rev(), int): # could be patch name
......
......@@ -518,7 +518,7 @@ class FileSelectionDialog(QDialog):
def onToolSelected(self, tool):
'user selected a tool from the tool combo'
tool = hglib.fromunicode(tool)
assert tool in self.tools
assert tool in self.tools, tool
self.diffpath, self.diffopts, self.mergeopts = self.tools[tool]
self.updateDiffButtons(tool)
......
......@@ -75,7 +75,7 @@ class WctxCleaner(QObject):
def __init__(self, repoagent, parent=None):
super(WctxCleaner, self).__init__(parent)
assert parent is None or isinstance(parent, QWidget)
assert parent is None or isinstance(parent, QWidget), parent
self._repoagent = repoagent
self._cmdsession = cmdcore.nullCmdSession()
self._checkth = CheckThread(repoagent.rawRepo(), self)
......
......@@ -332,12 +332,12 @@ class WebconfModel(QAbstractTableModel):
def getpathmapat(self, row):
"""return pair of (path, localpath) at the specified index"""
assert 0 <= row and row < self.rowCount()
assert 0 <= row and row < self.rowCount(), row
return tuple(hglib.tounicode(e) for e in self._config.items('paths')[row])
def addpathmap(self, path, localpath):
"""add path mapping to serve"""
assert path not in self.paths
assert path not in self.paths, path
self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
try:
self._config.set('paths', hglib.fromunicode(path),
......@@ -364,5 +364,5 @@ class WebconfModel(QAbstractTableModel):
def _indexofpath(self, path):
path = hglib.fromunicode(path)
assert path in self._config['paths']
assert path in self._config['paths'], path
return list(self._config['paths']).index(path)
......@@ -74,7 +74,7 @@ def debuggethostfingerprint(ui, repo, source='default', **opts):
def postinitskel(ui, repo, hooktype, result, pats, **kwargs):
"""create common files in new repository"""
assert hooktype == 'post-init'
assert hooktype == 'post-init', hooktype
if result:
return
dest = ui.expandpath(pats and pats[0] or '.')
......
......@@ -38,7 +38,7 @@ class patchctx(object):
"""
self._path = patchpath
if rev:
assert isinstance(rev, str)
assert isinstance(rev, str), repr(rev)
self._patchname = rev
else:
self._patchname = os.path.basename(patchpath)
......
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