add some of the TRY rules (#4651)

This commit is contained in:
Thomas Brandého 2025-01-20 13:58:17 -08:00 committed by GitHub
parent 9c019a65d5
commit 2855ed4887
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 56 additions and 38 deletions

View File

@ -86,8 +86,8 @@ build-backend = "poetry.core.masonry.api"
target-version = "py39"
output-format = "concise"
lint.isort.split-on-trailing-comma = false
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PERF", "PTH", "RUF", "SIM", "T", "W"]
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012"]
lint.select = ["B", "C4", "D", "E", "ERA", "F", "FURB", "I", "PERF", "PTH", "RUF", "SIM", "T", "TRY", "W"]
lint.ignore = ["B008", "D205", "E501", "F403", "SIM115", "RUF006", "RUF012", "TRY0"]
lint.pydocstyle.convention = "google"
[tool.ruff.lint.per-file-ignores]

View File

@ -463,14 +463,8 @@ class App(MiddlewareMixin, LifespanMixin):
Returns:
The generated component.
Raises:
exceptions.MatchTypeError: If the return types of match cases in rx.match are different.
"""
try:
return component if isinstance(component, Component) else component()
except exceptions.MatchTypeError:
raise
return component if isinstance(component, Component) else component()
def add_page(
self,

View File

@ -429,20 +429,22 @@ class Component(BaseComponent, ABC):
else:
continue
def determine_key(value):
# Try to create a var from the value
key = value if isinstance(value, Var) else LiteralVar.create(value)
# Check that the var type is not None.
if key is None:
raise TypeError
return key
# Check whether the key is a component prop.
if types._issubclass(field_type, Var):
# Used to store the passed types if var type is a union.
passed_types = None
try:
# Try to create a var from the value.
if isinstance(value, Var):
kwargs[key] = value
else:
kwargs[key] = LiteralVar.create(value)
# Check that the var type is not None.
if kwargs[key] is None:
raise TypeError
kwargs[key] = determine_key(value)
expected_type = fields[key].outer_type_.__args__[0]
# validate literal fields.

View File

@ -421,12 +421,13 @@ def _run_commands_in_subprocess(cmds: list[str]) -> bool:
console.debug(f"Running command: {' '.join(cmds)}")
try:
result = subprocess.run(cmds, capture_output=True, text=True, check=True)
console.debug(result.stdout)
return True
except subprocess.CalledProcessError as cpe:
console.error(cpe.stdout)
console.error(cpe.stderr)
return False
else:
console.debug(result.stdout)
return True
def _make_pyi_files():
@ -931,10 +932,11 @@ def _get_file_from_prompt_in_loop() -> Tuple[bytes, str] | None:
file_extension = image_filepath.suffix
try:
image_file = image_filepath.read_bytes()
return image_file, file_extension
except OSError as ose:
console.error(f"Unable to read the {file_extension} file due to {ose}")
raise typer.Exit(code=1) from ose
else:
return image_file, file_extension
console.debug(f"File extension detected: {file_extension}")
return None

View File

@ -278,6 +278,22 @@ def windows_npm_escape_hatch() -> bool:
return environment.REFLEX_USE_NPM.get()
def _check_app_name(config: Config):
"""Check if the app name is set in the config.
Args:
config: The config object.
Raises:
RuntimeError: If the app name is not set in the config.
"""
if not config.app_name:
raise RuntimeError(
"Cannot get the app module because `app_name` is not set in rxconfig! "
"If this error occurs in a reflex test case, ensure that `get_app` is mocked."
)
def get_app(reload: bool = False) -> ModuleType:
"""Get the app module based on the default config.
@ -288,18 +304,16 @@ def get_app(reload: bool = False) -> ModuleType:
The app based on the default config.
Raises:
RuntimeError: If the app name is not set in the config.
Exception: If an error occurs while getting the app module.
"""
from reflex.utils import telemetry
try:
environment.RELOAD_CONFIG.set(reload)
config = get_config()
if not config.app_name:
raise RuntimeError(
"Cannot get the app module because `app_name` is not set in rxconfig! "
"If this error occurs in a reflex test case, ensure that `get_app` is mocked."
)
_check_app_name(config)
module = config.module
sys.path.insert(0, str(Path.cwd()))
app = (
@ -315,11 +329,11 @@ def get_app(reload: bool = False) -> ModuleType:
# Reload the app module.
importlib.reload(app)
return app
except Exception as ex:
telemetry.send_error(ex, context="frontend")
raise
else:
return app
def get_and_validate_app(reload: bool = False) -> AppInfo:
@ -1189,11 +1203,12 @@ def ensure_reflex_installation_id() -> Optional[int]:
if installation_id is None:
installation_id = random.getrandbits(128)
installation_id_file.write_text(str(installation_id))
# If we get here, installation_id is definitely set
return installation_id
except Exception as e:
console.debug(f"Failed to ensure reflex installation id: {e}")
return None
else:
# If we get here, installation_id is definitely set
return installation_id
def initialize_reflex_user_directory():
@ -1407,19 +1422,22 @@ def create_config_init_app_from_remote_template(app_name: str, template_url: str
except OSError as ose:
console.error(f"Failed to create temp directory for extracting zip: {ose}")
raise typer.Exit(1) from ose
try:
zipfile.ZipFile(zip_file_path).extractall(path=unzip_dir)
# The zip file downloaded from github looks like:
# repo-name-branch/**/*, so we need to remove the top level directory.
if len(subdirs := os.listdir(unzip_dir)) != 1:
console.error(f"Expected one directory in the zip, found {subdirs}")
raise typer.Exit(1)
template_dir = unzip_dir / subdirs[0]
console.debug(f"Template folder is located at {template_dir}")
except Exception as uze:
console.error(f"Failed to unzip the template: {uze}")
raise typer.Exit(1) from uze
if len(subdirs := os.listdir(unzip_dir)) != 1:
console.error(f"Expected one directory in the zip, found {subdirs}")
raise typer.Exit(1)
template_dir = unzip_dir / subdirs[0]
console.debug(f"Template folder is located at {template_dir}")
# Move the rxconfig file here first.
path_ops.mv(str(template_dir / constants.Config.FILE), constants.Config.FILE)
new_config = get_config(reload=True)

View File

@ -156,9 +156,10 @@ def _prepare_event(event: str, **kwargs) -> dict:
def _send_event(event_data: dict) -> bool:
try:
httpx.post(POSTHOG_API_URL, json=event_data)
return True
except Exception:
return False
else:
return True
def _send(event, telemetry_enabled, **kwargs):

View File

@ -71,9 +71,10 @@ def has_error_modal(driver: WebDriver) -> bool:
"""
try:
driver.find_element(By.XPATH, CONNECTION_ERROR_XPATH)
return True
except NoSuchElementException:
return False
else:
return True
@pytest.mark.asyncio