Repository navigation
Expand file tree
/
Copy pathtest_hosting.py
More file actions
1463 lines (1145 loc) ยท 46.4 KB
/
Copy pathtest_hosting.py
File metadata and controls
1463 lines (1145 loc) ยท 46.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import json
import logging
import uuid
from unittest.mock import MagicMock, mock_open
import click
import pytest
from pytest_mock import MockerFixture, MockFixture
from reflex_base.utils.log import SUCCESS
from reflex_build_sdk.types import DeploymentReport, GcpConnection, GcpStatus
from reflex_cli import constants
from reflex_cli.utils.exceptions import TokenAccessDeniedError, TokenValidationError
from reflex_cli.utils.hosting import (
_WATCH_UNREACHABLE_GRACE,
ScaleParams,
ScaleType,
TokenSource,
WatchOutcome,
_report_deployment_failure,
_strip_terminal_controls,
as_json_document,
authenticated_token,
delete_token_from_config,
deployment_status_failed,
find_gcp_connection,
gcp_deploy_available,
get_auth_request_id,
get_authenticated_client,
get_existing_access_token,
get_existing_access_token_with_source,
get_selected_project,
get_token_org_id,
get_token_tier,
list_gcp_connections,
normalize_project_id,
normalize_provider,
provider_display_name,
save_token_to_config,
set_instance_bounds,
stored_access_token,
validate_token,
validate_token_with_retries,
watch_deployment_status,
)
from tests.units.reflex_cli.sdk import api_error, fake_client
_client = fake_client
@pytest.mark.parametrize(
"config_content, expected_token",
[
('{"access_token": "valid_token"}', "valid_token"),
("{}", ""),
(None, ""),
],
)
def test_get_existing_access_token(
mocker: MockerFixture, config_content: str | None, expected_token: str
):
mocker.patch("os.environ.get", return_value="")
mocker.patch("pathlib.Path.open", mock_open(read_data=config_content))
assert get_existing_access_token() == expected_token
mocker.patch("pathlib.Path.open", side_effect=FileNotFoundError("Test exception"))
assert get_existing_access_token() == ""
def test_get_existing_access_token_prefers_the_environment(
monkeypatch: pytest.MonkeyPatch,
):
"""An exported token is an explicit choice; the config file is ambient state.
Args:
monkeypatch: The pytest monkeypatch fixture.
"""
monkeypatch.setenv("REFLEX_ACCESS_TOKEN", "env_token")
constants.Hosting.HOSTING_JSON.write_text('{"access_token": "config_token"}')
assert get_existing_access_token_with_source() == (
"env_token",
TokenSource.ENVIRONMENT,
)
def test_get_existing_access_token_falls_back_to_the_config_file(
monkeypatch: pytest.MonkeyPatch,
):
"""Without the environment variable the stored token is used.
Args:
monkeypatch: The pytest monkeypatch fixture.
"""
monkeypatch.delenv("REFLEX_ACCESS_TOKEN", raising=False)
constants.Hosting.HOSTING_JSON.write_text('{"access_token": "config_token"}')
assert get_existing_access_token_with_source() == (
"config_token",
TokenSource.CONFIG,
)
def test_get_existing_access_token_ignores_an_empty_environment_variable(
monkeypatch: pytest.MonkeyPatch,
):
"""An empty export is not a token and must not shadow the config file.
Args:
monkeypatch: The pytest monkeypatch fixture.
"""
monkeypatch.setenv("REFLEX_ACCESS_TOKEN", "")
constants.Hosting.HOSTING_JSON.write_text('{"access_token": "config_token"}')
assert get_existing_access_token_with_source() == (
"config_token",
TokenSource.CONFIG,
)
def test_get_existing_access_token_with_no_token_anywhere(
mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.delenv("REFLEX_ACCESS_TOKEN", raising=False)
mocker.patch("pathlib.Path.open", side_effect=FileNotFoundError("Test exception"))
assert get_existing_access_token_with_source() == ("", TokenSource.NONE)
@pytest.mark.parametrize(
"config_content, expected",
[
('{"access_token": "valid_token"}', {}),
('{"access_token": "valid_token", "project": "p1"}', {"project": "p1"}),
('{"another_key": "value"}', {"another_key": "value"}),
],
)
def test_delete_token_from_config(config_content: str, expected: dict):
"""Only the token is removed; everything else in the config survives.
Args:
config_content: The starting contents of the config file.
expected: The config expected to remain afterwards.
"""
constants.Hosting.HOSTING_JSON.write_text(config_content)
delete_token_from_config()
assert json.loads(constants.Hosting.HOSTING_JSON.read_text()) == expected
@pytest.mark.parametrize(
"stored_token, token, removed",
[
("old_token", "old_token", True),
("new_token", "old_token", False),
("new_token", "", False),
("", "", True),
(None, "old_token", False),
],
)
def test_delete_token_from_config_only_removes_matching_token(
stored_token: str | None, token: str, removed: bool
):
"""Conditional deletion preserves a different token and unrelated settings.
Args:
stored_token: The token stored in the config, or None if absent.
token: The token expected to be removed.
removed: Whether the stored token should be removed.
"""
config = {"project": "p1"}
if stored_token is not None:
config["access_token"] = stored_token
original = json.dumps(config, indent=2)
constants.Hosting.HOSTING_JSON.write_text(original)
delete_token_from_config(token)
if removed:
assert json.loads(constants.Hosting.HOSTING_JSON.read_text()) == {
"project": "p1"
}
else:
assert constants.Hosting.HOSTING_JSON.read_text() == original
@pytest.mark.parametrize("token", [None, "old_token"])
def test_delete_token_from_config_without_a_config_file(token: str | None):
"""Deleting when no config exists is a no-op rather than an error.
Args:
token: The optional token expected to be removed.
"""
assert not constants.Hosting.HOSTING_JSON.exists()
delete_token_from_config(token)
assert not constants.Hosting.HOSTING_JSON.exists()
def test_delete_token_from_config_keeps_the_config_when_the_write_fails(
mocker: MockerFixture,
):
"""A failed delete must leave the existing config readable, not truncated.
Args:
mocker: Pytest mocker fixture.
"""
original = '{"access_token": "good_token", "project": "p1"}'
constants.Hosting.HOSTING_JSON.write_text(original)
mocker.patch("json.dump", side_effect=OSError("disk full"))
delete_token_from_config()
assert constants.Hosting.HOSTING_JSON.read_text() == original
assert list(constants.Hosting.HOSTING_JSON.parent.iterdir()) == [
constants.Hosting.HOSTING_JSON
]
def test_delete_token_from_config_keeps_an_unreadable_config(
mocker: MockerFixture,
):
"""A config that cannot be parsed is left alone rather than replaced.
Args:
mocker: Pytest mocker fixture.
"""
malformed = '{"access_token": "good_token", "project": "p1"'
constants.Hosting.HOSTING_JSON.write_text(malformed)
delete_token_from_config()
assert constants.Hosting.HOSTING_JSON.read_text() == malformed
def test_save_token_to_config_recovers_from_an_unreadable_config():
"""Re-authenticating still works when the config is malformed."""
constants.Hosting.HOSTING_JSON.write_text('{"access_token": "good_token"')
save_token_to_config("new_token")
assert json.loads(constants.Hosting.HOSTING_JSON.read_text()) == {
"access_token": "new_token"
}
def test_stored_access_token_distinguishes_absent_from_unreadable():
"""A missing config reads as no token; a malformed one is an error."""
assert stored_access_token() == ""
constants.Hosting.HOSTING_JSON.write_text('{"project": "p1"}')
assert stored_access_token() == ""
constants.Hosting.HOSTING_JSON.write_text('{"access_token": "tok"}')
assert stored_access_token() == "tok"
constants.Hosting.HOSTING_JSON.write_text("{not json")
with pytest.raises(ValueError):
stored_access_token()
# Valid JSON that is not an object is still unusable, not empty.
constants.Hosting.HOSTING_JSON.write_text('["not", "an", "object"]')
with pytest.raises(ValueError):
stored_access_token()
def test_delete_token_from_config_tolerates_an_unremovable_legacy_file(
mocker: MockerFixture,
):
"""The legacy cleanup must not abort the token removal it follows.
Args:
mocker: Pytest mocker fixture.
"""
constants.Hosting.HOSTING_JSON.write_text('{"access_token": "valid_token"}')
constants.Hosting.HOSTING_JSON_V0.write_text("{}")
mocker.patch("pathlib.Path.unlink", side_effect=PermissionError("denied"))
delete_token_from_config()
assert json.loads(constants.Hosting.HOSTING_JSON.read_text()) == {}
def test_delete_token_from_config_removes_the_legacy_file():
"""The pre-v1 hosting file is removed alongside the token."""
constants.Hosting.HOSTING_JSON.write_text('{"access_token": "valid_token"}')
constants.Hosting.HOSTING_JSON_V0.write_text("{}")
delete_token_from_config()
assert not constants.Hosting.HOSTING_JSON_V0.exists()
def test_save_token_to_config_creates_the_config():
"""Saving works when neither the directory nor the file exists yet."""
save_token_to_config("test_token")
assert json.loads(constants.Hosting.HOSTING_JSON.read_text()) == {
"access_token": "test_token"
}
def test_save_token_to_config_preserves_other_keys():
"""Saving a token leaves unrelated config entries untouched."""
constants.Hosting.HOSTING_JSON.write_text(
'{"access_token": "old_token", "project": "p1"}'
)
save_token_to_config("new_token")
assert json.loads(constants.Hosting.HOSTING_JSON.read_text()) == {
"access_token": "new_token",
"project": "p1",
}
def test_save_token_to_config_keeps_the_old_token_when_the_write_fails(
mocker: MockerFixture,
):
"""A failed write must not truncate the credentials already on disk.
Args:
mocker: Pytest mocker fixture.
"""
original = '{"access_token": "good_token", "project": "p1"}'
constants.Hosting.HOSTING_JSON.write_text(original)
mocker.patch("json.dump", side_effect=OSError("disk full"))
save_token_to_config("new_token")
assert constants.Hosting.HOSTING_JSON.read_text() == original
# The temporary file used for the atomic replace is cleaned up.
assert list(constants.Hosting.HOSTING_JSON.parent.iterdir()) == [
constants.Hosting.HOSTING_JSON
]
def test_authenticated_token_found_and_valid(mocker: MockFixture):
"""A stored token that validates comes back with the identity behind it.
Args:
mocker: Pytest mocker fixture.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token", return_value="valid_token"
)
mocker.patch("reflex_cli.utils.hosting._validate", return_value=_client().me)
token, info = authenticated_token()
assert token == "valid_token"
assert info["tier"] == "Pro"
assert info["user_id"] == str(uuid.UUID(int=1))
def test_authenticated_token_not_found(mocker: MockFixture):
"""With nothing stored there is nothing to validate.
Args:
mocker: Pytest mocker fixture.
"""
mocker.patch("reflex_cli.utils.hosting.get_existing_access_token", return_value="")
assert authenticated_token() == ("", {})
def test_authenticated_token_found_but_invalid(mocker: MockFixture):
"""A refused token is reported as no token at all, and is discarded.
Args:
mocker: Pytest mocker fixture.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token", return_value="bad_token"
)
mocker.patch(
"reflex_cli.utils.hosting._validate",
side_effect=TokenAccessDeniedError("access denied", request_id="req-1"),
)
delete_token = mocker.patch("reflex_cli.utils.hosting.delete_token_from_config")
assert authenticated_token() == ("", {})
delete_token.assert_called_once_with("bad_token")
@pytest.mark.parametrize("interactive", [True, False])
def test_validation_failure_preserves_a_replacement_token(
mocker: MockFixture, interactive: bool
):
"""A token saved during validation survives rejection of the previous token.
Args:
mocker: Pytest mocker fixture.
interactive: Whether to use the interactive validation helper.
"""
save_token_to_config("old_token")
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token_with_source",
return_value=("old_token", TokenSource.CONFIG),
)
def replace_token_and_reject(access_token: str, api=None):
"""Simulate a concurrent login before the validation response arrives.
Args:
access_token: The token being validated.
api: The optional client used for validation.
Raises:
TokenAccessDeniedError: When the old token is rejected.
"""
assert access_token == "old_token"
save_token_to_config("new_token")
msg = "access denied"
raise TokenAccessDeniedError(msg, request_id="req-1")
mocker.patch(
"reflex_cli.utils.hosting._validate", side_effect=replace_token_and_reject
)
if interactive:
assert validate_token_with_retries("old_token") == {}
else:
with pytest.raises(click.exceptions.Exit):
get_authenticated_client(token=None, interactive=False)
assert stored_access_token() == "new_token"
def test_authenticated_token_found_but_validation_fails(mocker: MockFixture):
"""A validation that could not be completed is not an identity.
Args:
mocker: Pytest mocker fixture.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token", return_value="some_token"
)
mocker.patch(
"reflex_cli.utils.hosting._validate",
side_effect=TokenValidationError("server error", request_id="req-1"),
)
assert authenticated_token() == ("", {})
def test_authenticate_without_token_in_non_interactive_mode(mocker: MockerFixture):
"""Non-interactive with nothing to authenticate with is an error, not a prompt.
Args:
mocker: Pytest mocker fixture.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token_with_source",
return_value=("", TokenSource.NONE),
)
with pytest.raises(click.exceptions.Exit):
get_authenticated_client(token=None, interactive=False)
def test_authenticate_with_env_token_in_non_interactive_mode(mocker: MockerFixture):
"""An exported token is enough to authenticate without a browser.
Args:
mocker: Pytest mocker fixture.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token_with_source",
return_value=("env_token", TokenSource.ENVIRONMENT),
)
client = _client()
new_client = mocker.patch(
"reflex_cli.utils.hosting.new_client", return_value=client.api
)
validate = mocker.patch(
"reflex_cli.utils.hosting._validate", return_value=client.me
)
browser = mocker.patch("reflex_cli.utils.hosting._authenticate_on_browser")
result = get_authenticated_client(token=None, interactive=False)
assert result.api is client.api
assert result.me is client.me
new_client.assert_called_once_with("env_token")
validate.assert_called_once_with("env_token", client.api)
browser.assert_not_called()
@pytest.mark.parametrize(
("token", "source"),
[
(None, TokenSource.ENVIRONMENT),
("bogus-token", TokenSource.OPTION),
],
)
def test_rejected_token_in_non_interactive_mode_does_not_prompt(
mocker: MockerFixture,
caplog: pytest.LogCaptureFixture,
token: str | None,
source: TokenSource,
):
"""A rejected token fails straight away instead of starting a browser login.
Args:
mocker: Pytest mocker fixture.
caplog: Pytest log capture fixture.
token: The token passed with --token, if any.
source: Where the rejected token came from.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token_with_source",
return_value=("bogus-token", TokenSource.ENVIRONMENT),
)
mocker.patch(
"reflex_cli.utils.hosting._validate",
side_effect=TokenAccessDeniedError("access denied", request_id="req-1"),
)
browser = mocker.patch(
"reflex_cli.utils.hosting._authenticate_on_browser", return_value=("", None)
)
with pytest.raises(click.exceptions.Exit) as exc_info:
get_authenticated_client(token=token, interactive=False)
assert exc_info.value.exit_code == 1
browser.assert_not_called()
errors = [r.getMessage() for r in caplog.records if r.levelno == logging.ERROR]
assert len(errors) == 1
assert errors[0].startswith(
f"The access token from the {source.value} was rejected: access denied (auth request id: req-1)"
)
assert "reflex login" in errors[0]
def test_rejected_config_token_in_non_interactive_mode_is_removed(
mocker: MockerFixture,
):
"""A saved token the control plane refuses is dropped from the config.
Args:
mocker: Pytest mocker fixture.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token_with_source",
return_value=("stale-token", TokenSource.CONFIG),
)
mocker.patch(
"reflex_cli.utils.hosting._validate",
side_effect=TokenAccessDeniedError("access denied", request_id="req-1"),
)
delete = mocker.patch("reflex_cli.utils.hosting.delete_token_from_config")
with pytest.raises(click.exceptions.Exit):
get_authenticated_client(token=None, interactive=False)
delete.assert_called_once_with("stale-token")
def test_unvalidated_token_in_non_interactive_mode_is_not_called_rejected(
mocker: MockerFixture, caplog: pytest.LogCaptureFixture
):
"""A timeout or server error fails without calling the token rejected.
Args:
mocker: Pytest mocker fixture.
caplog: Pytest log capture fixture.
"""
mocker.patch(
"reflex_cli.utils.hosting.get_existing_access_token_with_source",
return_value=("saved-token", TokenSource.CONFIG),
)
mocker.patch(
"reflex_cli.utils.hosting._validate",
side_effect=TokenValidationError("server error", request_id="req-2"),
)
delete = mocker.patch("reflex_cli.utils.hosting.delete_token_from_config")
browser = mocker.patch("reflex_cli.utils.hosting._authenticate_on_browser")
with pytest.raises(click.exceptions.Exit) as exc_info:
get_authenticated_client(token=None, interactive=False)
assert exc_info.value.exit_code == 1
delete.assert_not_called()
browser.assert_not_called()
errors = [r.getMessage() for r in caplog.records if r.levelno == logging.ERROR]
assert errors == [
"Unable to validate the access token from the config file: server error (auth request id: req-2). Please try again later."
]
def test_scale_arguments_are_pure_when_type_is_unspecified():
"""Reading the scale arguments must not settle the type on the object."""
scale_params = ScaleParams(vm_type="shared-1x")
first = scale_params.as_scale_arguments()
second = scale_params.as_scale_arguments()
assert scale_params.type is None
assert first == second == {"regions": {}}
def test_scale_arguments_by_size():
"""A size scale names the machine rather than the regions."""
scale_params = ScaleParams(type=ScaleType.SIZE, vm_type="c1m1")
assert scale_params.as_scale_arguments() == {"vm_type": "c1m1"}
def test_normalize_provider():
"""User-facing provider names map to backend values (or None if unknown)."""
from reflex_cli.utils.hosting import PROVIDER_GCP, PROVIDER_REFLEX_CLOUD
assert normalize_provider("reflex-cloud") == PROVIDER_REFLEX_CLOUD
assert normalize_provider("Reflex") == PROVIDER_REFLEX_CLOUD
assert normalize_provider("GCP") == PROVIDER_GCP
assert normalize_provider("google-cloud") == PROVIDER_GCP
assert normalize_provider("aws") is None
# The backend wire value is not exposed as a user-facing name.
assert normalize_provider("fly") is None
def test_provider_display_name():
"""Backend provider values render human-facing labels, defaulting to Cloud."""
assert provider_display_name("gcp") == "Google Cloud (GCP)"
assert provider_display_name("fly") == "Reflex Cloud"
assert provider_display_name(None) == "Reflex Cloud"
def test_get_token_org_and_tier():
"""org_id/tier come from the identity behind the token, None when absent."""
client = _client(org_id="org-1", tier="Enterprise")
assert get_token_org_id(client) == "org-1"
assert get_token_tier(client) == "Enterprise"
assert get_token_org_id(_client(org_id="")) is None
assert get_token_tier(_client(tier="")) is None
def _status(**fields: object) -> GcpStatus:
"""Build an org's GCP status.
Args:
fields: Overrides for the status fields.
Returns:
The status.
"""
defaults: dict[str, object] = {
"configured": True,
"allowed": True,
"project_id": None,
"region": None,
"connections": [],
}
defaults.update(fields)
return GcpStatus(**defaults) # pyright: ignore[reportArgumentType]
def test_gcp_deploy_available_configured_and_allowed():
"""GCP is offered only when it's both connected and tier-allowed."""
client = _client(org_id="o")
status = _status(region="us-central1")
client.api.providers.gcp_status.return_value = status
assert gcp_deploy_available(client) is status
def test_gcp_deploy_available_not_allowed():
"""A connected-but-not-allowed org does not get GCP offered."""
client = _client(org_id="o")
client.api.providers.gcp_status.return_value = _status(allowed=False)
assert gcp_deploy_available(client) is None
def test_gcp_deploy_available_swallows_errors():
"""A lookup failure falls back to no GCP rather than aborting the deploy."""
client = _client(org_id="o")
client.api.providers.gcp_status.side_effect = api_error(500, "boom")
assert gcp_deploy_available(client) is None
def test_gcp_deploy_available_without_org():
"""No resolvable org id means GCP cannot be offered."""
assert gcp_deploy_available(_client(org_id="")) is None
def _connection(name: str, number: int) -> GcpConnection:
"""Build a GCP connection.
Args:
name: The connection's name.
number: Seeds its id.
Returns:
The connection.
"""
return GcpConnection(
id=uuid.UUID(int=number),
name=name,
is_default=False,
project_id="p",
region="us-central1",
)
def test_list_gcp_connections_reads_the_status():
"""Connections come from the member-visible GCP status."""
client = _client(org_id="org-1")
connection = _connection("prod", 1)
client.api.providers.gcp_status.return_value = _status(connections=[connection])
assert list_gcp_connections(client) == [connection]
def test_list_gcp_connections_without_org():
"""No resolvable org id means there is nothing to list."""
assert list_gcp_connections(_client(org_id="")) == []
def test_list_gcp_connections_explicit_org():
"""An explicit org id wins over the token's own."""
client = _client(org_id="token-org")
client.api.providers.gcp_status.return_value = _status()
assert list_gcp_connections(client, org_id="other-org") == []
client.api.providers.gcp_status.assert_called_once_with("other-org")
@pytest.mark.parametrize(
("wanted", "expected"),
[
("prod", 1),
("PROD", 1),
(" prod ", 1),
("staging", 2),
("nope", None),
],
)
def test_find_gcp_connection(wanted: str, expected: int | None):
"""Connections match on id first, then on name, case-insensitively.
Args:
wanted: The name or id the user asked for.
expected: The seed of the connection that should match, if any.
"""
connections = [_connection("prod", 1), _connection("Staging", 2)]
match = find_gcp_connection(connections, wanted)
assert (match.id if match else None) == (
uuid.UUID(int=expected) if expected else None
)
def test_find_gcp_connection_by_id():
"""A connection is found by its id as well as by its name."""
connections = [_connection("prod", 1), _connection("Staging", 2)]
match = find_gcp_connection(connections, str(uuid.UUID(int=2)))
assert match is not None
assert match.name == "Staging"
@pytest.mark.parametrize(
("min_instances", "max_instances", "expected"),
[
(0, 5, {"min_instances": 0, "max_instances": 5}),
(2, None, {"min_instances": 2, "max_instances": 9}),
(None, 10, {"min_instances": 3, "max_instances": 10}),
],
)
def test_set_instance_bounds_keeps_the_bound_it_was_not_given(
min_instances: int | None,
max_instances: int | None,
expected: dict[str, int],
):
"""The endpoint replaces both bounds, so the app supplies the missing one.
Args:
min_instances: The minimum the caller asked for, if any.
max_instances: The maximum the caller asked for, if any.
expected: The bounds that should be sent.
"""
client = _client()
client.api.apps.get.return_value.min_instances = 3
client.api.apps.get.return_value.max_instances = 9
assert (
set_instance_bounds(
"app-1",
client,
min_instances=min_instances,
max_instances=max_instances,
)
is None
)
client.api.apps.set_instance_bounds.assert_called_once_with("app-1", **expected)
@pytest.mark.parametrize(
("status_code", "detail"),
[
(400, "min_instances must be less than or equal to max_instances"),
(400, "platform does not support instance bounds"),
(409, "a scale operation is already running for this app"),
],
)
def test_set_instance_bounds_error(status_code: int, detail: str):
"""Validation, unsupported-platform and conflict details reach the caller.
Args:
status_code: The status the API refused with.
detail: The API's explanation.
"""
client = _client()
client.api.apps.set_instance_bounds.side_effect = api_error(status_code, detail)
result = set_instance_bounds("app-1", client, min_instances=1, max_instances=0)
assert result is not None
assert result.startswith("set instance bounds failed")
assert detail in result
def test_validate_token_names_the_product_it_logs_in_through(
mocker: MockerFixture,
):
"""The identity call records which product the login came from.
Args:
mocker: Pytest mocker fixture.
"""
client = MagicMock()
client.__enter__.return_value = client
client.auth.me.return_value = _client(tier="Enterprise").me
mocker.patch("reflex_cli.utils.hosting.new_client", return_value=client)
mocker.patch(
"reflex_cli.utils.hosting.is_reflex_enterprise_installed", return_value=False
)
assert validate_token("some-token")["tier"] == "Enterprise"
client.auth.me.assert_called_once_with(source="reflex")
def test_validate_token_with_retries_warns_with_request_id(
mocker: MockerFixture, caplog: pytest.LogCaptureFixture
):
"""A failed validation surfaces the request id for support correlation.
Args:
mocker: Pytest mocker fixture.
caplog: Pytest log capture fixture.
"""
client = MagicMock()
client.__enter__.return_value = client
client.auth.me.side_effect = api_error(500, "boom")
mocker.patch("reflex_cli.utils.hosting.new_client", return_value=client)
assert validate_token_with_retries("some-token") == {}
request_id = get_auth_request_id()
assert request_id
warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
assert warnings
assert request_id in warnings[-1]
def test_validate_token_with_retries_access_denied_reports_request_id(
mocker: MockerFixture, caplog: pytest.LogCaptureFixture
):
"""The access denied error message includes the auth request id.
Args:
mocker: Pytest mocker fixture.
caplog: Pytest log capture fixture.
"""
client = MagicMock()
client.__enter__.return_value = client
client.auth.me.side_effect = api_error(403, "denied")
mocker.patch("reflex_cli.utils.hosting.new_client", return_value=client)
mocker.patch("reflex_cli.utils.hosting.delete_token_from_config")
assert validate_token_with_retries("some-token") == {}
errors = [r.getMessage() for r in caplog.records if r.levelno == logging.ERROR]
assert errors
assert get_auth_request_id() in errors[-1]
def test_validate_token_failure_carries_request_id_on_exception(
mocker: MockerFixture,
):
"""Validation errors carry the request id of their own request.
Args:
mocker: Pytest mocker fixture.
"""
client = MagicMock()
client.__enter__.return_value = client
client.auth.me.side_effect = api_error(500, "boom")
mocker.patch("reflex_cli.utils.hosting.new_client", return_value=client)
with pytest.raises(TokenValidationError) as exc_info:
validate_token("some-token")
assert exc_info.value.request_id == get_auth_request_id() != ""
@pytest.mark.parametrize(
("status", "failed"),
[
("deployment completed successfully", False),
("AwaitingApproval", False),
("bad response. received a bad response from cloud service.", False),
("Deployment is running smoothly.", False),
("build error", True),
("deployment failed", True),
("error: something went wrong", True),
("unable to find status for given id", True),
],
)
def test_deployment_status_failed(status: str, failed: bool):
"""A status is classified the same way wherever it is read.
Args:
status: The status string the hosting service returned.
failed: Whether it should read as a failure.
"""
assert deployment_status_failed(status) is failed
def test_as_json_document_renders_ids_and_timestamps_as_strings():
"""A document keeps the shape it had when response bodies were printed."""
connection = _connection("prod", 1)
when = datetime.datetime(2026, 7, 1, tzinfo=datetime.UTC)
assert as_json_document(connection) == {
"id": str(uuid.UUID(int=1)),
"name": "prod",
"is_default": False,
"project_id": "p",
"region": "us-central1",
}
assert as_json_document({"at": when}) == {"at": "2026-07-01T00:00:00+00:00"}
assert as_json_document([connection.id]) == [str(uuid.UUID(int=1))]
def _log_messages(caplog: pytest.LogCaptureFixture, level: int) -> list[str]:
"""Return the captured log messages emitted at the given level.
Args:
caplog: The pytest log capture fixture.
level: The numeric log level to filter records by.
Returns:
The formatted messages of the matching records.
"""
return [r.getMessage() for r in caplog.records if r.levelno == level]
def _report(**fields: object) -> DeploymentReport:
"""Build a deployment's final report.
Args:
fields: Overrides for the report's fields.
Returns:
The report.
"""
report: dict[str, object] = {
"status": "Failed",
"code": None,
"fault": None,
"reason": "",
"guidance": "",
"build_log_excerpt": None,
}
report.update(fields)
return DeploymentReport(**report) # pyright: ignore[reportArgumentType]
def test_failure_report_prints_reason_and_build_log(
caplog: pytest.LogCaptureFixture, capsys: pytest.CaptureFixture[str]
):
"""A build failure shows its reason, its guidance and the log's tail.
Args:
caplog: Pytest log capture fixture.
capsys: Pytest stdout capture fixture.
"""
report = _report(
code="build_failed",
fault="customer",
reason="Deployment error: the build failed",
guidance="Your app failed to build.",