You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pytest测试Python项目中__main__.py内的func1函数?

解决__main__.py中函数的单元测试导入问题

问题原因

当你运行tests.py时,Python会把tests.py当作__main__模块,所以from __main__ import func1实际上是从tests.py里查找func1,自然找不到目标函数。

推荐解决方案:重构代码分离逻辑

把业务函数和入口执行代码分开,这是更规范的项目结构,也能从根源上解决测试导入问题:

  1. 新建业务模块:创建my_module.py文件,将func1移到这个文件中:
import some_class

def func1(some_instance) -> bool:
    # 原有的函数代码
    # 返回True或False
  1. 修改__main__.py:从新模块导入func1,保留入口执行逻辑:
from my_module import func1
import some_class

some_instance = some_class()
func1(some_instance)
  1. 修改tests.py:直接从业务模块导入func1进行测试:
import some_class
from my_module import func1

def test_func1():
    test_instance = some_class()
    assert func1(test_instance) is True

临时解决方案(不推荐)

如果暂时不想重构代码,可以直接将__main__.py作为普通模块导入,但要注意:导入时会执行文件里的所有顶层代码(比如func1(some_instance)会被自动执行),可能带来不必要的副作用。

修改tests.py为:

import some_class
import __main__ as main_module

def test_func1():
    test_instance = some_class()
    assert main_module.func1(test_instance) is True

内容的提问来源于stack exchange,提问作者wikofad877

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:03:22