File: assertutil.py

package info (click to toggle)
python-pyutil 3.3.2-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 884 kB
  • sloc: python: 7,198; makefile: 6
file content (40 lines) | stat: -rw-r--r-- 1,215 bytes parent folder | download
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))