When using python's unittest subtest, I am confused regarding how parameters are named and scoped within the sub-test.
The canonical example given in the link above seems to imply that the parameters used within the with self.subtest() clause can be passed as keyword arguments to subTest(). For reference, the example shown is this:
class NumbersTest(unittest.TestCase):
def test_even(self):
"""
Test that numbers between 0 and 5 are all even.
"""
for i in range(0, 6):
with self.subTest(i=i):
self.assertEqual(i % 2, 0)
It is using an ambiguous convention of naming the inner-scoped variable the same as the parameter (i=i). I took this to mean that keyword argument name is taken as the inner scoped variable name. However, when I tried to create my own test, I found that both PyCharm and the python interpreter complained of unresolved references if the keyword argument was not named precisely the same as the outer-scoped variable used as the parameter input.
i.e.:
class NumbersTest(unittest.TestCase):
def test_even(self):
"""
Test that numbers between 0 and 5 are all even.
"""
for i in range(0, 6):
with self.subTest(num=i): # <-- Renamed keyword argument parameter
self.assertEqual(num % 2, 0) # < -- Results in unresolved reference error "num"
How does one pass parameters into the subtest? How are they named and referenced within the subtest code block?
It seems to me that it would be nice if this was expounded on a little bit more in the docs, but the API for subTest(msg=None, **params) states:
...msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly.
So it seems that the keyword arguments passed in **params are used only for test identification when printing test status to the console. They don't get passed in as parameters to the code block in any fashion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With