1
0

conftest.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. """Test fixtures."""
  2. import asyncio
  3. import contextlib
  4. import os
  5. import platform
  6. import uuid
  7. from pathlib import Path
  8. from typing import Dict, Generator, Type
  9. from unittest import mock
  10. import pytest
  11. from reflex.app import App
  12. from reflex.event import EventSpec
  13. from reflex.model import ModelRegistry
  14. from reflex.utils import prerequisites
  15. from .states import (
  16. DictMutationTestState,
  17. ListMutationTestState,
  18. MutableTestState,
  19. SubUploadState,
  20. UploadState,
  21. )
  22. def pytest_configure(config):
  23. if config.getoption("asyncio_mode") == "auto":
  24. asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
  25. @pytest.fixture
  26. def app() -> App:
  27. """A base app.
  28. Returns:
  29. The app.
  30. """
  31. return App()
  32. @pytest.fixture
  33. def app_module_mock(monkeypatch) -> mock.Mock:
  34. """Mock the app module.
  35. This overwrites prerequisites.get_app to return the mock for the app module.
  36. To use this in your test, assign `app_module_mock.app = rx.App(...)`.
  37. Args:
  38. monkeypatch: pytest monkeypatch fixture.
  39. Returns:
  40. The mock for the main app module.
  41. """
  42. app_module_mock = mock.Mock()
  43. get_app_mock = mock.Mock(return_value=app_module_mock)
  44. monkeypatch.setattr(prerequisites, "get_app", get_app_mock)
  45. return app_module_mock
  46. @pytest.fixture(scope="session")
  47. def windows_platform() -> Generator:
  48. """Check if system is windows.
  49. Yields:
  50. whether system is windows.
  51. """
  52. yield platform.system() == "Windows"
  53. @pytest.fixture
  54. def list_mutation_state():
  55. """Create a state with list mutation features.
  56. Returns:
  57. A state with list mutation features.
  58. """
  59. return ListMutationTestState()
  60. @pytest.fixture
  61. def dict_mutation_state():
  62. """Create a state with dict mutation features.
  63. Returns:
  64. A state with dict mutation features.
  65. """
  66. return DictMutationTestState()
  67. @pytest.fixture
  68. def upload_sub_state_event_spec():
  69. """Create an event Spec for a substate.
  70. Returns:
  71. Event Spec.
  72. """
  73. return EventSpec(handler=SubUploadState.handle_upload, upload=True) # type: ignore
  74. @pytest.fixture
  75. def upload_event_spec():
  76. """Create an event Spec for a multi-upload base state.
  77. Returns:
  78. Event Spec.
  79. """
  80. return EventSpec(handler=UploadState.handle_upload1, upload=True) # type: ignore
  81. @pytest.fixture
  82. def base_config_values() -> Dict:
  83. """Get base config values.
  84. Returns:
  85. Dictionary of base config values
  86. """
  87. return {"app_name": "app"}
  88. @pytest.fixture
  89. def base_db_config_values() -> Dict:
  90. """Get base DBConfig values.
  91. Returns:
  92. Dictionary of base db config values
  93. """
  94. return {"database": "db"}
  95. @pytest.fixture
  96. def sqlite_db_config_values(base_db_config_values) -> Dict:
  97. """Get sqlite DBConfig values.
  98. Args:
  99. base_db_config_values: Base DBConfig fixture.
  100. Returns:
  101. Dictionary of sqlite DBConfig values
  102. """
  103. base_db_config_values["engine"] = "sqlite"
  104. return base_db_config_values
  105. @pytest.fixture
  106. def router_data_headers() -> Dict[str, str]:
  107. """Router data headers.
  108. Returns:
  109. client headers
  110. """
  111. return {
  112. "host": "localhost:8000",
  113. "connection": "Upgrade",
  114. "pragma": "no-cache",
  115. "cache-control": "no-cache",
  116. "user-agent": "Mock Agent",
  117. "upgrade": "websocket",
  118. "origin": "http://localhost:3000",
  119. "sec-websocket-version": "13",
  120. "accept-encoding": "gzip, deflate, br",
  121. "accept-language": "en-US,en;q=0.9",
  122. "cookie": "csrftoken=mocktoken; "
  123. "name=reflex;"
  124. " list_cookies=%5B%22some%22%2C%20%22random%22%2C%20%22cookies%22%5D;"
  125. " dict_cookies=%7B%22name%22%3A%20%22reflex%22%7D; val=true",
  126. "sec-websocket-key": "mock-websocket-key",
  127. "sec-websocket-extensions": "permessage-deflate; client_max_window_bits",
  128. }
  129. @pytest.fixture
  130. def router_data(router_data_headers) -> Dict[str, str]:
  131. """Router data.
  132. Args:
  133. router_data_headers: Headers fixture.
  134. Returns:
  135. Dict of router data.
  136. """
  137. return { # type: ignore
  138. "pathname": "/",
  139. "query": {},
  140. "token": "b181904c-3953-4a79-dc18-ae9518c22f05",
  141. "sid": "9fpxSzPb9aFMb4wFAAAH",
  142. "headers": router_data_headers,
  143. "ip": "127.0.0.1",
  144. }
  145. # borrowed from py3.11
  146. class chdir(contextlib.AbstractContextManager):
  147. """Non thread-safe context manager to change the current working directory."""
  148. def __init__(self, path):
  149. """Prepare contextmanager.
  150. Args:
  151. path: the path to change to
  152. """
  153. self.path = path
  154. self._old_cwd = []
  155. def __enter__(self):
  156. """Save current directory and perform chdir."""
  157. self._old_cwd.append(Path.cwd())
  158. os.chdir(self.path)
  159. def __exit__(self, *excinfo):
  160. """Change back to previous directory on stack.
  161. Args:
  162. excinfo: sys.exc_info captured in the context block
  163. """
  164. os.chdir(self._old_cwd.pop())
  165. @pytest.fixture
  166. def tmp_working_dir(tmp_path):
  167. """Create a temporary directory and chdir to it.
  168. After the test executes, chdir back to the original working directory.
  169. Args:
  170. tmp_path: pytest tmp_path fixture creates per-test temp dir
  171. Yields:
  172. subdirectory of tmp_path which is now the current working directory.
  173. """
  174. working_dir = tmp_path / "working_dir"
  175. working_dir.mkdir()
  176. with chdir(working_dir):
  177. yield working_dir
  178. @pytest.fixture
  179. def mutable_state() -> MutableTestState:
  180. """Create a Test state containing mutable types.
  181. Returns:
  182. A state object.
  183. """
  184. return MutableTestState()
  185. @pytest.fixture(scope="function")
  186. def token() -> str:
  187. """Create a token.
  188. Returns:
  189. A fresh/unique token string.
  190. """
  191. return str(uuid.uuid4())
  192. @pytest.fixture
  193. def model_registry() -> Generator[Type[ModelRegistry], None, None]:
  194. """Create a model registry.
  195. Yields:
  196. A fresh model registry.
  197. """
  198. yield ModelRegistry
  199. ModelRegistry._metadata = None