gpt4 book ai didi

python - 使用 doctests 在 Python 项目中导入

转载 作者:IT王子 更新时间:2023-10-29 00:32:35 27 4
gpt4 key购买 nike

我有一个具有以下目录结构的 Python 项目:

/(some files)/model/(python files)/tools/(more python files)...

So, I have Python files in couple subdirectories and there are somedependencies between directories as well: tools are used by model, etc. Now my problem is that I want to make doctests for both models and tools, and I want be able to run tests from command line like this: ./model/car.py .I can make this work, but only with messy boilerplate code. I would liketo know what is the correct way, or is there any?

Question: How should I write my imports?

Thanx. Here is an example...

Content of tools/tool.py:

#!/usr/bin/env python
"""
>>> is_four(21)
False
>>> is_four(4)
True
"""

def is_four(val):
return val == 4

if __name__ == '__main__':
import doctest
doctest.testmod()

...和model/car.py:

#!/usr/bin/env python   
"""
>>> car = Car()
>>> car.ok()
True
"""

from tools.tool import *

class Car(object):
def __init__(self):
self.tire_count = 4
def ok(self):
return is_four(self.tire_count)

if __name__ == '__main__':
import doctest
doctest.testmod()

通过在 car.py 的开头添加以下行,它可以工作,但看起来不太好。 :(

if __name__ == '__main__':
import sys
import os
sys.path.append(os.path.abspath(os.path.dirname('..')))

最佳答案

您要做的是相对导入。它在 Python 中运行良好,但在模块级别,而不是在文件系统级别。我知道,这令人困惑。

这意味着如果您在子目录中运行脚本,它看不到上层目录,因为对于运行脚本,模块的根目录是当前目录:没有上层模块。

那么相对导入有什么用呢?

好吧,子目录中的模块汽车导入上层目录中的模块,只要它们本身是从上层目录导入的。

在您的情况下,这意味着您必须从“/”运行脚本,以便它成为模块的根目录,并且允许子模块使用相对导入。

您的问题的可能解决方案是删除您的 if __name__ == "__main__" block 并创建/tests.py:

import doctest
from model import car
from tools import tool

doctest.testmod(car)
doctest.testmod(tool)

然后运行太启动所有测试。

最终你会想要自动化这个过程,一个简单的解决方案是使用 unittest 这样你就可以创建测试套件并添加你想要测试的模块名称:

import unittest
import doctest

modules = ("model.car",
"tools.tool")

suite = unittest.TestSuite()
for mod in modules:
suite.addTest(doctest.DocTestSuite(mod))
runner = unittest.TextTestRunner()
runner.run(suite)

另一种解决方案(推荐)是使用工具,例如 nose为您自动执行此操作。

easy_install nose
nosetests --with-doctest # done :-)

顺便说一下,避免from x import *。这适用于快速脚本,但是当您的程序增长时,您确实需要明确命名您导入的内容。 import xfrom x import y

关于python - 使用 doctests 在 Python 项目中导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2372125/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com