Skip to content

Commit

Permalink
refactored logics and added unit test for --api-server-timeout argument
Browse files Browse the repository at this point in the history
  • Loading branch information
samuel-esp committed Nov 20, 2024
1 parent 72ad3fb commit e625241
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
4 changes: 2 additions & 2 deletions kube_downscaler/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ def _matches_absolute_time_spec(time: datetime.datetime, match: Match):
return time_from <= time <= time_to


def get_kube_api():
def get_kube_api(timeout: int):
config = pykube.KubeConfig.from_env()
api = pykube.HTTPClient(config)
api = pykube.HTTPClient(config, timeout=timeout)
return api


Expand Down
3 changes: 1 addition & 2 deletions kube_downscaler/scaler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1357,11 +1357,10 @@ def scale(
enable_events: bool = False,
matching_labels: FrozenSet[Pattern] = frozenset(),
):
api = helper.get_kube_api()
api = helper.get_kube_api(api_server_timeout)

now = datetime.datetime.now(datetime.timezone.utc)
forced_uptime = pods_force_uptime(api, namespaces)
pykube.http.DEFAULT_HTTP_TIMEOUT=api_server_timeout

for clazz in RESOURCE_CLASSES:
plural = clazz.endpoint
Expand Down
35 changes: 35 additions & 0 deletions tests/test_scaler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,41 @@
from kube_downscaler.scaler import scale_down_jobs
from kube_downscaler.scaler import scale_up_jobs

def test_scale_custom_timeout(monkeypatch):
api_server_timeout = 15 # Defined by the user
api = MagicMock()
api.timeout = 15 # Expected timeout

mock_get_kube_api = MagicMock(return_value=api)
monkeypatch.setattr(
"kube_downscaler.scaler.helper.get_kube_api", mock_get_kube_api
)

scale(
namespaces=frozenset({"default"}),
upscale_period="never",
downscale_period="never",
default_uptime="never",
default_downtime="always",
upscale_target_only=False,
include_resources=frozenset(["pods"]),
exclude_namespaces=frozenset(),
exclude_deployments=frozenset(),
dry_run=False,
grace_period=300,
admission_controller="",
constrained_downscaler=False,
api_server_timeout=api_server_timeout,
downtime_replicas=0,
deployment_time_annotation=None,
enable_events=False,
matching_labels=frozenset(),
)

# ensure get_kube_api is called with the correct timeout value
mock_get_kube_api.assert_called_once_with(api_server_timeout)
# ensure timeout value is correctly set on the returned object
assert api.timeout == api_server_timeout

def test_scaler_always_up(monkeypatch):
api = MagicMock()
Expand Down

0 comments on commit e625241

Please sign in to comment.