I'm trying to build a project via the method described in The Hitchhiker's Guide To Python. I'm running into problems with the test structure.
My file structure looks like this:
.
├── __init__.py
├── sample
│ ├── __init__.py
│ └── core.py
├── setup.py
└── tests
├── __init__.py
├── context.py
└── test_core.py
With:
# sample/core.py
class SampleClass:
def got_it(self):
return True
And:
# tests/context.py
import os
import sys
sys.path.insert(0, os.path.abspath(
os.path.join(os.path.dirname(__file__), '..')
))
import sample
And:
# tests/test_core.py
import unittest
from .context import sample
class SampleClassTest(unittest.TestCase):
def test_got_it(self):
# ...
pass
if __name__ == '__main__':
unittest.main()
(Note that I just thru the __init__.py
files in the root and tests to see if that helped, but it didn't.)
When I try to run tests/test_core.py
with Python 3.7. I get this error:
ImportError: attempted relative import with no known parent package
That happens if I run the test file from outside the tests directory or in it.
If I remote the .
and do this in tests/test_core.py:
from context import sample
Everything loads, but I can't access SampleClass
.
The things I've tried are:
sc = SampleClass()
NameError: name 'SampleClass' is not defined
sc = sample.SampleClass()
AttributeError: module 'sample' has no attribute 'SampleClass'
sc = sample.core.SampleClass()
AttributeError: module 'sample' has no attribute 'core'
sc = core.SampleClass()
NameError: name 'core' is not defined
I tried on Python 2 as well and had similar problems (with slightly different error methods). I also tried calling a function instead of a class and had similar problems there as well.
Can someone point me in the direction of what I'm doing wrong?