Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 1 | import warnings |
| 2 | |
| 3 | # The warnings module isn't easily tested, because it relies on module |
| 4 | # globals to store configuration information. We need to extract the |
| 5 | # current settings to avoid bashing them while running tests. |
| 6 | |
| 7 | _filters = [] |
| 8 | _showwarning = None |
| 9 | |
| 10 | def showwarning(message, category, filename, lineno, file=None): |
Jeremy Hylton | b6d2f3e | 2003-07-11 20:22:55 +0000 | [diff] [blame^] | 11 | i = filename.find("Lib") |
Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 12 | filename = filename[i:] |
| 13 | print "%s:%s: %s: %s" % (filename, lineno, category.__name__, message) |
| 14 | |
| 15 | def monkey(): |
| 16 | global _filters, _showwarning |
| 17 | _filters = warnings.filters[:] |
| 18 | _showwarning = warnings.showwarning |
| 19 | warnings.showwarning = showwarning |
| 20 | |
| 21 | def unmonkey(): |
| 22 | warnings.filters = _filters[:] |
| 23 | warnings.showwarning = _showwarning |
| 24 | |
| 25 | def test(): |
| 26 | for item in warnings.filters: |
| 27 | print (item[0], item[1] is None, item[2].__name__, item[3] is None, |
| 28 | item[4]) |
| 29 | hello = "hello world" |
| 30 | for i in range(4): |
| 31 | warnings.warn(hello) |
| 32 | warnings.warn(hello, UserWarning) |
| 33 | warnings.warn(hello, DeprecationWarning) |
| 34 | for i in range(3): |
| 35 | warnings.warn(hello) |
| 36 | warnings.filterwarnings("error", "", Warning, "", 0) |
| 37 | try: |
| 38 | warnings.warn(hello) |
| 39 | except Exception, msg: |
| 40 | print "Caught", msg.__class__.__name__ + ":", msg |
| 41 | else: |
| 42 | print "No exception" |
| 43 | warnings.resetwarnings() |
| 44 | try: |
| 45 | warnings.filterwarnings("booh", "", Warning, "", 0) |
| 46 | except Exception, msg: |
| 47 | print "Caught", msg.__class__.__name__ + ":", msg |
| 48 | else: |
| 49 | print "No exception" |
| 50 | |
| 51 | monkey() |
| 52 | test() |
| 53 | unmonkey() |