Avoid repetition in tests when using Python's unittest subTest?2019 Community Moderator ElectionHow should I unit test threaded code?How do I test a private function or a class that has private methods, fields or inner classes?Unit Testing C CodeIs Unit Testing worth the effort?Running unittest with typical test directory structureHow does Python's super() work with multiple inheritance?if/else in Python's list comprehension?Python unittest - opposite of assertRaises?How can i make the attached pyunit python script search for tests in subfoldersHow to convert python unittests to py.test when having global fixtures?
What is IP squat space
Meaning of "SEVERA INDEOVI VAS" from 3rd Century slab
Good allowance savings plan?
Make a transparent 448*448 image
Can elves maintain concentration in a trance?
How to generate globally unique ids for different tables of the same database?
Why using two cd commands in bash script does not execute the second command
Making a sword in the stone, in a medieval world without magic
How do I hide Chekhov's Gun?
Font with correct density?
Fill color and outline color with the same value
How to get the name of the database a stored procedure is executed in within that stored procedure while it's executing?
Schematic conventions for different supply rails
How could a scammer know the apps on my phone / iTunes account?
Does splitting a potentially monolithic application into several smaller ones help prevent bugs?
Employee lack of ownership
Bash replace string at multiple places in a file from command line
Can the damage from a Talisman of Pure Good (or Ultimate Evil) be non-lethal?
Why are the outputs of printf and std::cout different
Is it normal that my co-workers at a fitness company criticize my food choices?
Happy pi day, everyone!
Is having access to past exams cheating and, if yes, could it be proven just by a good grade?
How could a female member of a species produce eggs unto death?
What are the possible solutions of the given equation?
Avoid repetition in tests when using Python's unittest subTest?
2019 Community Moderator ElectionHow should I unit test threaded code?How do I test a private function or a class that has private methods, fields or inner classes?Unit Testing C CodeIs Unit Testing worth the effort?Running unittest with typical test directory structureHow does Python's super() work with multiple inheritance?if/else in Python's list comprehension?Python unittest - opposite of assertRaises?How can i make the attached pyunit python script search for tests in subfoldersHow to convert python unittests to py.test when having global fixtures?
I'm having trouble trying to come up with a elegant solution for this situation.
Let's say I have a unittest in Python that will test several elements from an iterable. Since this iterable is costly to build in memory, I want to build it only once trough the setUpClass method. Then, in each test, I want to sequentially pass each element in the iterable to the test, which I can to using the context manager and the subTest method. This is all fine.
The following code is an example of a mock test case doing exactly what I've described:
import unittest
class NumberTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.numbers = []
for x in range(1000):
cls.numbers.append(x)
@classmethod
def tearDownClass(cls):
del cls.numbers
def test_number_is_even(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 0)
def test_number_is_odd(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 1)
def test_number_is_positive(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n > 0)
def test_number_is_negative(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n < 0)
if __name__ == '__main__':
unittest.main()
What bugs me here is that the lines for n in self.numbers: with self.subTest(current_number=n): . . . are repeated for each test method. Is there any way to avoid this? I know I could simply clump all self.assert statements together in a single method, but this defeats the purpose of having different tests for different aspects in the first place.
In my mind the "ideal" solution would be to, somehow, yield the values from the iterable (maybe through the setUp method? No clue) and pass these values to each test method before yielding the next one. but I have no idea how to actually do this, especially since it involves a context manager... Has anyone got any other solutions, or are there simply no workarounds for this?
python python-3.x unit-testing python-unittest
add a comment |
I'm having trouble trying to come up with a elegant solution for this situation.
Let's say I have a unittest in Python that will test several elements from an iterable. Since this iterable is costly to build in memory, I want to build it only once trough the setUpClass method. Then, in each test, I want to sequentially pass each element in the iterable to the test, which I can to using the context manager and the subTest method. This is all fine.
The following code is an example of a mock test case doing exactly what I've described:
import unittest
class NumberTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.numbers = []
for x in range(1000):
cls.numbers.append(x)
@classmethod
def tearDownClass(cls):
del cls.numbers
def test_number_is_even(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 0)
def test_number_is_odd(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 1)
def test_number_is_positive(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n > 0)
def test_number_is_negative(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n < 0)
if __name__ == '__main__':
unittest.main()
What bugs me here is that the lines for n in self.numbers: with self.subTest(current_number=n): . . . are repeated for each test method. Is there any way to avoid this? I know I could simply clump all self.assert statements together in a single method, but this defeats the purpose of having different tests for different aspects in the first place.
In my mind the "ideal" solution would be to, somehow, yield the values from the iterable (maybe through the setUp method? No clue) and pass these values to each test method before yielding the next one. but I have no idea how to actually do this, especially since it involves a context manager... Has anyone got any other solutions, or are there simply no workarounds for this?
python python-3.x unit-testing python-unittest
Welcome jfaccioni. You say you test the elements of an iterable - unit-testing, however, is to test code to see if there are any bugs in the code. Maybe this is a misunderstanding. If you are trying to find bugs in code, could you please show that code? Otherwise, we are probably not talking about unit-testing here.
– Dirk Herrmann
Mar 7 at 20:35
Thanks for the comment. What I want to do is to test a class I've made. In my actual code, instances of this class are built by reading input values from a long file (microscopy detection data), one instance per line. For the tests I've created a mock data file from which I instantiate mock instances of the class in thesetUpClassmethod. But now that I wrote this, I realize that this may not be unit-testing at all... since I'm testing different instances of the class, not the code itself. I'm not used to unit-tests so I may have approached the problem with the wrong mindset.
– jfaccioni
Mar 10 at 3:41
add a comment |
I'm having trouble trying to come up with a elegant solution for this situation.
Let's say I have a unittest in Python that will test several elements from an iterable. Since this iterable is costly to build in memory, I want to build it only once trough the setUpClass method. Then, in each test, I want to sequentially pass each element in the iterable to the test, which I can to using the context manager and the subTest method. This is all fine.
The following code is an example of a mock test case doing exactly what I've described:
import unittest
class NumberTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.numbers = []
for x in range(1000):
cls.numbers.append(x)
@classmethod
def tearDownClass(cls):
del cls.numbers
def test_number_is_even(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 0)
def test_number_is_odd(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 1)
def test_number_is_positive(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n > 0)
def test_number_is_negative(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n < 0)
if __name__ == '__main__':
unittest.main()
What bugs me here is that the lines for n in self.numbers: with self.subTest(current_number=n): . . . are repeated for each test method. Is there any way to avoid this? I know I could simply clump all self.assert statements together in a single method, but this defeats the purpose of having different tests for different aspects in the first place.
In my mind the "ideal" solution would be to, somehow, yield the values from the iterable (maybe through the setUp method? No clue) and pass these values to each test method before yielding the next one. but I have no idea how to actually do this, especially since it involves a context manager... Has anyone got any other solutions, or are there simply no workarounds for this?
python python-3.x unit-testing python-unittest
I'm having trouble trying to come up with a elegant solution for this situation.
Let's say I have a unittest in Python that will test several elements from an iterable. Since this iterable is costly to build in memory, I want to build it only once trough the setUpClass method. Then, in each test, I want to sequentially pass each element in the iterable to the test, which I can to using the context manager and the subTest method. This is all fine.
The following code is an example of a mock test case doing exactly what I've described:
import unittest
class NumberTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.numbers = []
for x in range(1000):
cls.numbers.append(x)
@classmethod
def tearDownClass(cls):
del cls.numbers
def test_number_is_even(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 0)
def test_number_is_odd(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertEqual(n % 2, 1)
def test_number_is_positive(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n > 0)
def test_number_is_negative(self):
for n in self.numbers:
with self.subTest(current_number=n):
self.assertTrue(n < 0)
if __name__ == '__main__':
unittest.main()
What bugs me here is that the lines for n in self.numbers: with self.subTest(current_number=n): . . . are repeated for each test method. Is there any way to avoid this? I know I could simply clump all self.assert statements together in a single method, but this defeats the purpose of having different tests for different aspects in the first place.
In my mind the "ideal" solution would be to, somehow, yield the values from the iterable (maybe through the setUp method? No clue) and pass these values to each test method before yielding the next one. but I have no idea how to actually do this, especially since it involves a context manager... Has anyone got any other solutions, or are there simply no workarounds for this?
python python-3.x unit-testing python-unittest
python python-3.x unit-testing python-unittest
asked Mar 6 at 18:42
jfaccionijfaccioni
1714
1714
Welcome jfaccioni. You say you test the elements of an iterable - unit-testing, however, is to test code to see if there are any bugs in the code. Maybe this is a misunderstanding. If you are trying to find bugs in code, could you please show that code? Otherwise, we are probably not talking about unit-testing here.
– Dirk Herrmann
Mar 7 at 20:35
Thanks for the comment. What I want to do is to test a class I've made. In my actual code, instances of this class are built by reading input values from a long file (microscopy detection data), one instance per line. For the tests I've created a mock data file from which I instantiate mock instances of the class in thesetUpClassmethod. But now that I wrote this, I realize that this may not be unit-testing at all... since I'm testing different instances of the class, not the code itself. I'm not used to unit-tests so I may have approached the problem with the wrong mindset.
– jfaccioni
Mar 10 at 3:41
add a comment |
Welcome jfaccioni. You say you test the elements of an iterable - unit-testing, however, is to test code to see if there are any bugs in the code. Maybe this is a misunderstanding. If you are trying to find bugs in code, could you please show that code? Otherwise, we are probably not talking about unit-testing here.
– Dirk Herrmann
Mar 7 at 20:35
Thanks for the comment. What I want to do is to test a class I've made. In my actual code, instances of this class are built by reading input values from a long file (microscopy detection data), one instance per line. For the tests I've created a mock data file from which I instantiate mock instances of the class in thesetUpClassmethod. But now that I wrote this, I realize that this may not be unit-testing at all... since I'm testing different instances of the class, not the code itself. I'm not used to unit-tests so I may have approached the problem with the wrong mindset.
– jfaccioni
Mar 10 at 3:41
Welcome jfaccioni. You say you test the elements of an iterable - unit-testing, however, is to test code to see if there are any bugs in the code. Maybe this is a misunderstanding. If you are trying to find bugs in code, could you please show that code? Otherwise, we are probably not talking about unit-testing here.
– Dirk Herrmann
Mar 7 at 20:35
Welcome jfaccioni. You say you test the elements of an iterable - unit-testing, however, is to test code to see if there are any bugs in the code. Maybe this is a misunderstanding. If you are trying to find bugs in code, could you please show that code? Otherwise, we are probably not talking about unit-testing here.
– Dirk Herrmann
Mar 7 at 20:35
Thanks for the comment. What I want to do is to test a class I've made. In my actual code, instances of this class are built by reading input values from a long file (microscopy detection data), one instance per line. For the tests I've created a mock data file from which I instantiate mock instances of the class in the
setUpClass method. But now that I wrote this, I realize that this may not be unit-testing at all... since I'm testing different instances of the class, not the code itself. I'm not used to unit-tests so I may have approached the problem with the wrong mindset.– jfaccioni
Mar 10 at 3:41
Thanks for the comment. What I want to do is to test a class I've made. In my actual code, instances of this class are built by reading input values from a long file (microscopy detection data), one instance per line. For the tests I've created a mock data file from which I instantiate mock instances of the class in the
setUpClass method. But now that I wrote this, I realize that this may not be unit-testing at all... since I'm testing different instances of the class, not the code itself. I'm not used to unit-tests so I may have approached the problem with the wrong mindset.– jfaccioni
Mar 10 at 3:41
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55030112%2favoid-repetition-in-tests-when-using-pythons-unittest-subtest%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55030112%2favoid-repetition-in-tests-when-using-pythons-unittest-subtest%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Welcome jfaccioni. You say you test the elements of an iterable - unit-testing, however, is to test code to see if there are any bugs in the code. Maybe this is a misunderstanding. If you are trying to find bugs in code, could you please show that code? Otherwise, we are probably not talking about unit-testing here.
– Dirk Herrmann
Mar 7 at 20:35
Thanks for the comment. What I want to do is to test a class I've made. In my actual code, instances of this class are built by reading input values from a long file (microscopy detection data), one instance per line. For the tests I've created a mock data file from which I instantiate mock instances of the class in the
setUpClassmethod. But now that I wrote this, I realize that this may not be unit-testing at all... since I'm testing different instances of the class, not the code itself. I'm not used to unit-tests so I may have approached the problem with the wrong mindset.– jfaccioni
Mar 10 at 3:41