I have a python module containing (amongst other functions) this piece of code:
def check_color_range(*argv):
"""
Abbreviated documentation and other tests.
>>> check_color_range(23, -1, 99, 10000)
Traceback (most recent call last):
...
TypeError: Falscher Farbwert -1!
"""
for c in argv:
if c < 0 or c > 255:
raise TypeError('Falscher Farbwert ' + str(c) + '!')
When I run this using doctest like so: python -m doctest -v demo.py, I get the following output:
Trying:
check_color_range(23, -1, 99, 10000)
Expecting:
Traceback (most recent call last):
...
TypeError: Falscher Farbwert -1!
**********************************************************************
File "C:\az\code_camp_python\src\EigeneProgramme\Tag3\arcade_base\demo.py", line 5, in demo.check_color_range
Failed example:
check_color_range(23, -1, 99, 10000)
Expected:
Traceback (most recent call last):
...
TypeError: Falscher Farbwert -1!
Got:
Traceback (most recent call last):
File "C:\az\miniconda3\envs\py37\lib\doctest.py", line 1329, in __run
compileflags, 1), test.globs)
File "<doctest demo.check_color_range[0]>", line 1, in <module>
check_color_range(23, -1, 99, 10000)
File "C:\az\code_camp_python\src\EigeneProgramme\Tag3\arcade_base\demo.py", line 12, in check_color_range
raise TypeError('Falscher Farbwert ' + str(c) + '!')
TypeError: Falscher Farbwert -1!
1 items had no tests:
demo
**********************************************************************
1 items had failures:
1 of 1 in demo.check_color_range
1 tests in 2 items.
0 passed and 1 failed.
***Test Failed*** 1 failures.
For me the expected and the actual Errors look the same, but I may be missing something. I already compared whitespace etc., which seems to be the same.
I then tried to paste the complete Traceback from the "Got:" section into the testcase - and I'm still get the failed test, so I guess I must be doing something wrong.
I'd be very happy, if you could give me a heads-up.
On line 8 you have: TypeError: Falscher Farbwert -1!____ (4 blank spaces at the end)
You should replace it with: TypeError: Falscher Farbwert -1!
Related
Title basically says everything
Code link: https://www.codechef.com/problems/HS08TEST
words = input()
x = words.split(' ')
withdraw = float(x[0])
init = float(x[1])
if(withdraw%5==0 and init>withdraw):
final=init-withdraw-0.5
print(final)
elif(init<(withdraw+0.5) or withdraw%5!=0):
print(init)
Error:
Traceback (most recent call last):
File "prog.py", line 1, in <module>
File "<string>", line 1
30 120
^
SyntaxError: unexpected EOF while parsing
I am trying to understand how to use the pdb.post_mortem() method.
for this given file
# expdb.py
import pdb
import trace
def hello():
a = 6 * 9
b = 7 ** 2
c = a * b
d = 4 / 0
print(c)
tracer = trace.Trace()
Command prompt
'''
# first Try
λ python -i expdb.py
>>> pdb.post_mortem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\pdb.py", line 1590, in post_mortem
raise ValueError("A valid traceback must be passed if no "
ValueError: A valid traceback must be passed if no exception is being handled
'''
'''
# Second Try
λ python -i expdb.py
>>> pdb.post_mortem(traceback=tracer.run('hello()') )
--- modulename: trace, funcname: _unsettrace
trace.py(77): sys.settrace(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\trace.py", line 500, in run
self.runctx(cmd, dict, dict)
File "C:\Program Files\Anaconda3\lib\trace.py", line 508, in runctx
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "expdb.py", line 8, in hello
d = 4 / 0
ZeroDivisionError: division by zero
>>>
The post_mortem method wants a traceback object, not a Trace object. Traceback objects can be acquired from sys.exc_info()[2] inside of an except block, or you can simply call pdb.post_mortem() with no arguments directly (in the except block).
But either way, you must catch the exception before you can debug it.
I have a problem with the following function in python (where swap is a function that I have previously created and that works fine):
def swap (cards):
"""
>>> swap('FBFFFBFFBF')
'BFBBBFBBFB'
>>> swap('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFBB'
>>> swap('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'BBFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFB'
"""
invert=""
for i in cards:
if i is "B":
invert+="F"
else:
invert+="B"
return (invert)
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
indices=""
for pos, i in enumerate(cards):
if i =="B":
indices+=str(pos)
first= int(indices[0])
last= int(indices[-1])
prefix= cards [:first]
middle= cards [first:last+1]
suffix= cards [last+1:]
middle2=swap(middle)
return (prefix+middle2+suffix)
def turns (cards):
"""
>>> turns('FBFFFBFFBF')
3
>>> turns('BFFBFBFFFBFBBBFBBBBFF')
6
>>> turns('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
14
"""
turn=0
while cards != 'F'*len(cards):
cards=swap2(cards)
turn+=1
return (turn)
if __name__ == '__main__':
import doctest
doctest.testmod()
when I run this function it works fine but if I use doctest to see if there are mistakes it tells me:
TypeError: 'str' object is not an iterator
I don't know where this error comes from.
Can anyone help me?
complete output of the doctest:
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 25, in __main__.swap2
Failed example:
next('FBFFFBFFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 27, in __main__.swap2
Failed example:
next('BFFBFBFFFBFBBBFBBBBFF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[1]>", line 1, in <module>
next('BFFBFBFFFBFBBBFBBBBFF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 29, in __main__.swap2
Failed example:
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[2]>", line 1, in <module>
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
TypeError: 'str' object is not an iterator
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
# …
The function is called swap2 but within the doctests, you are using next which happens to be a built-in function that does something completely different. That’s why you are seeing that error.
At times like this, it’s really important to actually look at the error messages. It clearly told you what was called:
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
So if you don’t know where that was supposed to come from, then check out the error message. Doctest will tell you what it is executing: swap2[0], swap2[1], etc. tells you the function name the docstring that is being executed is by doctest and which test case it is (0 is the first, 1 the second etc.). It even gives you the line number (within the doctest case) where the error appeared, and of course the line that was causing the error. So use that information to go to the problematic code, and figure out what the problem is.
Suppose I am given the following traceback:
Traceback (most recent call last):
File "<wingdb_compile>", line 3, in <module>
File "C:\Python34\lib\ftplib.py", line 419, in login
resp = self.sendcmd('PASS ' + passwd)
File "C:\Python34\lib\ftplib.py", line 272, in sendcmd
return self.getresp()
File "C:\Python34\lib\ftplib.py", line 245, in getresp
raise error_perm(resp)
ftplib.error_perm: 530 Login incorrect.
I have managed to extract the Error details but what has stumped me is how would I extract the line:
File "<wingdb_compile>", line 3, in <module>
I was looking at methods in the trace back package but wondered if any one had experience with that here
The function traceback.format_exc is built primarily for this
This is like print_exc(limit) but returns a string instead of printing to a file.
>>> import traceback
>>> try:
... x = 2/0
... except:
... error = traceback.format_exc()
...
>>> error
'Traceback (most recent call last):\n File "<stdin>", line 2, in <module>\nZeroDivisionError: division by zero\n'
>>> linesoferror = error.split('\n')
>>> linesoferror
['Traceback (most recent call last):', ' File "<stdin>", line 2, in <module>', 'ZeroDivisionError: division by zero', '']
So now you wanted the first line then you can simply use
>>> linesoferror[1]
' File "<stdin>", line 2, in <module>'
Voila! You have what you want
ALERT - Valid for Python 2.4.1 and above
I have this script
import unittest,itertools,random
##testclass
class Testcomb(unittest.TestCase):
def test_input(self):
self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5)
def calculate_combinations(combin,target):
counter = 0
for L in range(0, len(combin)+1):
for subset in itertools.combinations(combin, L):
if sum(subset) == target: counter= counter+1
return counter
comb1=[1,2,3,4]
if __name__=='__main__': unittest.main()
but the self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5) does not intercept the exception giving me this error:
E..
======================================================================
ERROR: test_input (__main__.Testcomb)
----------------------------------------------------------------------
Traceback (most recent call last):
File "total_combination.py", line 25, in test_input
self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (errors=1)
Can anyone help?
The exception that makes your test fail is triggered by the dict(comb1) part of the assertion.
>>> comb1=[1,2,3,4]
>>> dict(comb1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence
On the contrary, the assertRaises will return True only if it is the callable (in your case calculate_combinations) to trigger it.
HTH!