test_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import os
  2. import typing
  3. from pathlib import Path
  4. from typing import Any, List, Union
  5. import pytest
  6. from packaging import version
  7. from pynecone import Env
  8. from pynecone.constants import CONFIG_FILE, DB_URL
  9. from pynecone.utils import build, format, imports, prerequisites, types
  10. from pynecone.vars import Var
  11. V055 = version.parse("0.5.5")
  12. V059 = version.parse("0.5.9")
  13. V056 = version.parse("0.5.6")
  14. V0510 = version.parse("0.5.10")
  15. @pytest.mark.parametrize(
  16. "input,output",
  17. [
  18. ("", ""),
  19. ("hello", "hello"),
  20. ("Hello", "hello"),
  21. ("camelCase", "camel_case"),
  22. ("camelTwoHumps", "camel_two_humps"),
  23. ("_start_with_underscore", "_start_with_underscore"),
  24. ("__start_with_double_underscore", "__start_with_double_underscore"),
  25. ],
  26. )
  27. def test_to_snake_case(input: str, output: str):
  28. """Test converting strings to snake case.
  29. Args:
  30. input: The input string.
  31. output: The expected output string.
  32. """
  33. assert format.to_snake_case(input) == output
  34. @pytest.mark.parametrize(
  35. "input,output",
  36. [
  37. ("", ""),
  38. ("hello", "hello"),
  39. ("Hello", "Hello"),
  40. ("snake_case", "snakeCase"),
  41. ("snake_case_two", "snakeCaseTwo"),
  42. ],
  43. )
  44. def test_to_camel_case(input: str, output: str):
  45. """Test converting strings to camel case.
  46. Args:
  47. input: The input string.
  48. output: The expected output string.
  49. """
  50. assert format.to_camel_case(input) == output
  51. @pytest.mark.parametrize(
  52. "input,output",
  53. [
  54. ("", ""),
  55. ("hello", "Hello"),
  56. ("Hello", "Hello"),
  57. ("snake_case", "SnakeCase"),
  58. ("snake_case_two", "SnakeCaseTwo"),
  59. ],
  60. )
  61. def test_to_title_case(input: str, output: str):
  62. """Test converting strings to title case.
  63. Args:
  64. input: The input string.
  65. output: The expected output string.
  66. """
  67. assert format.to_title_case(input) == output
  68. @pytest.mark.parametrize(
  69. "input,output",
  70. [
  71. ("{", "}"),
  72. ("(", ")"),
  73. ("[", "]"),
  74. ("<", ">"),
  75. ('"', '"'),
  76. ("'", "'"),
  77. ],
  78. )
  79. def test_get_close_char(input: str, output: str):
  80. """Test getting the close character for a given open character.
  81. Args:
  82. input: The open character.
  83. output: The expected close character.
  84. """
  85. assert format.get_close_char(input) == output
  86. @pytest.mark.parametrize(
  87. "text,open,expected",
  88. [
  89. ("", "{", False),
  90. ("{wrap}", "{", True),
  91. ("{wrap", "{", False),
  92. ("{wrap}", "(", False),
  93. ("(wrap)", "(", True),
  94. ],
  95. )
  96. def test_is_wrapped(text: str, open: str, expected: bool):
  97. """Test checking if a string is wrapped in the given open and close characters.
  98. Args:
  99. text: The text to check.
  100. open: The open character.
  101. expected: Whether the text is wrapped.
  102. """
  103. assert format.is_wrapped(text, open) == expected
  104. @pytest.mark.parametrize(
  105. "text,open,check_first,num,expected",
  106. [
  107. ("", "{", True, 1, "{}"),
  108. ("wrap", "{", True, 1, "{wrap}"),
  109. ("wrap", "(", True, 1, "(wrap)"),
  110. ("wrap", "(", True, 2, "((wrap))"),
  111. ("(wrap)", "(", True, 1, "(wrap)"),
  112. ("{wrap}", "{", True, 2, "{wrap}"),
  113. ("(wrap)", "{", True, 1, "{(wrap)}"),
  114. ("(wrap)", "(", False, 1, "((wrap))"),
  115. ],
  116. )
  117. def test_wrap(text: str, open: str, expected: str, check_first: bool, num: int):
  118. """Test wrapping a string.
  119. Args:
  120. text: The text to wrap.
  121. open: The open character.
  122. expected: The expected output string.
  123. check_first: Whether to check if the text is already wrapped.
  124. num: The number of times to wrap the text.
  125. """
  126. assert format.wrap(text, open, check_first=check_first, num=num) == expected
  127. @pytest.mark.parametrize(
  128. "text,indent_level,expected",
  129. [
  130. ("", 2, ""),
  131. ("hello", 2, "hello"),
  132. ("hello\nworld", 2, " hello\n world\n"),
  133. ("hello\nworld", 4, " hello\n world\n"),
  134. (" hello\n world", 2, " hello\n world\n"),
  135. ],
  136. )
  137. def test_indent(text: str, indent_level: int, expected: str, windows_platform: bool):
  138. """Test indenting a string.
  139. Args:
  140. text: The text to indent.
  141. indent_level: The number of spaces to indent by.
  142. expected: The expected output string.
  143. windows_platform: Whether the system is windows.
  144. """
  145. assert format.indent(text, indent_level) == (
  146. expected.replace("\n", "\r\n") if windows_platform else expected
  147. )
  148. @pytest.mark.parametrize(
  149. "condition,true_value,false_value,expected",
  150. [
  151. ("cond", "<C1>", '""', '{isTrue(cond) ? <C1> : ""}'),
  152. ("cond", "<C1>", "<C2>", "{isTrue(cond) ? <C1> : <C2>}"),
  153. ],
  154. )
  155. def test_format_cond(condition: str, true_value: str, false_value: str, expected: str):
  156. """Test formatting a cond.
  157. Args:
  158. condition: The condition to check.
  159. true_value: The value to return if the condition is true.
  160. false_value: The value to return if the condition is false.
  161. expected: The expected output string.
  162. """
  163. assert format.format_cond(condition, true_value, false_value) == expected
  164. def test_merge_imports():
  165. """Test that imports are merged correctly."""
  166. d1 = {"react": {"Component"}}
  167. d2 = {"react": {"Component"}, "react-dom": {"render"}}
  168. d = imports.merge_imports(d1, d2)
  169. assert set(d.keys()) == {"react", "react-dom"}
  170. assert set(d["react"]) == {"Component"}
  171. assert set(d["react-dom"]) == {"render"}
  172. @pytest.mark.parametrize(
  173. "cls,expected",
  174. [
  175. (str, False),
  176. (int, False),
  177. (float, False),
  178. (bool, False),
  179. (List, True),
  180. (List[int], True),
  181. ],
  182. )
  183. def test_is_generic_alias(cls: type, expected: bool):
  184. """Test checking if a class is a GenericAlias.
  185. Args:
  186. cls: The class to check.
  187. expected: Whether the class is a GenericAlias.
  188. """
  189. assert types.is_generic_alias(cls) == expected
  190. @pytest.mark.parametrize(
  191. "route,expected",
  192. [
  193. ("", "index"),
  194. ("/", "index"),
  195. ("custom-route", "custom-route"),
  196. ("custom-route/", "custom-route"),
  197. ("/custom-route", "custom-route"),
  198. ],
  199. )
  200. def test_format_route(route: str, expected: bool):
  201. """Test formatting a route.
  202. Args:
  203. route: The route to format.
  204. expected: The expected formatted route.
  205. """
  206. assert format.format_route(route) == expected
  207. @pytest.mark.parametrize(
  208. "bun_version,is_valid, prompt_input",
  209. [
  210. (V055, False, "yes"),
  211. (V059, True, None),
  212. (V0510, False, "yes"),
  213. ],
  214. )
  215. def test_bun_validate_and_install(mocker, bun_version, is_valid, prompt_input):
  216. """Test that the bun version on host system is validated properly. Also test that
  217. the required bun version is installed should the user opt for it.
  218. Args:
  219. mocker: Pytest mocker object.
  220. bun_version: The bun version.
  221. is_valid: Whether bun version is valid for running pynecone.
  222. prompt_input: The input from user on whether to install bun.
  223. """
  224. mocker.patch(
  225. "pynecone.utils.prerequisites.get_bun_version", return_value=bun_version
  226. )
  227. mocker.patch("pynecone.utils.prerequisites.console.ask", return_value=prompt_input)
  228. bun_install = mocker.patch("pynecone.utils.prerequisites.install_bun")
  229. remove_existing_bun_installation = mocker.patch(
  230. "pynecone.utils.prerequisites.remove_existing_bun_installation"
  231. )
  232. prerequisites.validate_and_install_bun()
  233. if not is_valid:
  234. remove_existing_bun_installation.assert_called_once()
  235. bun_install.assert_called_once()
  236. def test_bun_validation_exception(mocker):
  237. """Test that an exception is thrown and program exists when user selects no when asked
  238. whether to install bun or not.
  239. Args:
  240. mocker: Pytest mocker.
  241. """
  242. mocker.patch("pynecone.utils.prerequisites.get_bun_version", return_value=V056)
  243. mocker.patch("pynecone.utils.prerequisites.console.ask", return_value="no")
  244. with pytest.raises(RuntimeError):
  245. prerequisites.validate_and_install_bun()
  246. def test_remove_existing_bun_installation(mocker, tmp_path):
  247. """Test that existing bun installation is removed.
  248. Args:
  249. mocker: Pytest mocker.
  250. tmp_path: test path.
  251. """
  252. bun_location = tmp_path / ".bun"
  253. bun_location.mkdir()
  254. mocker.patch(
  255. "pynecone.utils.prerequisites.get_package_manager",
  256. return_value=str(bun_location),
  257. )
  258. mocker.patch(
  259. "pynecone.utils.prerequisites.os.path.expandvars",
  260. return_value=str(bun_location),
  261. )
  262. prerequisites.remove_existing_bun_installation()
  263. assert not bun_location.exists()
  264. def test_setup_frontend(tmp_path, mocker):
  265. """Test checking if assets content have been
  266. copied into the .web/public folder.
  267. Args:
  268. tmp_path: root path of test case data directory
  269. mocker: mocker object to allow mocking
  270. """
  271. web_folder = tmp_path / ".web"
  272. web_public_folder = web_folder / "public"
  273. assets = tmp_path / "assets"
  274. assets.mkdir()
  275. (assets / "favicon.ico").touch()
  276. assert str(web_folder) == prerequisites.create_web_directory(tmp_path)
  277. mocker.patch("pynecone.utils.prerequisites.install_frontend_packages")
  278. build.setup_frontend(tmp_path, disable_telemetry=False)
  279. assert web_folder.exists()
  280. assert web_public_folder.exists()
  281. assert (web_public_folder / "favicon.ico").exists()
  282. @pytest.mark.parametrize(
  283. "input, output",
  284. [
  285. ("_hidden", True),
  286. ("not_hidden", False),
  287. ("__dundermethod__", False),
  288. ],
  289. )
  290. def test_is_backend_variable(input, output):
  291. assert types.is_backend_variable(input) == output
  292. @pytest.mark.parametrize(
  293. "cls, cls_check, expected",
  294. [
  295. (int, int, True),
  296. (int, float, False),
  297. (int, Union[int, float], True),
  298. (float, Union[int, float], True),
  299. (str, Union[int, float], False),
  300. (List[int], List[int], True),
  301. (List[int], List[float], True),
  302. (Union[int, float], Union[int, float], False),
  303. (Union[int, Var[int]], Var[int], False),
  304. (int, Any, True),
  305. (Any, Any, True),
  306. (Union[int, float], Any, True),
  307. ],
  308. )
  309. def test_issubclass(cls: type, cls_check: type, expected: bool):
  310. assert types._issubclass(cls, cls_check) == expected
  311. @pytest.mark.parametrize(
  312. "app_name,expected_config_name",
  313. [
  314. ("appname", "AppnameConfig"),
  315. ("app_name", "AppnameConfig"),
  316. ("app-name", "AppnameConfig"),
  317. ("appname2.io", "AppnameioConfig"),
  318. ],
  319. )
  320. def test_create_config(app_name, expected_config_name, mocker):
  321. """Test templates.PCCONFIG is formatted with correct app name and config class name.
  322. Args:
  323. app_name: App name.
  324. expected_config_name: Expected config name.
  325. mocker: Mocker object.
  326. """
  327. mocker.patch("builtins.open")
  328. tmpl_mock = mocker.patch("pynecone.compiler.templates.PCCONFIG")
  329. prerequisites.create_config(app_name)
  330. tmpl_mock.render.assert_called_with(
  331. app_name=app_name, config_name=expected_config_name
  332. )
  333. @pytest.fixture
  334. def tmp_working_dir(tmp_path):
  335. """Create a temporary directory and chdir to it.
  336. After the test executes, chdir back to the original working directory.
  337. Args:
  338. tmp_path: pytest tmp_path fixture creates per-test temp dir
  339. Yields:
  340. subdirectory of tmp_path which is now the current working directory.
  341. """
  342. old_pwd = Path(".").resolve()
  343. working_dir = tmp_path / "working_dir"
  344. working_dir.mkdir()
  345. os.chdir(working_dir)
  346. yield working_dir
  347. os.chdir(old_pwd)
  348. def test_create_config_e2e(tmp_working_dir):
  349. """Create a new config file, exec it, and make assertions about the config.
  350. Args:
  351. tmp_working_dir: a new directory that is the current working directory
  352. for the duration of the test.
  353. """
  354. app_name = "e2e"
  355. prerequisites.create_config(app_name)
  356. eval_globals = {}
  357. exec((tmp_working_dir / CONFIG_FILE).read_text(), eval_globals)
  358. config = eval_globals["config"]
  359. assert config.app_name == app_name
  360. assert config.db_url == DB_URL
  361. assert config.env == Env.DEV
  362. @pytest.mark.parametrize(
  363. "name,expected",
  364. [
  365. ("input1", "ref_input1"),
  366. ("input 1", "ref_input_1"),
  367. ("input-1", "ref_input_1"),
  368. ("input_1", "ref_input_1"),
  369. ("a long test?1! name", "ref_a_long_test_1_name"),
  370. ],
  371. )
  372. def test_format_ref(name, expected):
  373. """Test formatting a ref.
  374. Args:
  375. name: The name to format.
  376. expected: The expected formatted name.
  377. """
  378. assert format.format_ref(name) == expected
  379. class DataFrame:
  380. """A Fake pandas DataFrame class."""
  381. pass
  382. @pytest.mark.parametrize(
  383. "class_type,expected",
  384. [
  385. (list, False),
  386. (int, False),
  387. (dict, False),
  388. (DataFrame, True),
  389. (typing.Any, False),
  390. (typing.List, False),
  391. ],
  392. )
  393. def test_is_dataframe(class_type, expected):
  394. """Test that a type name is DataFrame.
  395. Args:
  396. class_type: the class type.
  397. expected: whether type name is DataFrame
  398. """
  399. assert types.is_dataframe(class_type) == expected