Search code examples
pythonpython-2.7python-unittestnose

Python unittest: 'self' is not defined


I am new to unittest. I am trying to skip test cases based on values in a list.

class UESpecTest(unittest.TestCase):
    global testcases_exec_list
    testcases = []
    testcases = testcases_exec_list
    @unittest.skipIf('0' not in self.testcases, "Testcase input not given")
    def test_retrieve_spec_info(self):
        read_spec_info.open_csv(self.spec_info)
        assert (bool(self.spec_info) == True) #Raise assertion if dictionary is empty

I am getting the below error

  File "test_ue_cap_main.py", line 39, in UESpecTest
    @unittest.skipIf('0' not in self.testcases, "Testcase input not given") 
NameError: name 'self' is not defined

I am not sure why self is undefined here.


Solution

  • self is not a magic variable like this in Java and Javascript. That is why you have to define it as the first parameter in methods. If self isn't defined as a parameter or some other kind of variable, it's just not defined, like any other variable. Its name is purely conventional.

    (Although if self was equivalent to this it still wouldn't make sense because there's no instance in question, just the class)

    When you're at the class level, you can use other variables at the class level normally. For example:

    class A:
        x = 1
        y = 2
        z = x + y  # 3
    

    So you can remove the self and just say '0' not in testcases.

    Also, you have some weird stuff going on:

    global testcases_exec_list
    testcases = []
    testcases = testcases_exec_list
    
    1. The line testcases = [] is completely redundant because you immediately override it.
    2. The line global testcases_exec_list is probably useless (depending on the rest of the class definition) because global is for assignment, not access.
    3. Why are you defining testcases if you already have testcases_exec_list? Do you understand that this makes them the same list, rather than making a copy?