forked from zooko/pyutil
-
Notifications
You must be signed in to change notification settings - Fork 3
/
assertutil.py
40 lines (33 loc) · 1.19 KB
/
assertutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -*- coding: utf-8; fill-column: 77 -*-
# -*- indent-tabs-mode: nil -*-
# This file is part of pyutil; see README.rst for licensing terms.
"""
Tests useful in assertion checking, prints out nicely formated messages too.
"""
from .humanreadable import hr
def _format_error(prefix, args, kwargs):
if prefix:
msgbuf=[prefix]
if args or kwargs:
msgbuf.append(": ")
else:
msgbuf=[]
if args:
msgbuf.append(", ".join(["%s %s" % tuple(map(hr, (arg, type(arg),))) for arg in args]))
if kwargs:
if args:
msgbuf.append(", ")
msgbuf.append(", ".join(["%s: %s %s" % tuple(map(hr, (k, kwargs[k], type(kwargs[k]),))) for k in sorted(kwargs.keys())]))
return "".join(msgbuf)
def _assert(___cond=False, *args, **kwargs):
if ___cond:
return True
raise AssertionError(_format_error(None, args, kwargs))
def precondition(___cond=False, *args, **kwargs):
if ___cond:
return True
raise AssertionError(_format_error("precondition", args, kwargs))
def postcondition(___cond=False, *args, **kwargs):
if ___cond:
return True
raise AssertionError(_format_error("postcondition", args, kwargs))