test_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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, constants
  8. from pynecone.utils import build, format, imports, prerequisites, types
  9. from pynecone.vars import Var
  10. V055 = version.parse("0.5.5")
  11. V059 = version.parse("0.5.9")
  12. V056 = version.parse("0.5.6")
  13. V062 = version.parse("0.6.2")
  14. @pytest.mark.parametrize(
  15. "input,output",
  16. [
  17. ("", ""),
  18. ("hello", "hello"),
  19. ("Hello", "hello"),
  20. ("camelCase", "camel_case"),
  21. ("camelTwoHumps", "camel_two_humps"),
  22. ("_start_with_underscore", "_start_with_underscore"),
  23. ("__start_with_double_underscore", "__start_with_double_underscore"),
  24. ],
  25. )
  26. def test_to_snake_case(input: str, output: str):
  27. """Test converting strings to snake case.
  28. Args:
  29. input: The input string.
  30. output: The expected output string.
  31. """
  32. assert format.to_snake_case(input) == output
  33. @pytest.mark.parametrize(
  34. "input,output",
  35. [
  36. ("", ""),
  37. ("hello", "hello"),
  38. ("Hello", "Hello"),
  39. ("snake_case", "snakeCase"),
  40. ("snake_case_two", "snakeCaseTwo"),
  41. ],
  42. )
  43. def test_to_camel_case(input: str, output: str):
  44. """Test converting strings to camel case.
  45. Args:
  46. input: The input string.
  47. output: The expected output string.
  48. """
  49. assert format.to_camel_case(input) == output
  50. @pytest.mark.parametrize(
  51. "input,output",
  52. [
  53. ("", ""),
  54. ("hello", "Hello"),
  55. ("Hello", "Hello"),
  56. ("snake_case", "SnakeCase"),
  57. ("snake_case_two", "SnakeCaseTwo"),
  58. ],
  59. )
  60. def test_to_title_case(input: str, output: str):
  61. """Test converting strings to title case.
  62. Args:
  63. input: The input string.
  64. output: The expected output string.
  65. """
  66. assert format.to_title_case(input) == output
  67. @pytest.mark.parametrize(
  68. "input,output",
  69. [
  70. ("{", "}"),
  71. ("(", ")"),
  72. ("[", "]"),
  73. ("<", ">"),
  74. ('"', '"'),
  75. ("'", "'"),
  76. ],
  77. )
  78. def test_get_close_char(input: str, output: str):
  79. """Test getting the close character for a given open character.
  80. Args:
  81. input: The open character.
  82. output: The expected close character.
  83. """
  84. assert format.get_close_char(input) == output
  85. @pytest.mark.parametrize(
  86. "text,open,expected",
  87. [
  88. ("", "{", False),
  89. ("{wrap}", "{", True),
  90. ("{wrap", "{", False),
  91. ("{wrap}", "(", False),
  92. ("(wrap)", "(", True),
  93. ],
  94. )
  95. def test_is_wrapped(text: str, open: str, expected: bool):
  96. """Test checking if a string is wrapped in the given open and close characters.
  97. Args:
  98. text: The text to check.
  99. open: The open character.
  100. expected: Whether the text is wrapped.
  101. """
  102. assert format.is_wrapped(text, open) == expected
  103. @pytest.mark.parametrize(
  104. "text,open,check_first,num,expected",
  105. [
  106. ("", "{", True, 1, "{}"),
  107. ("wrap", "{", True, 1, "{wrap}"),
  108. ("wrap", "(", True, 1, "(wrap)"),
  109. ("wrap", "(", True, 2, "((wrap))"),
  110. ("(wrap)", "(", True, 1, "(wrap)"),
  111. ("{wrap}", "{", True, 2, "{wrap}"),
  112. ("(wrap)", "{", True, 1, "{(wrap)}"),
  113. ("(wrap)", "(", False, 1, "((wrap))"),
  114. ],
  115. )
  116. def test_wrap(text: str, open: str, expected: str, check_first: bool, num: int):
  117. """Test wrapping a string.
  118. Args:
  119. text: The text to wrap.
  120. open: The open character.
  121. expected: The expected output string.
  122. check_first: Whether to check if the text is already wrapped.
  123. num: The number of times to wrap the text.
  124. """
  125. assert format.wrap(text, open, check_first=check_first, num=num) == expected
  126. @pytest.mark.parametrize(
  127. "text,indent_level,expected",
  128. [
  129. ("", 2, ""),
  130. ("hello", 2, "hello"),
  131. ("hello\nworld", 2, " hello\n world\n"),
  132. ("hello\nworld", 4, " hello\n world\n"),
  133. (" hello\n world", 2, " hello\n world\n"),
  134. ],
  135. )
  136. def test_indent(text: str, indent_level: int, expected: str, windows_platform: bool):
  137. """Test indenting a string.
  138. Args:
  139. text: The text to indent.
  140. indent_level: The number of spaces to indent by.
  141. expected: The expected output string.
  142. windows_platform: Whether the system is windows.
  143. """
  144. assert format.indent(text, indent_level) == (
  145. expected.replace("\n", "\r\n") if windows_platform else expected
  146. )
  147. @pytest.mark.parametrize(
  148. "condition,true_value,false_value,expected",
  149. [
  150. ("cond", "<C1>", '""', '{isTrue(cond) ? <C1> : ""}'),
  151. ("cond", "<C1>", "<C2>", "{isTrue(cond) ? <C1> : <C2>}"),
  152. ],
  153. )
  154. def test_format_cond(condition: str, true_value: str, false_value: str, expected: str):
  155. """Test formatting a cond.
  156. Args:
  157. condition: The condition to check.
  158. true_value: The value to return if the condition is true.
  159. false_value: The value to return if the condition is false.
  160. expected: The expected output string.
  161. """
  162. assert format.format_cond(condition, true_value, false_value) == expected
  163. def test_merge_imports():
  164. """Test that imports are merged correctly."""
  165. d1 = {"react": {"Component"}}
  166. d2 = {"react": {"Component"}, "react-dom": {"render"}}
  167. d = imports.merge_imports(d1, d2)
  168. assert set(d.keys()) == {"react", "react-dom"}
  169. assert set(d["react"]) == {"Component"}
  170. assert set(d["react-dom"]) == {"render"}
  171. @pytest.mark.parametrize(
  172. "cls,expected",
  173. [
  174. (str, False),
  175. (int, False),
  176. (float, False),
  177. (bool, False),
  178. (List, True),
  179. (List[int], True),
  180. ],
  181. )
  182. def test_is_generic_alias(cls: type, expected: bool):
  183. """Test checking if a class is a GenericAlias.
  184. Args:
  185. cls: The class to check.
  186. expected: Whether the class is a GenericAlias.
  187. """
  188. assert types.is_generic_alias(cls) == expected
  189. @pytest.mark.parametrize(
  190. "route,expected",
  191. [
  192. ("", "index"),
  193. ("/", "index"),
  194. ("custom-route", "custom-route"),
  195. ("custom-route/", "custom-route"),
  196. ("/custom-route", "custom-route"),
  197. ],
  198. )
  199. def test_format_route(route: str, expected: bool):
  200. """Test formatting a route.
  201. Args:
  202. route: The route to format.
  203. expected: The expected formatted route.
  204. """
  205. assert format.format_route(route) == expected
  206. @pytest.mark.parametrize(
  207. "bun_version,is_valid, prompt_input",
  208. [
  209. (V055, False, "yes"),
  210. (V059, True, None),
  211. (V062, False, "yes"),
  212. ],
  213. )
  214. def test_bun_validate_and_install(mocker, bun_version, is_valid, prompt_input):
  215. """Test that the bun version on host system is validated properly. Also test that
  216. the required bun version is installed should the user opt for it.
  217. Args:
  218. mocker: Pytest mocker object.
  219. bun_version: The bun version.
  220. is_valid: Whether bun version is valid for running pynecone.
  221. prompt_input: The input from user on whether to install bun.
  222. """
  223. mocker.patch(
  224. "pynecone.utils.prerequisites.get_bun_version", return_value=bun_version
  225. )
  226. mocker.patch("pynecone.utils.prerequisites.console.ask", return_value=prompt_input)
  227. bun_install = mocker.patch("pynecone.utils.prerequisites.install_bun")
  228. remove_existing_bun_installation = mocker.patch(
  229. "pynecone.utils.prerequisites.remove_existing_bun_installation"
  230. )
  231. prerequisites.validate_and_install_bun()
  232. if not is_valid:
  233. remove_existing_bun_installation.assert_called_once()
  234. bun_install.assert_called_once()
  235. def test_bun_validation_exception(mocker):
  236. """Test that an exception is thrown and program exists when user selects no when asked
  237. whether to install bun or not.
  238. Args:
  239. mocker: Pytest mocker.
  240. """
  241. mocker.patch("pynecone.utils.prerequisites.get_bun_version", return_value=V056)
  242. mocker.patch("pynecone.utils.prerequisites.console.ask", return_value="no")
  243. with pytest.raises(RuntimeError):
  244. prerequisites.validate_and_install_bun()
  245. def test_remove_existing_bun_installation(mocker, tmp_path):
  246. """Test that existing bun installation is removed.
  247. Args:
  248. mocker: Pytest mocker.
  249. tmp_path: test path.
  250. """
  251. bun_location = tmp_path / ".bun"
  252. bun_location.mkdir()
  253. mocker.patch(
  254. "pynecone.utils.prerequisites.get_package_manager",
  255. return_value=str(bun_location),
  256. )
  257. mocker.patch(
  258. "pynecone.utils.prerequisites.os.path.expandvars",
  259. return_value=str(bun_location),
  260. )
  261. prerequisites.remove_existing_bun_installation()
  262. assert not bun_location.exists()
  263. def test_setup_frontend(tmp_path, mocker):
  264. """Test checking if assets content have been
  265. copied into the .web/public folder.
  266. Args:
  267. tmp_path: root path of test case data directory
  268. mocker: mocker object to allow mocking
  269. """
  270. web_folder = tmp_path / ".web"
  271. web_public_folder = web_folder / "public"
  272. assets = tmp_path / "assets"
  273. assets.mkdir()
  274. (assets / "favicon.ico").touch()
  275. assert str(web_folder) == prerequisites.create_web_directory(tmp_path)
  276. mocker.patch("pynecone.utils.prerequisites.install_frontend_packages")
  277. mocker.patch("pynecone.utils.build.set_environment_variables")
  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 / constants.CONFIG_FILE).read_text(), eval_globals)
  358. config = eval_globals["config"]
  359. assert config.app_name == app_name
  360. assert config.db_url == constants.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
  400. @pytest.mark.parametrize("gitignore_exists", [True, False])
  401. def test_initialize_non_existent_gitignore(tmp_path, mocker, gitignore_exists):
  402. """Test that the generated .gitignore_file file on pc init contains the correct file
  403. names with correct formatting.
  404. Args:
  405. tmp_path: The root test path.
  406. mocker: The mock object.
  407. gitignore_exists: Whether a gitignore file exists in the root dir.
  408. """
  409. sep = os.sep
  410. expected = constants.DEFAULT_GITIGNORE.copy()
  411. mocker.patch("pynecone.constants.GITIGNORE_FILE", tmp_path / ".gitignore")
  412. gitignore_file = tmp_path / ".gitignore"
  413. if gitignore_exists:
  414. gitignore_file.touch()
  415. gitignore_file.write_text(
  416. """
  417. pynecone.db
  418. __pycache__/
  419. """
  420. )
  421. prerequisites.initialize_gitignore()
  422. assert gitignore_file.exists()
  423. file_content = gitignore_file.open().read()
  424. file_content.replace(f"{sep}{sep}", sep)
  425. assert set(file_content.split()) == expected