conftest.py 5.8 KB

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