I am trying to take a UML class diagram and implement it.
The following code is for testing my resulting Die Class implementation.
import unittest
from Die import Die
class DieTest(unittest.TestCase):
def test_instantiation(self):
d6 = Die()
self.assertEqual(d6.getSides(), 6)
self.assertFalse(d6.getSides() == 3)
d3 = Die(3)
self.assertTrue(d3.getSides() == 3)
self.assertFalse(d3.getSides() == 6)
self.assertFalse(d6.replaceDie())
def test_rolls(self):
d6 = Die()
self.assertTrue(d6.rollDie() < 7)
self.assertFalse(d6.rollDie() > 6)
self.assertTrue(d6.rollTwoDie() < 13)
self.assertTrue(d6.rollTwoDie() <= 12)
self.assertTrue(d6.rollMultiDie(3) > 2)
self.assertTrue(d6.rollMultiDie(4) > 4)
def test_count(self):
d1 = Die()
d2 = Die()
d3 = Die()
d4 = Die()
self.assertTrue(d1.getDieCount() == 4)
def test_replace(self):
d1 = Die()
self.assertFalse(d1.replaceDie())
for x in range(1, 110):
d1.rollDie()
self.assertTrue(d1.replaceDie())
def test_totalRolls(self):
d1 = Die()
for x in range(1, 110):
d1.rollDie()
self.assertTrue(d1.getIncrementRolls() == 109)
d1.resetIncrementRolls()
self.assertTrue(d1.getIncrementRolls() == 0)
if __name__ == "__main__":
unittest.main()
So, what I have come up with is this -
import random
class Die:
def __init__(self, n=6) -> None:
self.numSides = n
self.numDie = 0
self.totalRolls = 0
self.replaceDie = False
pass
def rollDie(self):
return random.randrange(1, self.numSides)
def rollTwoDie(self):
return self.rollDie()+self.rollDie()
def rollMultiDie(self, n=2):
sum = 0
for i in range(n):
sum += self.rollDie()
def getSides(self):
return self.numSides
def getDieCount(self):
return self.numDie
def incrementRolls(self):
self.totalRolls = self.totalRolls + 1
if(self.totalRolls > 100):
self.replaceDie = True
def getIncrementRolls(self):
return self.incrementRolls
def resetIncrementRolls(self):
self.incrementRolls = 0
def replaceDie(self):
return self.replaceDie
My results -
FEEEF
====================================================================== ERROR: test_instantiation (main.DieTest)
---------------------------------------------------------------------- Traceback (most recent call last): File
"---------------------
5 attached files Mar 13, 2022 943 PM/DieTest.py", line 20, in
test_instantiation
self.assertFalse(d6.replaceDie()) TypeError: 'bool' object is not callable
====================================================================== ERROR: test_replace (main.DieTest)
---------------------------------------------------------------------- Traceback (most recent call last): File
"---------------------
5 attached files Mar 13, 2022 943 PM/DieTest.py", line 40, in
test_replace
self.assertFalse(d1.replaceDie()) TypeError: 'bool' object is not callable
====================================================================== ERROR: test_rolls (main.DieTest)
---------------------------------------------------------------------- Traceback (most recent call last): File
"---------------------
5 attached files Mar 13, 2022 943 PM/DieTest.py", line 28, in
test_rolls
self.assertTrue(d6.rollMultiDie(3) > 2) TypeError: '>' not supported between instances of 'NoneType' and 'int'
====================================================================== FAIL: test_count (main.DieTest)
---------------------------------------------------------------------- Traceback (most recent call last): File
"---------------------
5 attached files Mar 13, 2022 943 PM/DieTest.py", line 36, in
test_count
self.assertTrue(d1.getDieCount() == 4) AssertionError: False is not true
====================================================================== FAIL: test_totalRolls (main.DieTest)
---------------------------------------------------------------------- Traceback (most recent call last): File
"---------------------
5 attached files Mar 13, 2022 943 PM/DieTest.py", line 49, in
test_totalRolls
self.assertTrue(d1.getIncrementRolls() == 109) AssertionError: False is not true
---------------------------------------------------------------------- Ran 5 tests in 0.004s
FAILED (failures=2, errors=3)
With out changing any code in DieTest.py, what am I doing wrong with my class implementation?
Related
I am troubling with the code section given below.. when I execute it, I get value error given below.
Segmask = result2
box=[]
[liver_res, num] = measure.label(result1, return_num=True)
region = measure.regionprops(liver_res)
for i in range(num):
box.append(region[i].area)
label_num = box.index(max(box)) + 1
liver_res[liver_res != label_num] = 0
liver_res[liver_res == label_num] = 1
Value error:
Traceback (most recent call last):
File "/content/gdrive/My Drive/LiTS/test.py", line 122, in <module>
predict(args)
File "/content/gdrive/My Drive/LiTS/test.py", line 91, in predict
label_num = box.index(max(box)) + 1
ValueError: max() arg is an empty sequence
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!
I am using the following code to extract some features from audio files, an write them in numpy array files:
def calc_ceps(file_list, index, label, method=None, n_mfcc=None, s_rate=None):
'''Calculates and saves ceps'''
if method == None:
method = 'librosa'
if s_rate == None:
s_rate = 22050
if n_mfcc == None:
n_mfcc = 20
print 'Wave to Ceps:'
total = len(file_list)
for i, file in enumerate(file_list):
if method == 'librosa':
ceps = np.array(librosa.feature.mfcc(*read_wave(file), n_mfcc=n_mfcc))
ceps.shape = (len(ceps[0]), n_mfcc)
elif method == 'talkbox':
ceps = mfcc(read_wave(file)[0])[0]
write_data('ceps', ceps, label[i], file)
progress(i, total)
progress(199, 199)
the function progress(current, total) prints the progress, file_popul() provides the file list and write_data() writes the numpy array to file.
Calling:
>>>get_ceps(*file_popul())()
Whilst the calc_ceps() functions works 100% as intended (i.e. saves numpy arrays for ALL the files it gets), when it is over (i.e. written all the files) I get the following Traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
pdb output with steps:
>>> calc_ceps(*file_popul())()
Wave to Ceps:
99%> ~/final_project/code/utilities.py(122)calc_ceps()
-> progress(199, 199)
(Pdb) s
--Call--
> ~/python/final_project/code/utilities.py(16)progress()
-> def progress(current, maximum):
(Pdb) s
> ~/python/final_project/code/utilities.py(18)progress()
-> ratio = round((float(current) / float(maximum)), 2) * 100
(Pdb) s
> ~/python/final_project/code/utilities.py(19)progress()
-> if ratio < 100:
(Pdb) s
> ~/python/final_project/code/utilities.py(22)progress()
-> elif ratio == 100:
(Pdb) s
> ~/python/final_project/code/utilities.py(23)progress()
-> sys.stdout.write("\r100% done! \n")
(Pdb) s
100% done!
--Return--
> ~/python/final_project/code/utilities.py(23)progress()->None
->sys.stdout.write("\r100% done! \n")
(Pdb) s
--Return--
> ~/python/final_project/code/utilities.py(122)calc_ceps()->None
-> progress(199, 199)
(Pdb) s
TypeError: "'NoneType' object is not callable"
> <stdin>(1)<module>()
(Pdb) s
--Return--
> <stdin>(1)<module>()->None
(Pdb) s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>>
using python 2.7
Thanks in Advance.
EDIT: Commented out progress() usage, this is what I get in pdb:
>>> calc_ceps(*file_enum())()
Wave to Ceps:
--Return--
> /home/mpir/python/final_project/code/utilities.py(121)calc_ceps()->None
-> import pdb; pdb.set_trace()
(Pdb) s
TypeError: "'NoneType' object is not callable"
> <stdin>(1)<module>()
(Pdb) s
--Return--
> <stdin>(1)<module>()->None
(Pdb) s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>>
Ain't it strange?
You calc_ceps function has no return statement, so calc_ceps(*file_popul()) returns None, and you try to call it once again with one more pair of braces: calc_ceps(*file_popul())()
I want to add a custom assert method to a TestCase subclass. I tried to copy my implementation from the unittest module so that it would match the behaviour of the regular TestCase as closely as possible. (I would prefer to just delegate to self.assertEqual() but this causes even more backtrace noise, see below.) The unittest module seems to automatically hide some internal details of its implementation when reporting failed assertions.
import unittest
class MyTestCase(unittest.TestCase):
def assertLengthIsOne(self, sequence, msg=None):
if len(sequence) != 1:
msg = self._formatMessage(msg, "length is not one")
raise self.failureException(msg)
class TestFoo(MyTestCase):
seq = (1, 2, 3, 4, 5)
def test_stock_unittest_assertion(self):
self.assertEqual(len(self.seq), 1)
def test_custom_assertion(self):
self.assertLengthIsOne(self.seq)
unittest.main()
The output of this is as such:
amoe#vuurvlieg $ python unittest-demo.py
FF
======================================================================
FAIL: test_custom_assertion (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "unittest-demo.py", line 16, in test_custom_assertion
self.assertLengthIsOne(self.seq)
File "unittest-demo.py", line 7, in assertLengthIsOne
raise self.failureException(msg)
AssertionError: length is not one
======================================================================
FAIL: test_stock_unittest_assertion (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "unittest-demo.py", line 13, in test_stock_unittest_assertion
self.assertEqual(len(self.seq), 1)
AssertionError: 5 != 1
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=2)
Note that the custom assert method causes a stack trace with two frames, one inside the method itself, whereas the stock unittest method only has one frame, the relevant line in the user's code. How can I apply this frame-hiding behaviour to my own method?
This question was answered by Peter Otten on comp.lang.python.
Move MyTestCase in a separate module and define a global variable __unittest = True.
$ cat mytestcase.py
import unittest
__unittest = True
class MyTestCase(unittest.TestCase):
def assertLengthIsOne(self, sequence, msg=None):
if len(sequence) != 1:
msg = self._formatMessage(msg, "length is not one")
raise self.failureException(msg)
$ cat mytestcase_demo.py
import unittest
from mytestcase import MyTestCase
class TestFoo(MyTestCase):
seq = (1, 2, 3, 4, 5)
def test_stock_unittest_assertion(self):
self.assertEqual(len(self.seq), 1)
def test_custom_assertion(self):
self.assertLengthIsOne(self.seq)
if __name__ == "__main__":
unittest.main()
$ python mytestcase_demo.py
FF
======================================================================
FAIL: test_custom_assertion (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mytestcase_demo.py", line 11, in test_custom_assertion
self.assertLengthIsOne(self.seq)
AssertionError: length is not one
======================================================================
FAIL: test_stock_unittest_assertion (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mytestcase_demo.py", line 8, in test_stock_unittest_assertion
self.assertEqual(len(self.seq), 1)
AssertionError: 5 != 1
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=2)
$
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!