conftest.py 4.9 KB

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