简体   繁体   中英

Python Unit Test Whole-Module Setup

I am attempting to test a webapp with Selenium and Python. The application has a database backup utility that is quite handy. Currently, I have one large class RegressionTest(unittest.TestCase) and it utilizes setUpClass() and tearDownClass() to perform the database backup before and restoration after the test finishes. It's all working great, but I'd really like split these tests into multiple classes (with each test class having its own file) but I can't find a good way to do this without duplicating the backup/restore action.

Further complicating things, I want add the following restrictions:

This needs to be invokable both on my TeamCity CI server (currently using python3 -m teamcity.unittestpy , but I'm flexible so long as I continue to get test reporting) and via PyCharm's standard unit test run configuration. Unfortunately, when invoked through PyCharm, '__main__' == __name__ seems to evaluate to False , which rules out the possibility of a context manager like this:

if '__main__' == __name__:
  with BackupManager():
    if seleniumutils.is_running_under_teamcity():
      runner = TeamcityTestRunner()
    else:
      runner = unittest.TextTestRunner()
    unittest.main(testRunner=runner)

Here's the line that PyCharm is executing: /usr/bin/python3 /Path/To/PyCharm/Installation/helpers/pycharm/_jb_unittest_runner.py --path /Path/To/Project/Test/Code/testregression.py And here is the exact version of _jb_unittest_runner.py in the version of PyCharm that I'm using right now: https://github.com/JetBrains/intellij-community/blob/3486b93168677dbc2519a78f472039bc50ca78be/python/helpers/pycharm/_jb_unittest_runner.py

I can't think of anything that will allow me to do this. I thought maybe multiple inheritance could help, as ugly as that would be. But, I can't come up with any scenario in my head that wouldn't leave each test being invoked a minimum of two times.

So, can anyone come up with a solution that allows me to perform an action exactly once before and after my tests?

If you're looking to run the database backup once per test module, you might consider the setUpModule() and tearDownModule() functions.

Python's unittest will execute setUpModule() and tearDownModule() functions once for each module when these are declared at the module level.

PyCharm will run these when configured with the unittestrunner and I would imagine TeamCity will too since it is using unittest under the covers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM