Python unittest报错:TestSequenceFunctions未定义的原因排查
Let's break down exactly what's going on here. First, let's recap your code and the error you're seeing:
Your Code
if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(unittest.TestSequenceFunctions) unittest.TextTestRunner(verbosity=2).run(suite)
The Error
Traceback (most recent call last): File "test_CGSSv00.py", line 109, in <module> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) NameError: name 'TestSequenceFunctions' is not defined
The Root Cause
This error is straightforward: the TestSequenceFunctions class you're trying to use doesn't exist in your script's current namespace. Here's why that's happening:
You didn't define the test class locally
TestSequenceFunctionsisn't a built-in class in theunittestmodule. It's supposed to be a custom test class you write that inherits fromunittest.TestCase. If you haven't written this class anywhere in your script, Python has no idea what it refers to.You didn't import the class from another module
IfTestSequenceFunctionsis defined in a different.pyfile (like a separate test module), you need to explicitly import it into your current script—otherwise, Python can't access it.You had a syntax mistake in your code
Your original code tried to useunittest.TestSequenceFunctions—but again, that class doesn't live inside theunittestmodule. That's a typo; you should be referencing your own custom class directly (not prefixed withunittest.).
Fixes to Try
Option 1: Define the Test Class in Your Script
Add your custom test class above the if __name__ == '__main__' block:
import unittest # Define your test class first class TestSequenceFunctions(unittest.TestCase): def test_example(self): # Add your test logic here self.assertEqual(2 + 2, 4) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) unittest.TextTestRunner(verbosity=2).run(suite)
Option 2: Import the Class from Another Module
If TestSequenceFunctions is in a file named my_test_classes.py, import it like this:
import unittest from my_test_classes import TestSequenceFunctions # Import the existing class if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) unittest.TextTestRunner(verbosity=2).run(suite)
内容的提问来源于stack exchange,提问作者Python Jim

