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

标签 python linux unix path

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

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

So, I have Python files in couple subdirectories and there are some dependencies 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 like to 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/

相关文章:

python - 从 Pandas DataFrame 列中删除特定符号(unicode)

python - 如何打印列表中字符串中的单词?在 Python 中

python - 无效语法错误 : Building decision tree with Python and Spark, 流失预测

c - Scanf() 无法检测到错误的输入

c - 发生崩溃时查看堆栈

macos - 将文件从服务器复制到本地硬盘

Python Sqlite3 : Create a schema without having to use a second database

php - Windows 特定 CSS 选择器或代码片段

java - 检查与服务器的 TCP 连接数

linux - 什么代码不应该写成实时代码?