Parse timeout string with optional suffix into seconds. Supported formats: - Plain number: "120" → 120 seconds - Milliseconds: "5000ms" → 5 seconds - Seconds: "120s" → 120 seconds - Minutes: "2m" → 120 seconds Args: timeout_str: Timeout string (e.g.,
(timeout_str: str)
| 101 | |
| 102 | |
| 103 | def parse_timeout(timeout_str: str) -> int: |
| 104 | """Parse timeout string with optional suffix into seconds. |
| 105 | |
| 106 | Supported formats: |
| 107 | - Plain number: "120" → 120 seconds |
| 108 | - Milliseconds: "5000ms" → 5 seconds |
| 109 | - Seconds: "120s" → 120 seconds |
| 110 | - Minutes: "2m" → 120 seconds |
| 111 | |
| 112 | Args: |
| 113 | timeout_str: Timeout string (e.g., "120", "2m", "5000ms") |
| 114 | |
| 115 | Returns: |
| 116 | Timeout in seconds (integer) |
| 117 | |
| 118 | Raises: |
| 119 | ValueError: If format is invalid or value is not positive |
| 120 | """ |
| 121 | import re |
| 122 | |
| 123 | timeout_str = timeout_str.strip() |
| 124 | |
| 125 | # Match number with optional suffix |
| 126 | match = re.match(r"^(\d+(?:\.\d+)?)\s*(ms|s|m)?$", timeout_str, re.IGNORECASE) |
| 127 | if not match: |
| 128 | raise ValueError( |
| 129 | f"Invalid timeout format: '{timeout_str}'. " |
| 130 | f"Expected formats: '120', '120s', '2m', '5000ms'" |
| 131 | ) |
| 132 | |
| 133 | value_str, suffix = match.groups() |
| 134 | value = float(value_str) |
| 135 | |
| 136 | if value <= 0: |
| 137 | raise ValueError(f"Timeout must be positive, got: {value}") |
| 138 | |
| 139 | # Convert to seconds |
| 140 | if suffix is None or suffix.lower() == "s": |
| 141 | # Default is seconds |
| 142 | seconds = value |
| 143 | elif suffix.lower() == "ms": |
| 144 | # Milliseconds to seconds |
| 145 | seconds = value / 1000 |
| 146 | elif suffix.lower() == "m": |
| 147 | # Minutes to seconds |
| 148 | seconds = value * 60 |
| 149 | else: |
| 150 | # Should never reach here due to regex |
| 151 | raise ValueError(f"Unknown suffix: {suffix}") |
| 152 | |
| 153 | # Return as integer (round up to ensure at least 1 second for small values) |
| 154 | return max(1, int(seconds)) |
no test coverage detected