0

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'

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

hi myrmica, yes that seems to have run the test. For some reason I thought the test should be run from the IDE (vs code). Is it the case that tests are run by unittest from the terminal/console?
You can run the test module itself too, but you have to somehow solve the problem with sibling directories. (if your working dir is tests, the import machinery can't see the classes dir)
Thank you myrmica, the update is also useful, much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.