NameError: name 'METHOD_NAME' is not defined Python Unittest

Viewed 641

I've got the following project structure: enter image description here

The code for each of the files are as follows (nothing is included in init.py):

my_sum.py

from service import calculate_sum

def main():
    calculate_sum.create_sum()

if __name__ == "__main__":
    main()

calculate_sum.py:

def calculate(arg):
    total = 0
    for val in arg:
        total += val
    return total

def create_sum():
    print("hello")
    total = calculate([5, 5])
    print(total)

test_sum.py:

import unittest

from dir import *

class TestSum(unittest.TestCase):
    def test_list_int(self):
        """
        Test that it can sum a list of integers
        """
        data = [1, 2, 3]
        result = calculate(data)
        self.assertEqual(result, 6)

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

As you can see, this is a very simple program that calculates the sum of a list. Note: I am mimicking a larger project hence why I've got multiple (rather unnecessary) calls to methods.

When I run python -m unittest discover -s test/ from the MainDir directory, I get an error:

testsum.py", line 11, in test_list_int result = calculate(data) NameError: name 'calculate' is not defined

However, if I change the "calculate" method to "sum" (i.e. the below), my test runs fine. Note: I should note that I copied this example from a site online, and therefore, I think "sum" is defined somewhere, but I'm not really sure where and therefore don't know why the error is occurring.

Changing calculate_sum.py to the below passes the test:

def sum(arg):
    total = 0
    for val in arg:
        total += val
    return total

def create_sum():
    print("hello")
    total = sum([5, 5])
    print(total)

testsum.py:

import unittest

from dir import *

class TestSum(unittest.TestCase):
    def test_list_int(self):
        """
        Test that it can sum a list of integers
        """
        data = [1, 2, 3]
        result = sum(data)
        self.assertEqual(result, 6)

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

---------------------------------------------------------------------- Ran 1 test in 0.000s

OK

1 Answers

sum(_iterable) is an inbuilt method in python. So it did not call your method, but it called the inbuilt method.

In your test method, you did not import the service module which you did in your main module.

Add from MainDir.dir.service.calculate_sum import calculate to your test module, everything should work fine.

Related