简体   繁体   中英

Function not defined when running tests in Python package

I am creating a Python package/library . My directory structure looks like this:

my_package/
|-- my_package/
|   |-- tests/
|   |   |-- __init__.py
|   |   |-- my_tests.py
|   |   
|   |-- __init__.py
|   |-- main.py
|
|-- setup.py

I have all my functions in the main.py file:

def sum_nums(a,b):
    res = a + b
    return(res)

def mult_nums(a,b):
    res = a * b
    return(res)

def sub_nums(a,b):
    res = a - b
    return(res)

my_tests.py looks like this:

from unittest import TestCase

import my_package

def test_sum():
    assert sum_nums(3,4) == 7

def test_mult():
    assert mult_nums(3,4) == 12

def test_sub():
    assert sub_nums(3,4) == -1

When I run my tests from the package root directory as follows:

python setup.py test

... I get the following error :

NameError: name 'sum_nums' is not defined
  • Is my package directory structure correct?
  • Am I missing an _ init _.py file?
  • Does every directory require an _ init _.py file?
  • Is it okay to place all my functions inside a single main.py file without using if name == " main "?

You need to indicate that the functions under test came for the my_package package like:

from unittest import TestCase

import my_package

def test_sum():
    assert my_package.sum_nums(3,4) == 7

def test_mult():
    assert my_package.mult_nums(3,4) == 12

def test_sub():
    assert my_package.sub_nums(3,4) == -1

tests should not be in the package so move it up one dir. See sanic or any other module in github for example. Your functions need to be available in init .py. You can import them like is done in sanic.

https://github.com/huge-success/sanic

You also need

from my_package import sum_nums, mult_nums, sub_nums 

Or prefix with my_package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM