用 Python 分隔 src 和 test 目录
Separate src and test directories with Python
当我将测试文件和 src 文件放在不同的子文件夹中时,测试文件的 from
行出现编译错误:"Unable to import 'classA' pylint(import-error)
。当 src 和测试文件位于同一目录中时,它可以正常工作。这让我觉得这与 settings.json 文件有关,但我不确定。关于如何修复它有什么想法吗?
repo
├── .vscode
│ └── settings.json
├── src
│ ├── classA.py
│ └── classB.py
└── tests
├── classA_test.py
└── classB_test.py
classA.py:
from datetime import date
class fetchData():
var = ""
def __init__(self, thing):
self.var = thing
def getInfo(self, x):
..process things..
return info
classA_test.py
import unittest
from classA import fetchData
class classA(unittest.TestCase):
def testStuff(self):
..testStuff..
settings.json
{
"python.testing.unittestArgs": [
"-v",
"-s",
"./tests",
"-p",
"*_test.py"
],
"python.testing.pytestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.unittestEnabled": true
}
据此link
你可以在你的测试中做这样的事情:
# 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
个文件以使其成为一个包(您可以将它们留空)
希望有用。
正确的格式如下:
repo
├── .vscode
│ ├── settings.json
├── src
│ ├── classA.py
│ └── classB.py
└── tests
├── __init__.py (empty file)
├── classA_test.py
└── classB_test.py
classA_test.py
import unittest
from src.classA import fetchData
class classA(unittest.TestCase):
def testStuff(self):
..testStuff..
当我将测试文件和 src 文件放在不同的子文件夹中时,测试文件的 from
行出现编译错误:"Unable to import 'classA' pylint(import-error)
。当 src 和测试文件位于同一目录中时,它可以正常工作。这让我觉得这与 settings.json 文件有关,但我不确定。关于如何修复它有什么想法吗?
repo
├── .vscode
│ └── settings.json
├── src
│ ├── classA.py
│ └── classB.py
└── tests
├── classA_test.py
└── classB_test.py
classA.py:
from datetime import date
class fetchData():
var = ""
def __init__(self, thing):
self.var = thing
def getInfo(self, x):
..process things..
return info
classA_test.py
import unittest
from classA import fetchData
class classA(unittest.TestCase):
def testStuff(self):
..testStuff..
settings.json
{
"python.testing.unittestArgs": [
"-v",
"-s",
"./tests",
"-p",
"*_test.py"
],
"python.testing.pytestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.unittestEnabled": true
}
据此link
你可以在你的测试中做这样的事情:
# 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
个文件以使其成为一个包(您可以将它们留空)
希望有用。
正确的格式如下:
repo
├── .vscode
│ ├── settings.json
├── src
│ ├── classA.py
│ └── classB.py
└── tests
├── __init__.py (empty file)
├── classA_test.py
└── classB_test.py
classA_test.py
import unittest
from src.classA import fetchData
class classA(unittest.TestCase):
def testStuff(self):
..testStuff..