尝试在运行单元测试时,尝试在顶层包之外进行相对导入

2024-04-18 19:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的python项目的文件夹结构:

src->
    stock_alerter->
                 tests

在存放警报和测试的文件夹中,我有一个空的__init__.py

内部库存警报我有一个文件股票.py包含:

class Stock:
    def __init__(self, symbol):
        self.symbol = symbol
        self.price = None

内部测试我有一个文件测试_股票.py包含:

import unittest
from ..stock import Stock

class StockTest(unittest.TestCase):

    def test_price_of_a_new_stock_class_should_be_None(self):
        stock = Stock("GOOG")
        self.assertIsNone(stock.price)

当我运行测试时_股票.py我得到:

ValueError('attempted relative import beyond top-level package')

我做了一些搜索,但改变了

from ..stock import Stock

收件人:

stock import Stock

提供:

ModuleNotFoundError("No module named 'stock'")

有什么想法吗?顺便说一句,我使用Visual Studio Express 2017并运行了测试_股票.py. 你知道吗

附言:

添加:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

测试_股票.py作品。现在我觉得Python很简单。真是个噩梦。。。你知道吗


Tags: pathpyimportself文件夹initosstock
1条回答
网友
1楼 · 发布于 2024-04-18 19:19:29

My approach is to avoid writing scripts that have to import from the parent directory. In cases where this must happen, the preferred workaround is to modify sys.path.

但是还有其他的黑客攻击方法,看看这个链接:Sibling package imports

相关问题 更多 >