conftest.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. """Test fixtures."""
  2. import contextlib
  3. import os
  4. import platform
  5. from pathlib import Path
  6. from typing import Dict, Generator, List, Union
  7. import pytest
  8. import reflex as rx
  9. from reflex import constants
  10. from reflex.app import App
  11. from reflex.event import EventSpec
  12. @pytest.fixture
  13. def app() -> App:
  14. """A base app.
  15. Returns:
  16. The app.
  17. """
  18. return App()
  19. @pytest.fixture(scope="function")
  20. def windows_platform() -> Generator:
  21. """Check if system is windows.
  22. Yields:
  23. whether system is windows.
  24. """
  25. yield platform.system() == "Windows"
  26. @pytest.fixture
  27. def list_mutation_state():
  28. """Create a state with list mutation features.
  29. Returns:
  30. A state with list mutation features.
  31. """
  32. class TestState(rx.State):
  33. """The test state."""
  34. # plain list
  35. plain_friends = ["Tommy"]
  36. def make_friend(self):
  37. self.plain_friends.append("another-fd")
  38. def change_first_friend(self):
  39. self.plain_friends[0] = "Jenny"
  40. def unfriend_all_friends(self):
  41. self.plain_friends.clear()
  42. def unfriend_first_friend(self):
  43. del self.plain_friends[0]
  44. def remove_last_friend(self):
  45. self.plain_friends.pop()
  46. def make_friends_with_colleagues(self):
  47. colleagues = ["Peter", "Jimmy"]
  48. self.plain_friends.extend(colleagues)
  49. def remove_tommy(self):
  50. self.plain_friends.remove("Tommy")
  51. # list in dict
  52. friends_in_dict = {"Tommy": ["Jenny"]}
  53. def remove_jenny_from_tommy(self):
  54. self.friends_in_dict["Tommy"].remove("Jenny")
  55. def add_jimmy_to_tommy_friends(self):
  56. self.friends_in_dict["Tommy"].append("Jimmy")
  57. def tommy_has_no_fds(self):
  58. self.friends_in_dict["Tommy"].clear()
  59. # nested list
  60. friends_in_nested_list = [["Tommy"], ["Jenny"]]
  61. def remove_first_group(self):
  62. self.friends_in_nested_list.pop(0)
  63. def remove_first_person_from_first_group(self):
  64. self.friends_in_nested_list[0].pop(0)
  65. def add_jimmy_to_second_group(self):
  66. self.friends_in_nested_list[1].append("Jimmy")
  67. return TestState()
  68. @pytest.fixture
  69. def dict_mutation_state():
  70. """Create a state with dict mutation features.
  71. Returns:
  72. A state with dict mutation features.
  73. """
  74. class TestState(rx.State):
  75. """The test state."""
  76. # plain dict
  77. details = {"name": "Tommy"}
  78. def add_age(self):
  79. self.details.update({"age": 20}) # type: ignore
  80. def change_name(self):
  81. self.details["name"] = "Jenny"
  82. def remove_last_detail(self):
  83. self.details.popitem()
  84. def clear_details(self):
  85. self.details.clear()
  86. def remove_name(self):
  87. del self.details["name"]
  88. def pop_out_age(self):
  89. self.details.pop("age")
  90. # dict in list
  91. address = [{"home": "home address"}, {"work": "work address"}]
  92. def remove_home_address(self):
  93. self.address[0].pop("home")
  94. def add_street_to_home_address(self):
  95. self.address[0]["street"] = "street address"
  96. # nested dict
  97. friend_in_nested_dict = {"name": "Nikhil", "friend": {"name": "Alek"}}
  98. def change_friend_name(self):
  99. self.friend_in_nested_dict["friend"]["name"] = "Tommy"
  100. def remove_friend(self):
  101. self.friend_in_nested_dict.pop("friend")
  102. def add_friend_age(self):
  103. self.friend_in_nested_dict["friend"]["age"] = 30
  104. return TestState()
  105. class UploadState(rx.State):
  106. """The base state for uploading a file."""
  107. async def handle_upload1(self, files: List[rx.UploadFile]):
  108. """Handle the upload of a file.
  109. Args:
  110. files: The uploaded files.
  111. """
  112. pass
  113. class BaseState(rx.State):
  114. """The test base state."""
  115. pass
  116. class SubUploadState(BaseState):
  117. """The test substate."""
  118. img: str
  119. async def handle_upload(self, files: List[rx.UploadFile]):
  120. """Handle the upload of a file.
  121. Args:
  122. files: The uploaded files.
  123. """
  124. pass
  125. @pytest.fixture
  126. def upload_sub_state_event_spec():
  127. """Create an event Spec for a substate.
  128. Returns:
  129. Event Spec.
  130. """
  131. return EventSpec(handler=SubUploadState.handle_upload, upload=True) # type: ignore
  132. @pytest.fixture
  133. def upload_event_spec():
  134. """Create an event Spec for a multi-upload base state.
  135. Returns:
  136. Event Spec.
  137. """
  138. return EventSpec(handler=UploadState.handle_upload1, upload=True) # type: ignore
  139. @pytest.fixture
  140. def upload_state(tmp_path):
  141. """Create upload state.
  142. Args:
  143. tmp_path: pytest tmp_path
  144. Returns:
  145. The state
  146. """
  147. class FileUploadState(rx.State):
  148. """The base state for uploading a file."""
  149. img_list: List[str]
  150. async def handle_upload2(self, files):
  151. """Handle the upload of a file.
  152. Args:
  153. files: The uploaded files.
  154. """
  155. for file in files:
  156. upload_data = await file.read()
  157. outfile = f"{tmp_path}/{file.filename}"
  158. # Save the file.
  159. with open(outfile, "wb") as file_object:
  160. file_object.write(upload_data)
  161. # Update the img var.
  162. self.img_list.append(file.filename)
  163. async def multi_handle_upload(self, files: List[rx.UploadFile]):
  164. """Handle the upload of a file.
  165. Args:
  166. files: The uploaded files.
  167. """
  168. for file in files:
  169. upload_data = await file.read()
  170. outfile = f"{tmp_path}/{file.filename}"
  171. # Save the file.
  172. with open(outfile, "wb") as file_object:
  173. file_object.write(upload_data)
  174. # Update the img var.
  175. assert file.filename is not None
  176. self.img_list.append(file.filename)
  177. return FileUploadState
  178. @pytest.fixture
  179. def upload_sub_state(tmp_path):
  180. """Create upload substate.
  181. Args:
  182. tmp_path: pytest tmp_path
  183. Returns:
  184. The state
  185. """
  186. class FileState(rx.State):
  187. """The base state."""
  188. pass
  189. class FileUploadState(FileState):
  190. """The substate for uploading a file."""
  191. img_list: List[str]
  192. async def handle_upload2(self, files):
  193. """Handle the upload of a file.
  194. Args:
  195. files: The uploaded files.
  196. """
  197. for file in files:
  198. upload_data = await file.read()
  199. outfile = f"{tmp_path}/{file.filename}"
  200. # Save the file.
  201. with open(outfile, "wb") as file_object:
  202. file_object.write(upload_data)
  203. # Update the img var.
  204. self.img_list.append(file.filename)
  205. async def multi_handle_upload(self, files: List[rx.UploadFile]):
  206. """Handle the upload of a file.
  207. Args:
  208. files: The uploaded files.
  209. """
  210. for file in files:
  211. upload_data = await file.read()
  212. outfile = f"{tmp_path}/{file.filename}"
  213. # Save the file.
  214. with open(outfile, "wb") as file_object:
  215. file_object.write(upload_data)
  216. # Update the img var.
  217. assert file.filename is not None
  218. self.img_list.append(file.filename)
  219. return FileUploadState
  220. @pytest.fixture
  221. def upload_grand_sub_state(tmp_path):
  222. """Create upload grand-state.
  223. Args:
  224. tmp_path: pytest tmp_path
  225. Returns:
  226. The state
  227. """
  228. class BaseFileState(rx.State):
  229. """The base state."""
  230. pass
  231. class FileSubState(BaseFileState):
  232. """The substate."""
  233. pass
  234. class FileUploadState(FileSubState):
  235. """The grand-substate for uploading a file."""
  236. img_list: List[str]
  237. async def handle_upload2(self, files):
  238. """Handle the upload of a file.
  239. Args:
  240. files: The uploaded files.
  241. """
  242. for file in files:
  243. upload_data = await file.read()
  244. outfile = f"{tmp_path}/{file.filename}"
  245. # Save the file.
  246. with open(outfile, "wb") as file_object:
  247. file_object.write(upload_data)
  248. # Update the img var.
  249. assert file.filename is not None
  250. self.img_list.append(file.filename)
  251. async def multi_handle_upload(self, files: List[rx.UploadFile]):
  252. """Handle the upload of a file.
  253. Args:
  254. files: The uploaded files.
  255. """
  256. for file in files:
  257. upload_data = await file.read()
  258. outfile = f"{tmp_path}/{file.filename}"
  259. # Save the file.
  260. with open(outfile, "wb") as file_object:
  261. file_object.write(upload_data)
  262. # Update the img var.
  263. assert file.filename is not None
  264. self.img_list.append(file.filename)
  265. return FileUploadState
  266. @pytest.fixture
  267. def base_config_values() -> Dict:
  268. """Get base config values.
  269. Returns:
  270. Dictionary of base config values
  271. """
  272. return {"app_name": "app", "db_url": constants.DB_URL, "env": rx.Env.DEV}
  273. @pytest.fixture
  274. def base_db_config_values() -> Dict:
  275. """Get base DBConfig values.
  276. Returns:
  277. Dictionary of base db config values
  278. """
  279. return {"database": "db"}
  280. @pytest.fixture
  281. def sqlite_db_config_values(base_db_config_values) -> Dict:
  282. """Get sqlite DBConfig values.
  283. Args:
  284. base_db_config_values: Base DBConfig fixture.
  285. Returns:
  286. Dictionary of sqlite DBConfig values
  287. """
  288. base_db_config_values["engine"] = "sqlite"
  289. return base_db_config_values
  290. class GenState(rx.State):
  291. """A state with event handlers that generate multiple updates."""
  292. value: int
  293. def go(self, c: int):
  294. """Increment the value c times and update each time.
  295. Args:
  296. c: The number of times to increment.
  297. Yields:
  298. After each increment.
  299. """
  300. for _ in range(c):
  301. self.value += 1
  302. yield
  303. @pytest.fixture
  304. def gen_state() -> GenState:
  305. """A state.
  306. Returns:
  307. A test state.
  308. """
  309. return GenState # type: ignore
  310. @pytest.fixture
  311. def router_data_headers() -> Dict[str, str]:
  312. """Router data headers.
  313. Returns:
  314. client headers
  315. """
  316. return {
  317. "host": "localhost:8000",
  318. "connection": "Upgrade",
  319. "pragma": "no-cache",
  320. "cache-control": "no-cache",
  321. "user-agent": "Mock Agent",
  322. "upgrade": "websocket",
  323. "origin": "http://localhost:3000",
  324. "sec-websocket-version": "13",
  325. "accept-encoding": "gzip, deflate, br",
  326. "accept-language": "en-US,en;q=0.9",
  327. "cookie": "csrftoken=mocktoken; "
  328. "name=reflex;"
  329. " list_cookies=%5B%22some%22%2C%20%22random%22%2C%20%22cookies%22%5D;"
  330. " dict_cookies=%7B%22name%22%3A%20%22reflex%22%7D; val=true",
  331. "sec-websocket-key": "mock-websocket-key",
  332. "sec-websocket-extensions": "permessage-deflate; client_max_window_bits",
  333. }
  334. @pytest.fixture
  335. def router_data(router_data_headers) -> Dict[str, str]:
  336. """Router data.
  337. Args:
  338. router_data_headers: Headers fixture.
  339. Returns:
  340. Dict of router data.
  341. """
  342. return { # type: ignore
  343. "pathname": "/",
  344. "query": {},
  345. "token": "b181904c-3953-4a79-dc18-ae9518c22f05",
  346. "sid": "9fpxSzPb9aFMb4wFAAAH",
  347. "headers": router_data_headers,
  348. "ip": "127.0.0.1",
  349. }
  350. # borrowed from py3.11
  351. class chdir(contextlib.AbstractContextManager):
  352. """Non thread-safe context manager to change the current working directory."""
  353. def __init__(self, path):
  354. """Prepare contextmanager.
  355. Args:
  356. path: the path to change to
  357. """
  358. self.path = path
  359. self._old_cwd = []
  360. def __enter__(self):
  361. """Save current directory and perform chdir."""
  362. self._old_cwd.append(Path(".").resolve())
  363. os.chdir(self.path)
  364. def __exit__(self, *excinfo):
  365. """Change back to previous directory on stack.
  366. Args:
  367. excinfo: sys.exc_info captured in the context block
  368. """
  369. os.chdir(self._old_cwd.pop())
  370. @pytest.fixture
  371. def tmp_working_dir(tmp_path):
  372. """Create a temporary directory and chdir to it.
  373. After the test executes, chdir back to the original working directory.
  374. Args:
  375. tmp_path: pytest tmp_path fixture creates per-test temp dir
  376. Yields:
  377. subdirectory of tmp_path which is now the current working directory.
  378. """
  379. working_dir = tmp_path / "working_dir"
  380. working_dir.mkdir()
  381. with chdir(working_dir):
  382. yield working_dir
  383. @pytest.fixture
  384. def mutable_state():
  385. """Create a Test state containing mutable types.
  386. Returns:
  387. A state object.
  388. """
  389. class MutableTestState(rx.State):
  390. """A test state."""
  391. array: List[Union[str, List, Dict[str, str]]] = [
  392. "value",
  393. [1, 2, 3],
  394. {"key": "value"},
  395. ]
  396. hashmap: Dict[str, Union[List, str, Dict[str, str]]] = {
  397. "key": ["list", "of", "values"],
  398. "another_key": "another_value",
  399. "third_key": {"key": "value"},
  400. }
  401. def reassign_mutables(self):
  402. self.array = ["modified_value", [1, 2, 3], {"mod_key": "mod_value"}]
  403. self.hashmap = {
  404. "mod_key": ["list", "of", "values"],
  405. "mod_another_key": "another_value",
  406. "mod_third_key": {"key": "value"},
  407. }
  408. return MutableTestState()