【问题标题】:Separate src and test directories with Python用 Python 分离 src 和 test 目录
【发布时间】:2020-08-25 14:41:42
【问题描述】:

当我将我的测试和 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
}

【问题讨论】:

    标签: python unit-testing class visual-studio-code python-import


    【解决方案1】:

    正确的格式如下:

    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..
    

    【讨论】:

      【解决方案2】:

      据此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 文件以使其成为一个包(您可以将它们留空)

      希望有效。

      【讨论】:

      • 这似乎不起作用。我仍然遇到同样的问题:(
      • 我认为以 from src.classA import * 为例应该可行。你试过了吗?
      • 几个月前这对我有用,但现在不再适用了。有些事情发生了变化,但我不知道是什么。
      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 2021-04-23
      • 2021-12-08
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多