5

How can I write test cases like below in Python 2.7? I don't have an option of using Pytest/Python3.

import unittest

class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        tests = [
            ('foo', 'FOO'),
            ('too', 'TOO'),
            ('poo', 'POO'),
        ]
        for value, expected in tests:
            with self.subTest(value=value):
                self.assertEqual(value.upper(), expected)

if __name__ == '__main__':
    unittest.main()

In summary, I am looking for a substitute for "parameterized fixtures in Pytest" and "subtest feature of unittest" in Python 2.7.

I can do something like below in Python 2.7 but a first failed assertion will bail out of a test. Since I have only one method in my Testcase therefore only one test runs - despite that one test evaluating many assertions.

class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')
        self.assertEqual('too'.upper(), 'TOO')
        self.assertEqual('poo'.upper(), 'POO')

if __name__ == '__main__':
    unittest.main()

If I want to test each assertion separately I will have to put each one in its own method which will be cumbersome.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ThinkGeek
  • 4,749
  • 13
  • 44
  • 91
  • 1
    Use [`unittest2`](https://pypi.org/project/unittest2/), which backports many of the newer features. – jonrsharpe Feb 26 '19 at 17:11
  • Possible duplicate of [How do you generate dynamic (parameterized) unit tests in python?](https://stackoverflow.com/questions/32899/how-do-you-generate-dynamic-parameterized-unit-tests-in-python) – jonrsharpe Feb 26 '19 at 17:15

0 Answers0