【问题标题】:How to setup the root for Tests in Python in Visual Studio Code?如何在 Visual Studio Code 中为 Python 中的测试设置根目录?
【发布时间】:2020-06-19 22:49:56
【问题描述】:
project\
  src\
      __init__.py  
  tests\
      __init__.py
      stubs\r_json_response_expired.json

在我的测试中,我必须加载一个 JSON 文件。这个。

@patch('requests.post')
def test_subscription_delete_only_if_invalid(self, mock_post):
    with app.app_context():
        expires_at = datetime.utcnow()
        m = self.inject_expired_r_json()

def inject_expired_r_json(self):
        with open('stubs/r_json_response_expired.json') as fb_file:
            receipt_response = json.load(fb_file)
        m = MagicMock()
        m.json = MagicMock(name='json')
        m.json.return_value = receipt_response
        return m

运行测试时VS Code显示:

FileNotFoundError: [Errno 2] 没有这样的文件或目录: 'stubs/r_json_response_expired.json'

我的项目中有.env

PYTHONPATH=./src

在 settings.json (VS CODE) 中

"terminal.integrated.env.osx": {
    "PYTHONPATH": "${workspaceFolder}/src"
},
"python.envFile": "${workspaceFolder}/.env"

如果我碰巧切换了 IDE,我不喜欢在测试中更改路径以避免破坏 PyCharm。

【问题讨论】:

  • 运行 pip install -e . 在 vi​​rtualenv 中以开发模式安装您的项目,然后在中心位置使用 DIRNAME = os.path.dirname(__file__) 并将所有路径挂起。

标签: python visual-studio-code configuration


【解决方案1】:

问题是运行测试时的当前目录是您的工作区根目录project。可能您最好的选择是使用importlib_resources 来读取文件。如果您将 __init__.py 文件放在存根中,则可以将 JSON 文件读取为:

import importlib_resources

from . import stubs

data = importlib_resources.files(stubs).joinpath('r_json_response_expired.json').read_text()

如果由于某种原因您不能在目录中放置__init__.py,那么您可以使用 pathlib 创建文件路径。

import pathlib

data_path = pathlib.Path(__file__).parent / "stubs" / "r_json_response_expired.json"
data = data_path.read_text(encoding="utf-8")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-09
    • 2020-05-27
    • 2017-05-10
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多