This is the folder structure of my python project:
src->
stock_alerter->
tests
Inside the folders stock_alerter and tests I have an empty __init__.py
Inside stock_alerter I have a file stock.py containing:
class Stock:
def __init__(self, symbol):
self.symbol = symbol
self.price = None
Inside tests I have a file test_stock.py containing:
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)
When I run test_stock.py I get:
ValueError('attempted relative import beyond top-level package')
I did some searches but changing
from ..stock import Stock
to:
stock import Stock
gives:
ModuleNotFoundError("No module named 'stock'")
Any ideas? Btw, I use Visual Studio Express 2017 and ran test_stock.py.
PS:
Adding:
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)
to test_stock.py works. Now I thought Python is easy. What a nightmare ...