I have the following folder structure:
sdn_unit_tests/ this contains two folders, 'classes' and 'tests'.
'classes' contains one file 'validator.py' and a pycache folder. 'tests' contains one file 'test_validator.py'
The code for validator.py:
class Validator:
def username_is_valid(self, username):
if len(username) > 10:
return False
if ' ' in username:
return False
if username.islower():
return False
return True
The code for test_validator.py:
import unittest
from classes.validator import Validator
class TestValidator(unittest.TestCase):
def test_it_will_reject_username_if_too_long(self):#has to start with 'test_'
#Assume
username = 'InvalidTooLong'
validator = Validator()
#Action
result = validator.username_is_valid(username)
#Assert
self.assertFalse(result)
Expected behaviour: I expect that running test_validator.py will at least find the module, this is my first unit test so I don't know if it will say OK or false but I still expect it to find the classes.validator
Error:
Traceback (most recent call last):
File "/Users/.../Desktop/sdn_unit_tests/tests/test_validator.py", line 3, in <module>
from classes.validator import Validator
ModuleNotFoundError: No module named 'classes'
I would recommend running python -m unittest
from the parent directory. This will start automatic test discovery. But for this to work, you must create an empty __init__.py
file in your tests
folder.
Update: as a quick way to run test_validator.py
itself (e.g. from an IDE), add this to the beginning:
import sys
sys.path.append('..')
and this to the end:
if __name__ == '__main__':
unittest.main()