haystack/test/core/test_importing.py
Stefano Fiorucci 9546e69374
perf: Optimize import times (#8878)
* initial experiments

* progress

* draft

* fix header

* fix linting

* lot more lazy inits

* fixes to main init

* linting

* small refinements

* header fix

* release note

* improve consistency

* test: make sure no extra modules are being imported due to `__init__` definitions

* extend release note with an example

* refactoring import test

* updating release notes

* casting .keys() to list

* reverting to list

* Update haystack/__init__.py

Co-authored-by: Julian Risch <julian.risch@deepset.ai>

* fixing ident problem

* better comments

---------

Co-authored-by: David S. Batista <dsbatista@gmail.com>
Co-authored-by: Julian Risch <julian.risch@deepset.ai>
2025-02-21 09:55:20 +01:00

25 lines
999 B
Python

# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
#
# SPDX-License-Identifier: Apache-2.0
import sys
from unittest.mock import patch
def test_lazy_import():
# Save the original state of the module if it exists
original_imported = sys.modules.get("haystack.components.generators.chat.azure")
with patch.dict(sys.modules):
# Remove the module from sys.modules if it was already imported
if original_imported:
del sys.modules["haystack.components.generators.chat.azure"]
from haystack.components.generators.chat import OpenAIChatGenerator # Import the intended class
assert "haystack.components.generators.chat.openai" in sys.modules.keys()
assert "haystack.components.generators.chat.azure" not in sys.modules.keys()
# Restore the module if it was previously imported (preserves test isolation)
if original_imported:
sys.modules["haystack.components.generators.chat.azure"] = original_imported