2019-01-14 01:33:47 +00:00
|
|
|
import contextlib
|
2013-11-02 09:28:22 +00:00
|
|
|
import os
|
2019-01-14 01:33:47 +00:00
|
|
|
import py_compile
|
2015-08-05 09:06:26 +00:00
|
|
|
import shutil
|
2019-01-14 01:33:47 +00:00
|
|
|
import sys
|
2014-07-25 13:32:14 +00:00
|
|
|
import tempfile
|
2019-01-14 01:33:47 +00:00
|
|
|
import threading
|
|
|
|
import time
|
2019-02-27 15:35:30 +00:00
|
|
|
import types
|
2019-01-19 00:16:33 +00:00
|
|
|
import weakref
|
2019-01-14 01:33:47 +00:00
|
|
|
import zipfile
|
2023-01-18 08:46:01 +00:00
|
|
|
import zoneinfo
|
2015-01-28 12:35:27 +00:00
|
|
|
from importlib import import_module
|
2019-01-14 01:33:47 +00:00
|
|
|
from pathlib import Path
|
2019-08-23 08:53:36 +00:00
|
|
|
from subprocess import CompletedProcess
|
2019-04-24 09:46:55 +00:00
|
|
|
from unittest import mock, skip, skipIf
|
2013-11-02 09:28:22 +00:00
|
|
|
|
2020-06-18 11:04:10 +00:00
|
|
|
import django.__main__
|
2019-01-14 01:33:47 +00:00
|
|
|
from django.apps.registry import Apps
|
|
|
|
from django.test import SimpleTestCase
|
2015-02-21 18:18:54 +00:00
|
|
|
from django.test.utils import extend_sys_path
|
2015-08-05 09:06:26 +00:00
|
|
|
from django.utils import autoreload
|
2019-01-14 01:33:47 +00:00
|
|
|
from django.utils.autoreload import WatchmanUnavailable
|
2013-11-02 09:28:22 +00:00
|
|
|
|
2021-04-25 02:52:18 +00:00
|
|
|
from .test_module import __main__ as test_main
|
|
|
|
from .test_module import main_module as test_main_module
|
2019-04-24 09:46:55 +00:00
|
|
|
from .utils import on_macos_with_hfs
|
|
|
|
|
2013-11-02 09:28:22 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
class TestIterModulesAndFiles(SimpleTestCase):
|
|
|
|
def import_and_cleanup(self, name):
|
|
|
|
import_module(name)
|
|
|
|
self.addCleanup(lambda: sys.path_importer_cache.clear())
|
|
|
|
self.addCleanup(lambda: sys.modules.pop(name, None))
|
2015-08-08 13:12:49 +00:00
|
|
|
|
|
|
|
def clear_autoreload_caches(self):
|
2019-01-14 01:33:47 +00:00
|
|
|
autoreload.iter_modules_and_files.cache_clear()
|
2014-07-05 12:43:12 +00:00
|
|
|
|
2015-08-08 13:12:49 +00:00
|
|
|
def assertFileFound(self, filename):
|
2019-01-14 01:33:47 +00:00
|
|
|
# Some temp directories are symlinks. Python resolves these fully while
|
|
|
|
# importing.
|
2019-11-02 03:18:48 +00:00
|
|
|
resolved_filename = filename.resolve(strict=True)
|
2015-08-08 13:12:49 +00:00
|
|
|
self.clear_autoreload_caches()
|
|
|
|
# Test uncached access
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertIn(
|
|
|
|
resolved_filename, list(autoreload.iter_all_python_module_files())
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2015-08-08 13:12:49 +00:00
|
|
|
# Test cached access
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertIn(
|
|
|
|
resolved_filename, list(autoreload.iter_all_python_module_files())
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1)
|
2015-08-08 13:12:49 +00:00
|
|
|
|
|
|
|
def assertFileNotFound(self, filename):
|
2019-11-02 03:18:48 +00:00
|
|
|
resolved_filename = filename.resolve(strict=True)
|
2015-08-08 13:12:49 +00:00
|
|
|
self.clear_autoreload_caches()
|
|
|
|
# Test uncached access
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertNotIn(
|
|
|
|
resolved_filename, list(autoreload.iter_all_python_module_files())
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2015-08-08 13:12:49 +00:00
|
|
|
# Test cached access
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertNotIn(
|
|
|
|
resolved_filename, list(autoreload.iter_all_python_module_files())
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertEqual(autoreload.iter_modules_and_files.cache_info().hits, 1)
|
2015-08-08 13:12:49 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def temporary_file(self, filename):
|
2015-08-08 13:12:49 +00:00
|
|
|
dirname = tempfile.mkdtemp()
|
|
|
|
self.addCleanup(shutil.rmtree, dirname)
|
2019-01-14 01:33:47 +00:00
|
|
|
return Path(dirname) / filename
|
2015-08-08 13:12:49 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_paths_are_pathlib_instances(self):
|
|
|
|
for filename in autoreload.iter_all_python_module_files():
|
|
|
|
self.assertIsInstance(filename, Path)
|
2015-08-08 13:12:49 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_file_added(self):
|
2015-08-08 13:12:49 +00:00
|
|
|
"""
|
2019-01-14 01:33:47 +00:00
|
|
|
When a file is added, it's returned by iter_all_python_module_files().
|
2015-08-08 13:12:49 +00:00
|
|
|
"""
|
2019-01-14 01:33:47 +00:00
|
|
|
filename = self.temporary_file("test_deleted_removed_module.py")
|
|
|
|
filename.touch()
|
2015-08-08 13:12:49 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
with extend_sys_path(str(filename.parent)):
|
|
|
|
self.import_and_cleanup("test_deleted_removed_module")
|
2015-08-08 13:12:49 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertFileFound(filename.absolute())
|
2015-08-05 09:06:26 +00:00
|
|
|
|
|
|
|
def test_check_errors(self):
|
|
|
|
"""
|
|
|
|
When a file containing an error is imported in a function wrapped by
|
|
|
|
check_errors(), gen_filenames() returns it.
|
|
|
|
"""
|
2019-01-14 01:33:47 +00:00
|
|
|
filename = self.temporary_file("test_syntax_error.py")
|
|
|
|
filename.write_text("Ceci n'est pas du Python.")
|
2015-08-05 09:06:26 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
with extend_sys_path(str(filename.parent)):
|
2021-01-20 08:53:34 +00:00
|
|
|
try:
|
|
|
|
with self.assertRaises(SyntaxError):
|
|
|
|
autoreload.check_errors(import_module)("test_syntax_error")
|
|
|
|
finally:
|
|
|
|
autoreload._exception = None
|
2015-08-08 13:12:49 +00:00
|
|
|
self.assertFileFound(filename)
|
2015-08-05 09:06:26 +00:00
|
|
|
|
2015-08-29 11:26:00 +00:00
|
|
|
def test_check_errors_catches_all_exceptions(self):
|
|
|
|
"""
|
|
|
|
Since Python may raise arbitrary exceptions when importing code,
|
|
|
|
check_errors() must catch Exception, not just some subclasses.
|
|
|
|
"""
|
2019-01-14 01:33:47 +00:00
|
|
|
filename = self.temporary_file("test_exception.py")
|
|
|
|
filename.write_text("raise Exception")
|
|
|
|
with extend_sys_path(str(filename.parent)):
|
2021-01-18 11:50:51 +00:00
|
|
|
try:
|
|
|
|
with self.assertRaises(Exception):
|
|
|
|
autoreload.check_errors(import_module)("test_exception")
|
|
|
|
finally:
|
|
|
|
autoreload._exception = None
|
2015-08-29 11:26:00 +00:00
|
|
|
self.assertFileFound(filename)
|
2016-11-07 23:51:23 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_zip_reload(self):
|
2016-11-07 23:51:23 +00:00
|
|
|
"""
|
2019-01-14 01:33:47 +00:00
|
|
|
Modules imported from zipped files have their archive location included
|
|
|
|
in the result.
|
2016-11-07 23:51:23 +00:00
|
|
|
"""
|
2019-01-14 01:33:47 +00:00
|
|
|
zip_file = self.temporary_file("zip_import.zip")
|
|
|
|
with zipfile.ZipFile(str(zip_file), "w", zipfile.ZIP_DEFLATED) as zipf:
|
|
|
|
zipf.writestr("test_zipped_file.py", "")
|
|
|
|
|
|
|
|
with extend_sys_path(str(zip_file)):
|
|
|
|
self.import_and_cleanup("test_zipped_file")
|
|
|
|
self.assertFileFound(zip_file)
|
|
|
|
|
|
|
|
def test_bytecode_conversion_to_source(self):
|
|
|
|
""".pyc and .pyo files are included in the files list."""
|
|
|
|
filename = self.temporary_file("test_compiled.py")
|
|
|
|
filename.touch()
|
|
|
|
compiled_file = Path(
|
|
|
|
py_compile.compile(str(filename), str(filename.with_suffix(".pyc")))
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
filename.unlink()
|
|
|
|
with extend_sys_path(str(compiled_file.parent)):
|
|
|
|
self.import_and_cleanup("test_compiled")
|
|
|
|
self.assertFileFound(compiled_file)
|
|
|
|
|
2019-01-19 00:16:33 +00:00
|
|
|
def test_weakref_in_sys_module(self):
|
|
|
|
"""iter_all_python_module_file() ignores weakref modules."""
|
|
|
|
time_proxy = weakref.proxy(time)
|
|
|
|
sys.modules["time_proxy"] = time_proxy
|
|
|
|
self.addCleanup(lambda: sys.modules.pop("time_proxy", None))
|
|
|
|
list(autoreload.iter_all_python_module_files()) # No crash.
|
|
|
|
|
2019-02-27 15:35:30 +00:00
|
|
|
def test_module_without_spec(self):
|
|
|
|
module = types.ModuleType("test_module")
|
|
|
|
del module.__spec__
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.iter_modules_and_files((module,), frozenset()), frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-02-27 15:35:30 +00:00
|
|
|
|
2019-05-27 19:14:49 +00:00
|
|
|
def test_main_module_is_resolved(self):
|
|
|
|
main_module = sys.modules["__main__"]
|
|
|
|
self.assertFileFound(Path(main_module.__file__))
|
|
|
|
|
2019-06-26 04:44:10 +00:00
|
|
|
def test_main_module_without_file_is_not_resolved(self):
|
|
|
|
fake_main = types.ModuleType("__main__")
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.iter_modules_and_files((fake_main,), frozenset()), frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-06-26 04:44:10 +00:00
|
|
|
|
2019-07-21 20:55:25 +00:00
|
|
|
def test_path_with_embedded_null_bytes(self):
|
|
|
|
for path in (
|
|
|
|
"embedded_null_byte\x00.py",
|
|
|
|
"di\x00rectory/embedded_null_byte.py",
|
|
|
|
):
|
|
|
|
with self.subTest(path=path):
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.iter_modules_and_files((), frozenset([path])),
|
|
|
|
frozenset(),
|
|
|
|
)
|
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
|
2020-06-18 11:04:10 +00:00
|
|
|
class TestChildArguments(SimpleTestCase):
|
2021-01-04 14:50:49 +00:00
|
|
|
@mock.patch.dict(sys.modules, {"__main__": django.__main__})
|
2020-06-18 11:04:10 +00:00
|
|
|
@mock.patch("sys.argv", [django.__main__.__file__, "runserver"])
|
|
|
|
@mock.patch("sys.warnoptions", [])
|
2021-08-15 02:48:23 +00:00
|
|
|
@mock.patch("sys._xoptions", {})
|
2020-06-18 11:04:10 +00:00
|
|
|
def test_run_as_module(self):
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(),
|
|
|
|
[sys.executable, "-m", "django", "runserver"],
|
|
|
|
)
|
|
|
|
|
2021-01-04 14:50:49 +00:00
|
|
|
@mock.patch.dict(sys.modules, {"__main__": test_main})
|
|
|
|
@mock.patch("sys.argv", [test_main.__file__, "runserver"])
|
|
|
|
@mock.patch("sys.warnoptions", [])
|
2021-08-15 02:48:23 +00:00
|
|
|
@mock.patch("sys._xoptions", {})
|
2021-01-04 14:50:49 +00:00
|
|
|
def test_run_as_non_django_module(self):
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(),
|
|
|
|
[sys.executable, "-m", "utils_tests.test_module", "runserver"],
|
|
|
|
)
|
|
|
|
|
2021-04-25 02:52:18 +00:00
|
|
|
@mock.patch.dict(sys.modules, {"__main__": test_main_module})
|
|
|
|
@mock.patch("sys.argv", [test_main.__file__, "runserver"])
|
|
|
|
@mock.patch("sys.warnoptions", [])
|
2021-08-15 02:48:23 +00:00
|
|
|
@mock.patch("sys._xoptions", {})
|
2021-04-25 02:52:18 +00:00
|
|
|
def test_run_as_non_django_module_non_package(self):
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(),
|
|
|
|
[sys.executable, "-m", "utils_tests.test_module.main_module", "runserver"],
|
|
|
|
)
|
|
|
|
|
2021-08-15 16:10:36 +00:00
|
|
|
@mock.patch("__main__.__spec__", None)
|
2020-06-18 11:04:10 +00:00
|
|
|
@mock.patch("sys.argv", [__file__, "runserver"])
|
|
|
|
@mock.patch("sys.warnoptions", ["error"])
|
2021-08-15 02:48:23 +00:00
|
|
|
@mock.patch("sys._xoptions", {})
|
2020-06-18 11:04:10 +00:00
|
|
|
def test_warnoptions(self):
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(),
|
|
|
|
[sys.executable, "-Werror", __file__, "runserver"],
|
|
|
|
)
|
|
|
|
|
2021-08-15 02:48:23 +00:00
|
|
|
@mock.patch("sys.argv", [__file__, "runserver"])
|
|
|
|
@mock.patch("sys.warnoptions", [])
|
|
|
|
@mock.patch("sys._xoptions", {"utf8": True, "a": "b"})
|
|
|
|
def test_xoptions(self):
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(),
|
|
|
|
[sys.executable, "-Xutf8", "-Xa=b", __file__, "runserver"],
|
|
|
|
)
|
|
|
|
|
2021-08-15 16:10:36 +00:00
|
|
|
@mock.patch("__main__.__spec__", None)
|
2020-06-18 11:04:10 +00:00
|
|
|
@mock.patch("sys.warnoptions", [])
|
|
|
|
def test_exe_fallback(self):
|
2020-07-20 09:08:23 +00:00
|
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
|
|
exe_path = Path(tmpdir) / "django-admin.exe"
|
|
|
|
exe_path.touch()
|
2021-01-19 07:35:16 +00:00
|
|
|
with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]):
|
2023-08-26 14:23:19 +00:00
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(), [exe_path, "runserver"]
|
|
|
|
)
|
|
|
|
|
|
|
|
@mock.patch("sys.warnoptions", [])
|
|
|
|
@mock.patch.dict(sys.modules, {"__main__": django.__main__})
|
|
|
|
def test_use_exe_when_main_spec(self):
|
|
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
|
|
exe_path = Path(tmpdir) / "django-admin.exe"
|
|
|
|
exe_path.touch()
|
|
|
|
with mock.patch("sys.argv", [exe_path.with_suffix(""), "runserver"]):
|
2020-07-20 09:08:23 +00:00
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(), [exe_path, "runserver"]
|
|
|
|
)
|
2020-06-18 11:04:10 +00:00
|
|
|
|
2021-08-15 16:10:36 +00:00
|
|
|
@mock.patch("__main__.__spec__", None)
|
2020-06-18 11:04:10 +00:00
|
|
|
@mock.patch("sys.warnoptions", [])
|
2021-08-15 02:48:23 +00:00
|
|
|
@mock.patch("sys._xoptions", {})
|
2020-06-18 11:04:10 +00:00
|
|
|
def test_entrypoint_fallback(self):
|
2020-07-20 09:08:23 +00:00
|
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
|
|
script_path = Path(tmpdir) / "django-admin-script.py"
|
|
|
|
script_path.touch()
|
2021-01-19 07:35:16 +00:00
|
|
|
with mock.patch(
|
|
|
|
"sys.argv", [script_path.with_name("django-admin"), "runserver"]
|
|
|
|
):
|
2020-07-20 09:08:23 +00:00
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(),
|
2021-01-19 07:35:16 +00:00
|
|
|
[sys.executable, script_path, "runserver"],
|
2020-07-20 09:08:23 +00:00
|
|
|
)
|
2020-06-18 11:04:10 +00:00
|
|
|
|
2021-08-15 16:10:36 +00:00
|
|
|
@mock.patch("__main__.__spec__", None)
|
2020-06-18 11:04:10 +00:00
|
|
|
@mock.patch("sys.argv", ["does-not-exist", "runserver"])
|
|
|
|
@mock.patch("sys.warnoptions", [])
|
|
|
|
def test_raises_runtimeerror(self):
|
|
|
|
msg = "Script does-not-exist does not exist."
|
|
|
|
with self.assertRaisesMessage(RuntimeError, msg):
|
|
|
|
autoreload.get_child_arguments()
|
|
|
|
|
2021-05-26 09:19:47 +00:00
|
|
|
@mock.patch("sys.argv", [__file__, "runserver"])
|
|
|
|
@mock.patch("sys.warnoptions", [])
|
2021-08-15 02:48:23 +00:00
|
|
|
@mock.patch("sys._xoptions", {})
|
2021-05-26 09:19:47 +00:00
|
|
|
def test_module_no_spec(self):
|
|
|
|
module = types.ModuleType("test_module")
|
|
|
|
del module.__spec__
|
|
|
|
with mock.patch.dict(sys.modules, {"__main__": module}):
|
|
|
|
self.assertEqual(
|
|
|
|
autoreload.get_child_arguments(),
|
|
|
|
[sys.executable, __file__, "runserver"],
|
|
|
|
)
|
|
|
|
|
2020-06-18 11:04:10 +00:00
|
|
|
|
2020-11-05 11:18:20 +00:00
|
|
|
class TestUtilities(SimpleTestCase):
|
|
|
|
def test_is_django_module(self):
|
|
|
|
for module, expected in ((zoneinfo, False), (sys, False), (autoreload, True)):
|
|
|
|
with self.subTest(module=module):
|
|
|
|
self.assertIs(autoreload.is_django_module(module), expected)
|
|
|
|
|
|
|
|
def test_is_django_path(self):
|
|
|
|
for module, expected in (
|
2021-09-09 13:15:44 +00:00
|
|
|
(zoneinfo.__file__, False),
|
2020-11-05 11:18:20 +00:00
|
|
|
(contextlib.__file__, False),
|
|
|
|
(autoreload.__file__, True),
|
|
|
|
):
|
|
|
|
with self.subTest(module=module):
|
|
|
|
self.assertIs(autoreload.is_django_path(module), expected)
|
|
|
|
|
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
class TestCommonRoots(SimpleTestCase):
|
|
|
|
def test_common_roots(self):
|
|
|
|
paths = (
|
|
|
|
Path("/first/second"),
|
|
|
|
Path("/first/second/third"),
|
|
|
|
Path("/first/"),
|
|
|
|
Path("/root/first/"),
|
|
|
|
)
|
|
|
|
results = autoreload.common_roots(paths)
|
|
|
|
self.assertCountEqual(results, [Path("/first/"), Path("/root/first/")])
|
2016-11-07 23:51:23 +00:00
|
|
|
|
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
class TestSysPathDirectories(SimpleTestCase):
|
2016-11-07 23:51:23 +00:00
|
|
|
def setUp(self):
|
2023-12-31 09:01:31 +00:00
|
|
|
_directory = tempfile.TemporaryDirectory()
|
|
|
|
self.addCleanup(_directory.cleanup)
|
|
|
|
self.directory = Path(_directory.name).resolve(strict=True).absolute()
|
2019-01-14 01:33:47 +00:00
|
|
|
self.file = self.directory / "test"
|
|
|
|
self.file.touch()
|
2016-11-07 23:51:23 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_sys_paths_with_directories(self):
|
|
|
|
with extend_sys_path(str(self.file)):
|
|
|
|
paths = list(autoreload.sys_path_directories())
|
|
|
|
self.assertIn(self.file.parent, paths)
|
|
|
|
|
|
|
|
def test_sys_paths_non_existing(self):
|
2019-02-11 13:55:57 +00:00
|
|
|
nonexistent_file = Path(self.directory.name) / "does_not_exist"
|
|
|
|
with extend_sys_path(str(nonexistent_file)):
|
2019-01-14 01:33:47 +00:00
|
|
|
paths = list(autoreload.sys_path_directories())
|
2019-02-11 13:55:57 +00:00
|
|
|
self.assertNotIn(nonexistent_file, paths)
|
|
|
|
self.assertNotIn(nonexistent_file.parent, paths)
|
2019-01-14 01:33:47 +00:00
|
|
|
|
|
|
|
def test_sys_paths_absolute(self):
|
|
|
|
paths = list(autoreload.sys_path_directories())
|
|
|
|
self.assertTrue(all(p.is_absolute() for p in paths))
|
|
|
|
|
|
|
|
def test_sys_paths_directories(self):
|
|
|
|
with extend_sys_path(str(self.directory)):
|
|
|
|
paths = list(autoreload.sys_path_directories())
|
|
|
|
self.assertIn(self.directory, paths)
|
|
|
|
|
|
|
|
|
|
|
|
class GetReloaderTests(SimpleTestCase):
|
|
|
|
@mock.patch("django.utils.autoreload.WatchmanReloader")
|
|
|
|
def test_watchman_unavailable(self, mocked_watchman):
|
|
|
|
mocked_watchman.check_availability.side_effect = WatchmanUnavailable
|
|
|
|
self.assertIsInstance(autoreload.get_reloader(), autoreload.StatReloader)
|
|
|
|
|
|
|
|
@mock.patch.object(autoreload.WatchmanReloader, "check_availability")
|
|
|
|
def test_watchman_available(self, mocked_available):
|
|
|
|
# If WatchmanUnavailable isn't raised, Watchman will be chosen.
|
|
|
|
mocked_available.return_value = None
|
|
|
|
result = autoreload.get_reloader()
|
|
|
|
self.assertIsInstance(result, autoreload.WatchmanReloader)
|
|
|
|
|
|
|
|
|
|
|
|
class RunWithReloaderTests(SimpleTestCase):
|
|
|
|
@mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"})
|
|
|
|
@mock.patch("django.utils.autoreload.get_reloader")
|
|
|
|
def test_swallows_keyboard_interrupt(self, mocked_get_reloader):
|
|
|
|
mocked_get_reloader.side_effect = KeyboardInterrupt()
|
|
|
|
autoreload.run_with_reloader(lambda: None) # No exception
|
|
|
|
|
|
|
|
@mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "false"})
|
|
|
|
@mock.patch("django.utils.autoreload.restart_with_reloader")
|
|
|
|
def test_calls_sys_exit(self, mocked_restart_reloader):
|
|
|
|
mocked_restart_reloader.return_value = 1
|
|
|
|
with self.assertRaises(SystemExit) as exc:
|
|
|
|
autoreload.run_with_reloader(lambda: None)
|
|
|
|
self.assertEqual(exc.exception.code, 1)
|
|
|
|
|
|
|
|
@mock.patch.dict(os.environ, {autoreload.DJANGO_AUTORELOAD_ENV: "true"})
|
|
|
|
@mock.patch("django.utils.autoreload.start_django")
|
|
|
|
@mock.patch("django.utils.autoreload.get_reloader")
|
|
|
|
def test_calls_start_django(self, mocked_reloader, mocked_start_django):
|
|
|
|
mocked_reloader.return_value = mock.sentinel.RELOADER
|
|
|
|
autoreload.run_with_reloader(mock.sentinel.METHOD)
|
|
|
|
self.assertEqual(mocked_start_django.call_count, 1)
|
|
|
|
self.assertSequenceEqual(
|
|
|
|
mocked_start_django.call_args[0],
|
|
|
|
[mock.sentinel.RELOADER, mock.sentinel.METHOD],
|
|
|
|
)
|
|
|
|
|
2016-11-07 23:51:23 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
class StartDjangoTests(SimpleTestCase):
|
|
|
|
@mock.patch("django.utils.autoreload.ensure_echo_on")
|
|
|
|
def test_echo_on_called(self, mocked_echo):
|
|
|
|
fake_reloader = mock.MagicMock()
|
|
|
|
autoreload.start_django(fake_reloader, lambda: None)
|
|
|
|
self.assertEqual(mocked_echo.call_count, 1)
|
|
|
|
|
|
|
|
@mock.patch("django.utils.autoreload.check_errors")
|
|
|
|
def test_check_errors_called(self, mocked_check_errors):
|
|
|
|
fake_method = mock.MagicMock(return_value=None)
|
|
|
|
fake_reloader = mock.MagicMock()
|
|
|
|
autoreload.start_django(fake_reloader, fake_method)
|
|
|
|
self.assertCountEqual(mocked_check_errors.call_args[0], [fake_method])
|
|
|
|
|
|
|
|
@mock.patch("threading.Thread")
|
|
|
|
@mock.patch("django.utils.autoreload.check_errors")
|
|
|
|
def test_starts_thread_with_args(self, mocked_check_errors, mocked_thread):
|
|
|
|
fake_reloader = mock.MagicMock()
|
|
|
|
fake_main_func = mock.MagicMock()
|
|
|
|
fake_thread = mock.MagicMock()
|
|
|
|
mocked_check_errors.return_value = fake_main_func
|
|
|
|
mocked_thread.return_value = fake_thread
|
|
|
|
autoreload.start_django(fake_reloader, fake_main_func, 123, abc=123)
|
|
|
|
self.assertEqual(mocked_thread.call_count, 1)
|
|
|
|
self.assertEqual(
|
|
|
|
mocked_thread.call_args[1],
|
2019-04-29 08:44:58 +00:00
|
|
|
{
|
|
|
|
"target": fake_main_func,
|
|
|
|
"args": (123,),
|
|
|
|
"kwargs": {"abc": 123},
|
|
|
|
"name": "django-main-thread",
|
2022-02-03 19:24:19 +00:00
|
|
|
},
|
2019-01-14 01:33:47 +00:00
|
|
|
)
|
2021-04-13 06:05:12 +00:00
|
|
|
self.assertIs(fake_thread.daemon, True)
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertTrue(fake_thread.start.called)
|
|
|
|
|
|
|
|
|
|
|
|
class TestCheckErrors(SimpleTestCase):
|
|
|
|
def test_mutates_error_files(self):
|
|
|
|
fake_method = mock.MagicMock(side_effect=RuntimeError())
|
|
|
|
wrapped = autoreload.check_errors(fake_method)
|
|
|
|
with mock.patch.object(autoreload, "_error_files") as mocked_error_files:
|
2021-01-20 08:53:34 +00:00
|
|
|
try:
|
|
|
|
with self.assertRaises(RuntimeError):
|
|
|
|
wrapped()
|
|
|
|
finally:
|
|
|
|
autoreload._exception = None
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertEqual(mocked_error_files.append.call_count, 1)
|
2016-11-07 23:51:23 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
|
|
|
|
class TestRaiseLastException(SimpleTestCase):
|
|
|
|
@mock.patch("django.utils.autoreload._exception", None)
|
|
|
|
def test_no_exception(self):
|
|
|
|
# Should raise no exception if _exception is None
|
|
|
|
autoreload.raise_last_exception()
|
|
|
|
|
|
|
|
def test_raises_exception(self):
|
|
|
|
class MyException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Create an exception
|
|
|
|
try:
|
|
|
|
raise MyException("Test Message")
|
|
|
|
except MyException:
|
|
|
|
exc_info = sys.exc_info()
|
|
|
|
|
|
|
|
with mock.patch("django.utils.autoreload._exception", exc_info):
|
2019-03-15 23:27:57 +00:00
|
|
|
with self.assertRaisesMessage(MyException, "Test Message"):
|
2019-01-14 01:33:47 +00:00
|
|
|
autoreload.raise_last_exception()
|
2017-10-25 07:28:01 +00:00
|
|
|
|
2019-05-28 18:06:39 +00:00
|
|
|
def test_raises_custom_exception(self):
|
|
|
|
class MyException(Exception):
|
|
|
|
def __init__(self, msg, extra_context):
|
|
|
|
super().__init__(msg)
|
|
|
|
self.extra_context = extra_context
|
2022-02-03 19:24:19 +00:00
|
|
|
|
2019-05-28 18:06:39 +00:00
|
|
|
# Create an exception.
|
|
|
|
try:
|
|
|
|
raise MyException("Test Message", "extra context")
|
|
|
|
except MyException:
|
|
|
|
exc_info = sys.exc_info()
|
|
|
|
|
|
|
|
with mock.patch("django.utils.autoreload._exception", exc_info):
|
|
|
|
with self.assertRaisesMessage(MyException, "Test Message"):
|
|
|
|
autoreload.raise_last_exception()
|
|
|
|
|
|
|
|
def test_raises_exception_with_context(self):
|
|
|
|
try:
|
|
|
|
raise Exception(2)
|
|
|
|
except Exception as e:
|
|
|
|
try:
|
|
|
|
raise Exception(1) from e
|
|
|
|
except Exception:
|
|
|
|
exc_info = sys.exc_info()
|
|
|
|
|
|
|
|
with mock.patch("django.utils.autoreload._exception", exc_info):
|
|
|
|
with self.assertRaises(Exception) as cm:
|
|
|
|
autoreload.raise_last_exception()
|
|
|
|
self.assertEqual(cm.exception.args[0], 1)
|
|
|
|
self.assertEqual(cm.exception.__cause__.args[0], 2)
|
|
|
|
|
2017-10-25 07:28:01 +00:00
|
|
|
|
|
|
|
class RestartWithReloaderTests(SimpleTestCase):
|
|
|
|
executable = "/usr/bin/python"
|
|
|
|
|
|
|
|
def patch_autoreload(self, argv):
|
2019-08-23 08:53:36 +00:00
|
|
|
patch_call = mock.patch(
|
|
|
|
"django.utils.autoreload.subprocess.run",
|
|
|
|
return_value=CompletedProcess(argv, 0),
|
|
|
|
)
|
2017-10-25 07:28:01 +00:00
|
|
|
patches = [
|
|
|
|
mock.patch("django.utils.autoreload.sys.argv", argv),
|
|
|
|
mock.patch("django.utils.autoreload.sys.executable", self.executable),
|
|
|
|
mock.patch("django.utils.autoreload.sys.warnoptions", ["all"]),
|
2021-08-15 02:48:23 +00:00
|
|
|
mock.patch("django.utils.autoreload.sys._xoptions", {}),
|
2017-10-25 07:28:01 +00:00
|
|
|
]
|
|
|
|
for p in patches:
|
|
|
|
p.start()
|
|
|
|
self.addCleanup(p.stop)
|
|
|
|
mock_call = patch_call.start()
|
|
|
|
self.addCleanup(patch_call.stop)
|
|
|
|
return mock_call
|
|
|
|
|
|
|
|
def test_manage_py(self):
|
2020-07-18 18:42:35 +00:00
|
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
|
|
script = Path(temp_dir) / "manage.py"
|
|
|
|
script.touch()
|
2020-11-19 11:07:15 +00:00
|
|
|
argv = [str(script), "runserver"]
|
2020-07-18 18:42:35 +00:00
|
|
|
mock_call = self.patch_autoreload(argv)
|
2021-08-15 16:10:36 +00:00
|
|
|
with mock.patch("__main__.__spec__", None):
|
|
|
|
autoreload.restart_with_reloader()
|
2020-07-18 18:42:35 +00:00
|
|
|
self.assertEqual(mock_call.call_count, 1)
|
|
|
|
self.assertEqual(
|
|
|
|
mock_call.call_args[0][0],
|
|
|
|
[self.executable, "-Wall"] + argv,
|
|
|
|
)
|
2017-10-25 07:29:05 +00:00
|
|
|
|
|
|
|
def test_python_m_django(self):
|
|
|
|
main = "/usr/lib/pythonX.Y/site-packages/django/__main__.py"
|
|
|
|
argv = [main, "runserver"]
|
|
|
|
mock_call = self.patch_autoreload(argv)
|
|
|
|
with mock.patch("django.__main__.__file__", main):
|
2021-01-04 14:50:49 +00:00
|
|
|
with mock.patch.dict(sys.modules, {"__main__": django.__main__}):
|
|
|
|
autoreload.restart_with_reloader()
|
2017-10-25 07:29:05 +00:00
|
|
|
self.assertEqual(mock_call.call_count, 1)
|
|
|
|
self.assertEqual(
|
|
|
|
mock_call.call_args[0][0],
|
|
|
|
[self.executable, "-Wall", "-m", "django"] + argv[1:],
|
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ReloaderTests(SimpleTestCase):
|
|
|
|
RELOADER_CLS = None
|
|
|
|
|
|
|
|
def setUp(self):
|
2023-12-31 09:01:31 +00:00
|
|
|
_tempdir = tempfile.TemporaryDirectory()
|
|
|
|
self.tempdir = Path(_tempdir.name).resolve(strict=True).absolute()
|
2019-01-14 01:33:47 +00:00
|
|
|
self.existing_file = self.ensure_file(self.tempdir / "test.py")
|
2019-02-11 13:55:57 +00:00
|
|
|
self.nonexistent_file = (self.tempdir / "does_not_exist.py").absolute()
|
2019-01-14 01:33:47 +00:00
|
|
|
self.reloader = self.RELOADER_CLS()
|
2023-12-31 09:01:31 +00:00
|
|
|
self.addCleanup(self.reloader.stop)
|
|
|
|
self.addCleanup(_tempdir.cleanup)
|
2019-01-14 01:33:47 +00:00
|
|
|
|
|
|
|
def ensure_file(self, path):
|
|
|
|
path.parent.mkdir(exist_ok=True, parents=True)
|
|
|
|
path.touch()
|
|
|
|
# On Linux and Windows updating the mtime of a file using touch() will
|
|
|
|
# set a timestamp value that is in the past, as the time value for the
|
|
|
|
# last kernel tick is used rather than getting the correct absolute
|
|
|
|
# time.
|
|
|
|
# To make testing simpler set the mtime to be the observed time when
|
|
|
|
# this function is called.
|
|
|
|
self.set_mtime(path, time.time())
|
|
|
|
return path.absolute()
|
|
|
|
|
|
|
|
def set_mtime(self, fp, value):
|
|
|
|
os.utime(str(fp), (value, value))
|
|
|
|
|
|
|
|
def increment_mtime(self, fp, by=1):
|
|
|
|
current_time = time.time()
|
|
|
|
self.set_mtime(fp, current_time + by)
|
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def tick_twice(self):
|
|
|
|
ticker = self.reloader.tick()
|
|
|
|
next(ticker)
|
|
|
|
yield
|
|
|
|
next(ticker)
|
|
|
|
|
|
|
|
|
|
|
|
class IntegrationTests:
|
|
|
|
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
|
|
|
|
@mock.patch(
|
|
|
|
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_glob(self, mocked_modules, notify_mock):
|
|
|
|
non_py_file = self.ensure_file(self.tempdir / "non_py_file")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "*.py")
|
|
|
|
with self.tick_twice():
|
|
|
|
self.increment_mtime(non_py_file)
|
|
|
|
self.increment_mtime(self.existing_file)
|
|
|
|
self.assertEqual(notify_mock.call_count, 1)
|
|
|
|
self.assertCountEqual(notify_mock.call_args[0], [self.existing_file])
|
|
|
|
|
|
|
|
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
|
|
|
|
@mock.patch(
|
|
|
|
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_multiple_globs(self, mocked_modules, notify_mock):
|
|
|
|
self.ensure_file(self.tempdir / "x.test")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "*.py")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "*.test")
|
|
|
|
with self.tick_twice():
|
|
|
|
self.increment_mtime(self.existing_file)
|
|
|
|
self.assertEqual(notify_mock.call_count, 1)
|
|
|
|
self.assertCountEqual(notify_mock.call_args[0], [self.existing_file])
|
|
|
|
|
|
|
|
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
|
|
|
|
@mock.patch(
|
|
|
|
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_overlapping_globs(self, mocked_modules, notify_mock):
|
|
|
|
self.reloader.watch_dir(self.tempdir, "*.py")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "*.p*")
|
|
|
|
with self.tick_twice():
|
|
|
|
self.increment_mtime(self.existing_file)
|
|
|
|
self.assertEqual(notify_mock.call_count, 1)
|
|
|
|
self.assertCountEqual(notify_mock.call_args[0], [self.existing_file])
|
|
|
|
|
|
|
|
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
|
|
|
|
@mock.patch(
|
|
|
|
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_glob_recursive(self, mocked_modules, notify_mock):
|
|
|
|
non_py_file = self.ensure_file(self.tempdir / "dir" / "non_py_file")
|
|
|
|
py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "**/*.py")
|
|
|
|
with self.tick_twice():
|
|
|
|
self.increment_mtime(non_py_file)
|
|
|
|
self.increment_mtime(py_file)
|
|
|
|
self.assertEqual(notify_mock.call_count, 1)
|
|
|
|
self.assertCountEqual(notify_mock.call_args[0], [py_file])
|
|
|
|
|
|
|
|
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
|
|
|
|
@mock.patch(
|
|
|
|
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_multiple_recursive_globs(self, mocked_modules, notify_mock):
|
|
|
|
non_py_file = self.ensure_file(self.tempdir / "dir" / "test.txt")
|
|
|
|
py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "**/*.txt")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "**/*.py")
|
|
|
|
with self.tick_twice():
|
|
|
|
self.increment_mtime(non_py_file)
|
|
|
|
self.increment_mtime(py_file)
|
|
|
|
self.assertEqual(notify_mock.call_count, 2)
|
|
|
|
self.assertCountEqual(
|
|
|
|
notify_mock.call_args_list, [mock.call(py_file), mock.call(non_py_file)]
|
|
|
|
)
|
|
|
|
|
|
|
|
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
|
|
|
|
@mock.patch(
|
|
|
|
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_nested_glob_recursive(self, mocked_modules, notify_mock):
|
|
|
|
inner_py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "**/*.py")
|
|
|
|
self.reloader.watch_dir(inner_py_file.parent, "**/*.py")
|
|
|
|
with self.tick_twice():
|
|
|
|
self.increment_mtime(inner_py_file)
|
|
|
|
self.assertEqual(notify_mock.call_count, 1)
|
|
|
|
self.assertCountEqual(notify_mock.call_args[0], [inner_py_file])
|
|
|
|
|
|
|
|
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
|
|
|
|
@mock.patch(
|
|
|
|
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
|
2022-02-03 19:24:19 +00:00
|
|
|
)
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_overlapping_glob_recursive(self, mocked_modules, notify_mock):
|
|
|
|
py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "**/*.p*")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "**/*.py*")
|
|
|
|
with self.tick_twice():
|
|
|
|
self.increment_mtime(py_file)
|
|
|
|
self.assertEqual(notify_mock.call_count, 1)
|
|
|
|
self.assertCountEqual(notify_mock.call_args[0], [py_file])
|
|
|
|
|
|
|
|
|
|
|
|
class BaseReloaderTests(ReloaderTests):
|
|
|
|
RELOADER_CLS = autoreload.BaseReloader
|
|
|
|
|
2019-07-21 21:28:39 +00:00
|
|
|
def test_watch_dir_with_unresolvable_path(self):
|
|
|
|
path = Path("unresolvable_directory")
|
|
|
|
with mock.patch.object(Path, "absolute", side_effect=FileNotFoundError):
|
|
|
|
self.reloader.watch_dir(path, "**/*.mo")
|
|
|
|
self.assertEqual(list(self.reloader.directory_globs), [])
|
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_watch_with_glob(self):
|
|
|
|
self.reloader.watch_dir(self.tempdir, "*.py")
|
|
|
|
watched_files = list(self.reloader.watched_files())
|
|
|
|
self.assertIn(self.existing_file, watched_files)
|
|
|
|
|
|
|
|
def test_watch_files_with_recursive_glob(self):
|
|
|
|
inner_file = self.ensure_file(self.tempdir / "test" / "test.py")
|
|
|
|
self.reloader.watch_dir(self.tempdir, "**/*.py")
|
|
|
|
watched_files = list(self.reloader.watched_files())
|
|
|
|
self.assertIn(self.existing_file, watched_files)
|
|
|
|
self.assertIn(inner_file, watched_files)
|
|
|
|
|
|
|
|
def test_run_loop_catches_stopiteration(self):
|
|
|
|
def mocked_tick():
|
|
|
|
yield
|
|
|
|
|
|
|
|
with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick:
|
|
|
|
self.reloader.run_loop()
|
|
|
|
self.assertEqual(tick.call_count, 1)
|
|
|
|
|
|
|
|
def test_run_loop_stop_and_return(self):
|
|
|
|
def mocked_tick(*args):
|
|
|
|
yield
|
|
|
|
self.reloader.stop()
|
|
|
|
return # Raises StopIteration
|
|
|
|
|
|
|
|
with mock.patch.object(self.reloader, "tick", side_effect=mocked_tick) as tick:
|
|
|
|
self.reloader.run_loop()
|
|
|
|
|
|
|
|
self.assertEqual(tick.call_count, 1)
|
|
|
|
|
|
|
|
def test_wait_for_apps_ready_checks_for_exception(self):
|
|
|
|
app_reg = Apps()
|
|
|
|
app_reg.ready_event.set()
|
|
|
|
# thread.is_alive() is False if it's not started.
|
|
|
|
dead_thread = threading.Thread()
|
|
|
|
self.assertFalse(self.reloader.wait_for_apps_ready(app_reg, dead_thread))
|
|
|
|
|
|
|
|
def test_wait_for_apps_ready_without_exception(self):
|
|
|
|
app_reg = Apps()
|
|
|
|
app_reg.ready_event.set()
|
|
|
|
thread = mock.MagicMock()
|
|
|
|
thread.is_alive.return_value = True
|
|
|
|
self.assertTrue(self.reloader.wait_for_apps_ready(app_reg, thread))
|
|
|
|
|
|
|
|
|
|
|
|
def skip_unless_watchman_available():
|
|
|
|
try:
|
|
|
|
autoreload.WatchmanReloader.check_availability()
|
|
|
|
except WatchmanUnavailable as e:
|
|
|
|
return skip("Watchman unavailable: %s" % e)
|
|
|
|
return lambda func: func
|
|
|
|
|
|
|
|
|
|
|
|
@skip_unless_watchman_available()
|
|
|
|
class WatchmanReloaderTests(ReloaderTests, IntegrationTests):
|
|
|
|
RELOADER_CLS = autoreload.WatchmanReloader
|
|
|
|
|
2019-04-23 16:08:05 +00:00
|
|
|
def setUp(self):
|
|
|
|
super().setUp()
|
|
|
|
# Shorten the timeout to speed up tests.
|
2021-07-23 09:40:57 +00:00
|
|
|
self.reloader.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 2))
|
2019-04-23 16:08:05 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_watch_glob_ignores_non_existing_directories_two_levels(self):
|
|
|
|
with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe:
|
|
|
|
self.reloader._watch_glob(self.tempdir / "does_not_exist" / "more", ["*"])
|
|
|
|
self.assertFalse(mocked_subscribe.called)
|
|
|
|
|
|
|
|
def test_watch_glob_uses_existing_parent_directories(self):
|
|
|
|
with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe:
|
|
|
|
self.reloader._watch_glob(self.tempdir / "does_not_exist", ["*"])
|
|
|
|
self.assertSequenceEqual(
|
|
|
|
mocked_subscribe.call_args[0],
|
|
|
|
[
|
|
|
|
self.tempdir,
|
|
|
|
"glob-parent-does_not_exist:%s" % self.tempdir,
|
|
|
|
["anyof", ["match", "does_not_exist/*", "wholename"]],
|
|
|
|
],
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_watch_glob_multiple_patterns(self):
|
|
|
|
with mock.patch.object(self.reloader, "_subscribe") as mocked_subscribe:
|
|
|
|
self.reloader._watch_glob(self.tempdir, ["*", "*.py"])
|
|
|
|
self.assertSequenceEqual(
|
|
|
|
mocked_subscribe.call_args[0],
|
|
|
|
[
|
|
|
|
self.tempdir,
|
|
|
|
"glob:%s" % self.tempdir,
|
|
|
|
["anyof", ["match", "*", "wholename"], ["match", "*.py", "wholename"]],
|
|
|
|
],
|
|
|
|
)
|
|
|
|
|
|
|
|
def test_watched_roots_contains_files(self):
|
|
|
|
paths = self.reloader.watched_roots([self.existing_file])
|
|
|
|
self.assertIn(self.existing_file.parent, paths)
|
|
|
|
|
|
|
|
def test_watched_roots_contains_directory_globs(self):
|
|
|
|
self.reloader.watch_dir(self.tempdir, "*.py")
|
|
|
|
paths = self.reloader.watched_roots([])
|
|
|
|
self.assertIn(self.tempdir, paths)
|
|
|
|
|
|
|
|
def test_watched_roots_contains_sys_path(self):
|
|
|
|
with extend_sys_path(str(self.tempdir)):
|
|
|
|
paths = self.reloader.watched_roots([])
|
|
|
|
self.assertIn(self.tempdir, paths)
|
|
|
|
|
|
|
|
def test_check_server_status(self):
|
|
|
|
self.assertTrue(self.reloader.check_server_status())
|
|
|
|
|
|
|
|
def test_check_server_status_raises_error(self):
|
|
|
|
with mock.patch.object(self.reloader.client, "query") as mocked_query:
|
|
|
|
mocked_query.side_effect = Exception()
|
|
|
|
with self.assertRaises(autoreload.WatchmanUnavailable):
|
|
|
|
self.reloader.check_server_status()
|
|
|
|
|
|
|
|
@mock.patch("pywatchman.client")
|
|
|
|
def test_check_availability(self, mocked_client):
|
|
|
|
mocked_client().capabilityCheck.side_effect = Exception()
|
|
|
|
with self.assertRaisesMessage(
|
|
|
|
WatchmanUnavailable, "Cannot connect to the watchman service"
|
|
|
|
):
|
|
|
|
self.RELOADER_CLS.check_availability()
|
|
|
|
|
|
|
|
@mock.patch("pywatchman.client")
|
|
|
|
def test_check_availability_lower_version(self, mocked_client):
|
|
|
|
mocked_client().capabilityCheck.return_value = {"version": "4.8.10"}
|
|
|
|
with self.assertRaisesMessage(
|
|
|
|
WatchmanUnavailable, "Watchman 4.9 or later is required."
|
|
|
|
):
|
|
|
|
self.RELOADER_CLS.check_availability()
|
|
|
|
|
|
|
|
def test_pywatchman_not_available(self):
|
|
|
|
with mock.patch.object(autoreload, "pywatchman") as mocked:
|
|
|
|
mocked.__bool__.return_value = False
|
|
|
|
with self.assertRaisesMessage(
|
|
|
|
WatchmanUnavailable, "pywatchman not installed."
|
|
|
|
):
|
|
|
|
self.RELOADER_CLS.check_availability()
|
|
|
|
|
|
|
|
def test_update_watches_raises_exceptions(self):
|
|
|
|
class TestException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
with mock.patch.object(self.reloader, "_update_watches") as mocked_watches:
|
|
|
|
with mock.patch.object(
|
|
|
|
self.reloader, "check_server_status"
|
|
|
|
) as mocked_server_status:
|
|
|
|
mocked_watches.side_effect = TestException()
|
|
|
|
mocked_server_status.return_value = True
|
|
|
|
with self.assertRaises(TestException):
|
|
|
|
self.reloader.update_watches()
|
|
|
|
self.assertIsInstance(
|
|
|
|
mocked_server_status.call_args[0][0], TestException
|
|
|
|
)
|
|
|
|
|
2019-04-23 16:08:05 +00:00
|
|
|
@mock.patch.dict(os.environ, {"DJANGO_WATCHMAN_TIMEOUT": "10"})
|
|
|
|
def test_setting_timeout_from_environment_variable(self):
|
2019-09-26 21:55:25 +00:00
|
|
|
self.assertEqual(self.RELOADER_CLS().client_timeout, 10)
|
2019-04-23 16:08:05 +00:00
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
|
2019-04-24 09:46:55 +00:00
|
|
|
@skipIf(on_macos_with_hfs(), "These tests do not work with HFS+ as a filesystem")
|
2019-01-14 01:33:47 +00:00
|
|
|
class StatReloaderTests(ReloaderTests, IntegrationTests):
|
|
|
|
RELOADER_CLS = autoreload.StatReloader
|
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
super().setUp()
|
|
|
|
# Shorten the sleep time to speed up tests.
|
|
|
|
self.reloader.SLEEP_TIME = 0.01
|
|
|
|
|
2019-05-27 11:50:05 +00:00
|
|
|
@mock.patch("django.utils.autoreload.StatReloader.notify_file_changed")
|
|
|
|
def test_tick_does_not_trigger_twice(self, mock_notify_file_changed):
|
|
|
|
with mock.patch.object(
|
|
|
|
self.reloader, "watched_files", return_value=[self.existing_file]
|
|
|
|
):
|
|
|
|
ticker = self.reloader.tick()
|
|
|
|
next(ticker)
|
|
|
|
self.increment_mtime(self.existing_file)
|
|
|
|
next(ticker)
|
|
|
|
next(ticker)
|
|
|
|
self.assertEqual(mock_notify_file_changed.call_count, 1)
|
|
|
|
|
2019-01-14 01:33:47 +00:00
|
|
|
def test_snapshot_files_ignores_missing_files(self):
|
2019-02-11 13:55:57 +00:00
|
|
|
with mock.patch.object(
|
|
|
|
self.reloader, "watched_files", return_value=[self.nonexistent_file]
|
|
|
|
):
|
2019-01-14 01:33:47 +00:00
|
|
|
self.assertEqual(dict(self.reloader.snapshot_files()), {})
|
|
|
|
|
|
|
|
def test_snapshot_files_updates(self):
|
|
|
|
with mock.patch.object(
|
|
|
|
self.reloader, "watched_files", return_value=[self.existing_file]
|
|
|
|
):
|
|
|
|
snapshot1 = dict(self.reloader.snapshot_files())
|
|
|
|
self.assertIn(self.existing_file, snapshot1)
|
|
|
|
self.increment_mtime(self.existing_file)
|
|
|
|
snapshot2 = dict(self.reloader.snapshot_files())
|
|
|
|
self.assertNotEqual(
|
|
|
|
snapshot1[self.existing_file], snapshot2[self.existing_file]
|
|
|
|
)
|
|
|
|
|
2019-04-29 08:44:58 +00:00
|
|
|
def test_snapshot_files_with_duplicates(self):
|
|
|
|
with mock.patch.object(
|
|
|
|
self.reloader,
|
|
|
|
"watched_files",
|
|
|
|
return_value=[self.existing_file, self.existing_file],
|
|
|
|
):
|
|
|
|
snapshot = list(self.reloader.snapshot_files())
|
|
|
|
self.assertEqual(len(snapshot), 1)
|
|
|
|
self.assertEqual(snapshot[0][0], self.existing_file)
|