首页 > 解决方案 > 用 Python 分离 src 和 test 目录

问题描述

from当我将测试和 src 文件放在不同的子文件夹中时,我在测试文件的行中遇到编译错误: "Unable to import 'classA' pylint(import-error). 当 src 和 test 文件位于同一目录中时,它正在工作。这让我觉得这与 settings.json 文件有关,但我不确定。关于如何解决它的任何想法?

repo
├── .vscode
│   └── settings.json
├── src
│   ├── classA.py
│   └── classB.py
└── tests
     ├── classA_test.py
     └── classB_test.py

类A.py:

from datetime import date

class fetchData():
    var = ""

    def __init__(self, thing):
        self.var = thing

    def getInfo(self, x):
        ..process things..
        return info

类A_test.py

import unittest
from classA import fetchData

class classA(unittest.TestCase):
    def testStuff(self):
        ..testStuff..

设置.json

{
    "python.testing.unittestArgs": [
        "-v",
        "-s",
        "./tests",
        "-p",
        "*_test.py"
    ],
    "python.testing.pytestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.unittestEnabled": true
}

标签: pythonunit-testingclassvisual-studio-codepython-import

解决方案


根据这个链接

您可以在测试中执行以下操作:

# import the package
import antigravity

# import the antigravity module
from antigravity import antigravity

# or an object inside the antigravity module
from antigravity.antigravity import my_object

但请确保您__init__.py在每个目录中添加了文件以使其成为一个包(您可以将它们留空)

希望有效。


推荐阅读