1

I am following this answer to generate multiple test cases programmatically using the unittest approach.

Here's the code:

import unittest
import my_code

# Test cases (List of input output pairs not explicitly mentioned here)
known_values = [
    {'input': {}, 'output': {}}, 
    {'input': {}, 'output': {}}
]

# Subclass TestCase
class KnownGood(unittest.TestCase):
    def __init__(self, input_params, output):
        super(KnownGood, self).__init__()
        self.input_params = input_params
        self.output = output
    
    def runTest(self):
        self.assertEqual(
            my_code.my_func(self.input_params['a'], self.input_params['b']),
            self.output
        )

# Test suite
def suite():
    global known_values
    suite = unittest.TestSuite()
    suite.addTests(KnownGood(input_params=k['input'], output=k['output']) for k in known_values)
    return suite

if __name__ == '__main__':
    unittest.TextTestRunner().run(suite())

If I open a Python console in PyCharm and run the above code chunk (running unittest.TextTestRunner() without the if condition), the tests run successfully.

..
----------------------------------------------------------------------
Ran 2 tests in 0.002s
OK
<unittest.runner.TextTestResult run=2 errors=0 failures=0>

If I run the test by clicking on the green run button for the if __name__ block in PyCharm, I get the following error:

TypeError: __init__() missing 1 required positional argument: 'output'

Process finished with exit code 1

Empty suite

Empty suite

Python version: 3.7

Project structure: (- denotes folder and . denotes file)

-project_folder
    -tests
      .test_my_code.py
    .my_code.py
Chaos
  • 466
  • 1
  • 5
  • 12

1 Answers1

1

The problem is that PyCharm by default is running unittest or pytest (whatever you have configured as test runner) on the module if it identifies it as containing tests, ignoring the part in if __name__ == '__main__'.
That basically means that it executes unittest.main() instead of your customized version of running the tests.

The only solution I know to get the correct run configuration is to manually add it:

  • select Edit configurations... in the configuration list
  • add a new config using +
  • select Python as type
  • fill in the Script path by your test path (or use the browse button)

Maybe someone knows a more convenient way to force PyCharm to use "Run" instead of "Run Test"...

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46
  • I see. That makes a lot of sense after your explanation (although the "feature" did cause some of my hair to spontaneously part ways with my scalp). :) – Chaos Dec 29 '20 at 19:12
  • 1
    Yeah, I've run into this too, and would have liked an easier solution... – MrBean Bremen Dec 29 '20 at 19:15