python - 在 Python 包中运行测试时未定义函数

标签 python testing

我正在创建一个 Python 包/库。我的目录结构如下所示:

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

我的所有函数都在 ma​​in.py 文件中:

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 看起来像这样:

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

当我从包根目录运行测试时,如下所示:

python setup.py test

...我收到以下错误:

NameError: name 'sum_nums' is not defined
  • 我的包目录结构是否正确?
  • 我是否缺少 _ init _.py 文件?
  • 是否每个目录都需要一个 _ init _.py 文件?
  • 可以将我所有的函数放在一个 main.py 文件中吗 不使用 if name == "ma​​in"?

最佳答案

您需要指出被测函数来自 my_package 包,例如:

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

关于python - 在 Python 包中运行测试时未定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54661847/

相关文章:

python - 对多列进行转换以插入/复制缺失值

python - python cv2 中 VideoCapture 的多个实例的问题

node.js - 使用istanbul时,有没有办法动态要求config.js?

Angular5 - 测试调用内部http服务的函数

testing - JMeter 通过、失败、警告?

python - 为什么我们在django的model_name.object.get_or_create()中的get_or_create之后写[0]

python - 如何修复错误 : The truth value of an array with more than one element is ambiguous

python - Python的Bunch可以递归使用吗?

python - 如何从外部停止执行 Python 函数?

python - 排除 coverage 中的 'else' 子句