0

When I import a class with parent unittest.TestCase, the tests in that class run. Why is this?

Background: I have functions in one class with parent unittest.TestCase that I want to import into another class, but I won't be able to if importing it also runs those tests.

These answers did not solve the problem

Stop unittest from running code from import module

Run Python unittest when only TestCase imported

Example:

test.py

import unittest
from other_test import OtherTest


class Test(unittest.TestCase):

    def test(self):
        pass


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

other_test.py

import unittest


class OtherTest(unittest.TestCase):

    def test(self):
        self.fail("Why does this run?")```

running python test.py in same folder as these two scripts yields

F.
======================================================================
FAIL: test (other_test.OtherTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "other_test.py", line 7, in test
    self.fail("Why does this run?")
AssertionError: Why does this run?

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

Summary: Why does the failing test run and how do I import the OtherTest class without running its tests?

jsmith2021
  • 15
  • 4
  • 3
    `unittest.main` runs all the unit tests. Your other file includes unit tests. Therefore they are run. How about you put the stuff you need to import in a file that doesn't contain unit tests that you don't want to run? – khelwood Aug 29 '21 at 21:24

0 Answers0