conftest.py 5.6 KB

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