test_utils.py 14 KB

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