conftest.py 5.3 KB

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