Python Unittest Cannot Find Module
When running Python unittest, if you encounter the error message “Cannot find module”, it means that the module you are trying to import and test is not accessible from the location where you are executing the unittest.
This error commonly occurs when the module you are trying to import is not in the same directory as your test script or not in your Python’s module search path.
Solution
To resolve this issue, you can take the following steps:
- Ensure that the module you are trying to import is in the same directory as your test script.
- Make sure that the module’s name and spelling are correct. Python is case-sensitive, so the module name needs to be written exactly as it is.
- Check if the module has an `__init__.py` file, which makes it a package that can be imported. Without this file, Python treats the directory as a regular folder and not as a package.
- If the module is located in a different directory, you can add the directory to the Python’s module search path using the `sys.path.append()` function. Make sure to import the `sys` module before using it.
Example
Let’s say we have the following file structure:
. ├── tests │ ├── test_module.py └── my_module.py
In `test_module.py`, you want to import and test the `my_module.py` module:
import unittest import my_module class MyModuleTest(unittest.TestCase): def test_some_function(self): self.assertEqual(my_module.some_function(), expected_result) if __name__ == "__main__": unittest.main()
If you encounter the “Cannot find module” error, you need to ensure that both `test_module.py` and `my_module.py` are in the same directory (in this case, it is the “tests” directory).
- Python strftime milliseconds 3 digits
- Publishable packages can’t have ‘git’ dependencies. try adding a ‘publish_to: none’ entry to mark the package as not for publishing or remove the git dependency.
- Printf pipe
- Pydantic create model from dict
- Property ‘spring.profiles’ imported from location ‘class path resource [application.yml]’ is invalid and should be replaced with ‘spring.config.activate.on-profile’
- Python type tuple cannot be converted