Search code examples
pythonunit-testingnameerror

Python unit test - NameError: name 'upper' is not defined


Using Python 3.x. When running the test case for the following code, I get the error - NameError: name 'upper' is not defined. I am attaching the file to test, the File_P_third file where is the code, and the unit test file test_upper.

File File_P_third:

def upper_text(text):
    return text.upper()

File test_upper:

import unittest
import File_P_third


class TestUpper(unittest.TestCase):
    """docstring for ClassName"""
    def test_one_word(self):
        text = 'hello!'
        result = upper.upper_text(text)
        self.assertEqual(result, 'HELLO!')
        

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

My cmd`s exit text:

D:\Дохуя программист\Projects>python test_upper.py
E
======================================================================
ERROR: test_one_word (__main__.TestUpper)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_upper.py", line 9, in test_one_word
    result = upper.upper_text(text)
NameError: name 'upper' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

All files is in one directory and I still cant understand why is doesnt work. Can`t search the same problem in internet((


Solution

  • Replace import File_P_third with from File_P_third import upper_text. Call your function this way result = upper_text(text). Also make sure, both files File_P_third.py and test_upper.py are in the same directory.

    Below you'll find the complete code for your file File_P_third.py:

    import unittest
    from File_P_third import upper_text
    
    
    class TestUpper(unittest.TestCase):
        """docstring for ClassName"""
        def test_one_word(self):
            text = 'hello!'
            result = upper_text(text)
            self.assertEqual(result, 'HELLO!')
            
    
    if __name__ == '__main__':
        unittest.main()