单元测试如何导入他们测试的模块?

2024-10-02 20:40:30 发布

您现在位置:Python中文网/ 问答频道 /正文

(Python新手,Java老家伙)我遵循了Python项目设置的建议(这里有详细说明:What is the best project structure for a Python application?)。你知道吗

我的结构是:

artman
`-- artman
    +-- artman.py
    +-- util.py
    `-- test
        `-- util_test.py

…而我的测试代码尝试导入中的内容失败利用率它将要测试:

import unittest
import util        # <------ Unresolved import: util

class UtilTest( unittest.TestCase ):
    def testLookForArtmanRoot( self ):
        util.lookForArtmanRoot( "." )

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

我敢肯定这是一个简单的,新手Python的错误,但尽管谷歌我不知道我是否必须修改PYTHONPATH或采用其他解决方案。你知道吗


Tags: the项目pytestimportismainutil
1条回答
网友
1楼 · 发布于 2024-10-02 20:40:30

虽然这不是严格必要的,但我要澄清这个问题 目录/包/模块结构,让你学习,每一步的目的都会很清楚。你知道吗

artman_dir
`  artman_pkg
    +  __init__.py
    +  artman.py
    +  util.py
    +  test
        `  util_test.py
  • artman_dir添加到PYTHONPATH。你知道吗
  • 将名为__init__.py的空文件添加到artman_pkg。你知道吗

这两个步骤一起让你

import artman_pkg

任何python脚本。你知道吗

然后可以在util_test.pyusing an absolute import中导入util

import artman_pkg.util as util

其余的代码可以保持不变。你知道吗

相关问题 更多 >