test_hosting.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import json
  2. from unittest.mock import Mock, mock_open
  3. import httpx
  4. import pytest
  5. from reflex import constants
  6. from reflex.utils import hosting
  7. def test_get_existing_access_token_and_no_invitation_code(mocker):
  8. # Config file has token only
  9. mock_hosting_config = {"access_token": "ejJhfake_token"}
  10. mocker.patch("builtins.open", mock_open(read_data=json.dumps(mock_hosting_config)))
  11. token, code = hosting.get_existing_access_token()
  12. assert token == mock_hosting_config["access_token"]
  13. assert code == ""
  14. def test_get_existing_access_token_and_invitation_code(mocker):
  15. # Config file has both access token and the invitation code
  16. mock_hosting_config = {"access_token": "ejJhfake_token", "code": "fake_code"}
  17. mocker.patch("builtins.open", mock_open(read_data=json.dumps(mock_hosting_config)))
  18. token, code = hosting.get_existing_access_token()
  19. assert token == mock_hosting_config["access_token"]
  20. assert code == mock_hosting_config["code"]
  21. def test_no_existing_access_token(mocker):
  22. # Config file does not have access token
  23. mocker.patch(
  24. "builtins.open",
  25. mock_open(read_data=json.dumps({"no-token": "here", "no-code": "here"})),
  26. )
  27. access_token, invitation_code = hosting.get_existing_access_token()
  28. assert access_token == ""
  29. assert invitation_code == ""
  30. def test_no_config_file(mocker):
  31. # Config file not exist
  32. mocker.patch("builtins.open", side_effect=FileNotFoundError)
  33. access_token, invitation_code = hosting.get_existing_access_token()
  34. assert access_token == ""
  35. assert invitation_code == ""
  36. def test_empty_config_file(mocker):
  37. # Config file is empty
  38. mocker.patch("builtins.open", mock_open(read_data=""))
  39. access_token, invitation_code = hosting.get_existing_access_token()
  40. assert access_token == ""
  41. assert invitation_code == ""
  42. def test_invalid_json_config_file(mocker):
  43. # Config file content is not valid json
  44. mocker.patch("builtins.open", mock_open(read_data="im not json content"))
  45. access_token, invitation_code = hosting.get_existing_access_token()
  46. assert access_token == ""
  47. assert invitation_code == ""
  48. def test_validate_token_success(mocker):
  49. # Valid token passes without raising any exceptions
  50. mocker.patch("httpx.post")
  51. hosting.validate_token("fake_token")
  52. def test_invalid_token_access_denied(mocker):
  53. # Invalid token raises an exception
  54. mocker.patch("httpx.post", return_value=httpx.Response(403))
  55. with pytest.raises(ValueError) as ex:
  56. hosting.validate_token("invalid_token")
  57. assert ex.value == "access denied"
  58. def test_unable_to_validate_token(mocker):
  59. # Unable to validate token raises an exception, but not access denied
  60. mocker.patch("httpx.post", return_value=httpx.Response(500))
  61. with pytest.raises(Exception):
  62. hosting.validate_token("invalid_token")
  63. def test_delete_access_token_from_config(mocker):
  64. config_json = {
  65. "access_token": "fake_token",
  66. "code": "fake_code",
  67. "future": "some value",
  68. }
  69. mock_f = mock_open(read_data=json.dumps(config_json))
  70. mocker.patch("builtins.open", mock_f)
  71. mocker.patch("os.path.exists", return_value=True)
  72. mock_json_dump = mocker.patch("json.dump")
  73. hosting.delete_token_from_config()
  74. config_json.pop("access_token")
  75. assert mock_json_dump.call_args[0][0] == config_json
  76. def test_save_access_token_and_invitation_code_to_config(mocker):
  77. access_token = "fake_token"
  78. invitation_code = "fake_code"
  79. expected_config_json = {
  80. "access_token": access_token,
  81. "code": invitation_code,
  82. }
  83. mocker.patch("builtins.open")
  84. mock_json_dump = mocker.patch("json.dump")
  85. hosting.save_token_to_config(access_token, invitation_code)
  86. assert mock_json_dump.call_args[0][0] == expected_config_json
  87. def test_save_access_code_but_none_invitation_code_to_config(mocker):
  88. access_token = "fake_token"
  89. invitation_code = None
  90. expected_config_json = {
  91. "access_token": access_token,
  92. "code": invitation_code,
  93. }
  94. mocker.patch("builtins.open")
  95. mock_json_dump = mocker.patch("json.dump")
  96. hosting.save_token_to_config(access_token, invitation_code)
  97. expected_config_json.pop("code")
  98. assert mock_json_dump.call_args[0][0] == expected_config_json
  99. def test_authenticated_token_success(mocker):
  100. access_token = "fake_token"
  101. invitation_code = "fake_code"
  102. mocker.patch(
  103. "reflex.utils.hosting.get_existing_access_token",
  104. return_value=(access_token, invitation_code),
  105. )
  106. mocker.patch("reflex.utils.hosting.validate_token_with_retries", return_value=True)
  107. assert hosting.authenticated_token() == (access_token, invitation_code)
  108. def test_no_authenticated_token(mocker):
  109. mocker.patch(
  110. "reflex.utils.hosting.get_existing_access_token",
  111. return_value=("", "code-does-not-matter"),
  112. )
  113. assert hosting.authenticated_token()[0] == ""
  114. def test_maybe_authenticated_token_is_invalid(mocker):
  115. mocker.patch(
  116. "reflex.utils.hosting.get_existing_access_token",
  117. return_value=("invalid_token", "fake_code"),
  118. )
  119. mocker.patch("reflex.utils.hosting.validate_token_with_retries", return_value=False)
  120. assert hosting.authenticated_token()[0] == ""
  121. def test_prepare_deploy_not_authenticated(mocker):
  122. mocker.patch("reflex.utils.hosting.requires_authenticated", return_value=None)
  123. with pytest.raises(Exception) as ex:
  124. hosting.prepare_deploy("fake-app")
  125. assert ex.value == "Not authenticated"
  126. def test_server_unable_to_prepare_deploy(mocker):
  127. mocker.patch(
  128. "reflex.utils.hosting.requires_authenticated", return_value="fake_token"
  129. )
  130. mocker.patch("httpx.post", return_value=httpx.Response(500))
  131. with pytest.raises(Exception):
  132. hosting.prepare_deploy("fake-app")
  133. def test_prepare_deploy_success(mocker):
  134. mocker.patch(
  135. "reflex.utils.hosting.requires_authenticated", return_value="fake_token"
  136. )
  137. mocker.patch(
  138. "httpx.post",
  139. return_value=Mock(
  140. status_code=200,
  141. json=lambda: dict(
  142. app_prefix="fake-app-prefix",
  143. reply=dict(
  144. key="fake-key",
  145. api_url="fake-api-url",
  146. deploy_url="fake-deploy-url",
  147. ),
  148. suggestion=None,
  149. existing=[],
  150. ),
  151. ),
  152. )
  153. # server returns valid response (format is checked by pydantic model validation)
  154. hosting.prepare_deploy("fake-app")
  155. def test_deploy(mocker):
  156. mocker.patch(
  157. "reflex.utils.hosting.requires_access_token", return_value="fake_token"
  158. )
  159. mocker.patch("builtins.open")
  160. mocker.patch(
  161. "httpx.post",
  162. return_value=Mock(
  163. status_code=200,
  164. json=lambda: dict(
  165. frontend_url="https://fake-url", backend_url="https://fake-url"
  166. ),
  167. ),
  168. )
  169. hosting.deploy(
  170. frontend_file_name="fake-frontend-path",
  171. backend_file_name="fake-backend-path",
  172. export_dir="fake-export-dir",
  173. key="fake-key",
  174. app_name="fake-app-name",
  175. regions=["fake-region"],
  176. app_prefix="fake-app-prefix",
  177. )
  178. def test_validate_token_with_retries_failed(mocker):
  179. mock_validate_token = mocker.patch(
  180. "reflex.utils.hosting.validate_token", side_effect=Exception
  181. )
  182. mock_delete_token = mocker.patch("reflex.utils.hosting.delete_token_from_config")
  183. mocker.patch("time.sleep")
  184. assert hosting.validate_token_with_retries("fake-token") is False
  185. assert mock_validate_token.call_count == constants.Hosting.WEB_AUTH_RETRIES
  186. assert mock_delete_token.call_count == 0
  187. def test_validate_token_with_retries_access_denied(mocker):
  188. mock_validate_token = mocker.patch(
  189. "reflex.utils.hosting.validate_token", side_effect=ValueError
  190. )
  191. mock_delete_token = mocker.patch("reflex.utils.hosting.delete_token_from_config")
  192. mocker.patch("time.sleep")
  193. assert hosting.validate_token_with_retries("fake-token") is False
  194. assert mock_validate_token.call_count == 1
  195. assert mock_delete_token.call_count == 1
  196. def test_validate_token_with_retries_success(mocker):
  197. validate_token_returns = [Exception, Exception, None]
  198. mock_validate_token = mocker.patch(
  199. "reflex.utils.hosting.validate_token", side_effect=validate_token_returns
  200. )
  201. mock_delete_token = mocker.patch("reflex.utils.hosting.delete_token_from_config")
  202. mocker.patch("time.sleep")
  203. assert hosting.validate_token_with_retries("fake-token") is True
  204. assert mock_validate_token.call_count == len(validate_token_returns)
  205. assert mock_delete_token.call_count == 0
  206. @pytest.mark.parametrize(
  207. "prepare_response, expected",
  208. [
  209. (
  210. hosting.DeploymentPrepareResponse(
  211. app_prefix="fake-prefix",
  212. reply=hosting.DeploymentPrepInfo(
  213. key="key1", api_url="url11", deploy_url="url12"
  214. ),
  215. existing=None,
  216. suggestion=None,
  217. ),
  218. ("key1", "url11", "url12"),
  219. ),
  220. (
  221. hosting.DeploymentPrepareResponse(
  222. app_prefix="fake-prefix",
  223. reply=None,
  224. existing=[
  225. hosting.DeploymentPrepInfo(
  226. key="key21", api_url="url211", deploy_url="url212"
  227. ),
  228. hosting.DeploymentPrepInfo(
  229. key="key22", api_url="url21", deploy_url="url22"
  230. ),
  231. ],
  232. suggestion=None,
  233. ),
  234. ("key21", "url211", "url212"),
  235. ),
  236. (
  237. hosting.DeploymentPrepareResponse(
  238. app_prefix="fake-prefix",
  239. reply=None,
  240. existing=None,
  241. suggestion=hosting.DeploymentPrepInfo(
  242. key="key31", api_url="url31", deploy_url="url31"
  243. ),
  244. ),
  245. ("key31", "url31", "url31"),
  246. ),
  247. ],
  248. )
  249. def test_interactive_get_deployment_key_user_accepts_defaults(
  250. mocker, prepare_response, expected
  251. ):
  252. mocker.patch("reflex.utils.console.ask", side_effect=[""])
  253. assert (
  254. hosting.interactive_get_deployment_key_from_user_input(
  255. prepare_response, "fake-app"
  256. )
  257. == expected
  258. )
  259. def test_interactive_get_deployment_key_user_input_accepted(mocker):
  260. mocker.patch("reflex.utils.console.ask", side_effect=["my-site"])
  261. mocker.patch(
  262. "reflex.utils.hosting.prepare_deploy",
  263. return_value=hosting.DeploymentPrepareResponse(
  264. app_prefix="fake-prefix",
  265. reply=hosting.DeploymentPrepInfo(
  266. key="my-site", api_url="url211", deploy_url="url212"
  267. ),
  268. ),
  269. )
  270. assert hosting.interactive_get_deployment_key_from_user_input(
  271. hosting.DeploymentPrepareResponse(
  272. app_prefix="fake-prefix",
  273. reply=None,
  274. existing=None,
  275. suggestion=hosting.DeploymentPrepInfo(
  276. key="rejected-key", api_url="rejected-url", deploy_url="rejected-url"
  277. ),
  278. ),
  279. "fake-app",
  280. ) == ("my-site", "url211", "url212")
  281. def test_process_envs():
  282. assert hosting.process_envs(["a=b", "c=d"]) == {"a": "b", "c": "d"}
  283. @pytest.mark.parametrize(
  284. "inputs, expected",
  285. [
  286. # enters two envs then enter
  287. (
  288. ["a", "b", "c", "d", ""],
  289. ["a=b", "c=d"],
  290. ),
  291. # No envs
  292. ([""], []),
  293. # enters one env with value, one without, then enter
  294. (["a", "b", "c", "", ""], ["a=b", "c="]),
  295. ],
  296. )
  297. def test_interactive_prompt_for_envs(mocker, inputs, expected):
  298. mocker.patch("reflex.utils.console.ask", side_effect=inputs)
  299. assert hosting.interactive_prompt_for_envs() == expected
  300. def test_requirements_txt_only_contains_reflex(mocker):
  301. mocker.patch("reflex.utils.hosting.check_requirements_txt_exist", return_value=True)
  302. mocker.patch("builtins.open", mock_open(read_data="\nreflex=1.2.3\n\n"))
  303. assert hosting.check_requirements_for_non_reflex_packages() is False
  304. def test_requirements_txt_only_contains_other_packages(mocker):
  305. mocker.patch("reflex.utils.hosting.check_requirements_txt_exist", return_value=True)
  306. mocker.patch(
  307. "builtins.open", mock_open(read_data="\nreflex=1.2.3\n\npynonexist=3.2.1")
  308. )
  309. assert hosting.check_requirements_for_non_reflex_packages() is True