I am trying to Mock an import in python for a test. My code looks something like this.
"""Python file description."""
import sys
import pytest
import datetime as dt
from unittest.mock import Mock
sys.modules['module_A'] = Mock()
from module_to_test import function_to_test
where I need to mock module_A
as a dependency for module_to_test
.
On save, VSCode auto-orders this alphabetically, and as a result creates the Mock after it tries to import from the module with the dependency.
How do I prevent the Sort Imports from ordering a subset of files? This could be through a list of files, a glob, regex or similar?
Glob pattern of the test file ./tests/test_*.py.
Update - Partial solution posted below.
If like mine your VSCode config is using isort (not autopep8) to do the import sorting, then you can override it on a selective basis like this:
app = Flask(__name__)
from . import views # isort:skip
i.e. Add the # isort:skip
comment to the import you don't want to jump to the top of the file.
Source: https://github.com/timothycrosley/isort#skip-processing-of-imports-outside-of-configuration
VS Code runs autopep8 at save time and you can add the # noqa
or # nopep8
comment at the end of a line to exclude that line from checking/sorting:
sys.modules['module_A'] = Mock()
from module_to_test import function_to_test # noqa
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With