Skip to content

Commit

Permalink
Handle unknown config fields gracefully (#126)
Browse files Browse the repository at this point in the history
  • Loading branch information
epwalsh authored Jun 13, 2022
1 parent 0f43f3b commit 21fea35
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Fixed

- Fixed bug in loading config where encountering unknown fields would cause an exception.
`beaker-py` now gracefully handles this.

## [v1.4.1](https://github.com/allenai/beaker-py/releases/tag/v1.4.1) - 2022-06-10

### Added
Expand Down
18 changes: 17 additions & 1 deletion beaker/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import os
import warnings
from dataclasses import asdict, dataclass, fields
from pathlib import Path
from typing import ClassVar, Optional
Expand Down Expand Up @@ -44,6 +45,11 @@ class Config:
Default Beaker workspace to use.
"""

default_image: Optional[str] = None
"""
The default image used for interactive sessions.
"""

ADDRESS_KEY: ClassVar[str] = "BEAKER_ADDR"
CONFIG_PATH_KEY: ClassVar[str] = "BEAKER_CONFIG"
TOKEN_KEY: ClassVar[str] = "BEAKER_TOKEN"
Expand Down Expand Up @@ -102,7 +108,17 @@ def from_path(cls, path: Path) -> "Config":
"""
with open(path) as config_file:
logger.debug("Loading beaker config from '%s'", path)
return cls(**yaml.load(config_file, Loader=yaml.SafeLoader))
field_names = {f.name for f in fields(cls)}
data = yaml.load(config_file, Loader=yaml.SafeLoader)
for key in list(data.keys()):
if key not in field_names:
del data[key]
warnings.warn(
f"Unknown field '{key}' found in config '{path}'. "
f"If this is a bug, please report it at https://github.com/allenai/beaker-py/issues/new/",
RuntimeWarning,
)
return cls(**data)

def save(self, path: Optional[Path] = None):
"""
Expand Down
13 changes: 13 additions & 0 deletions tests/config_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import pytest
import yaml

from beaker import Beaker
from beaker.config import Config


def test_str_method(client: Beaker):
assert "user_token=***" in str(client.config)
assert client.config.user_token not in str(client.config)


def test_config_from_path_unknown_field(tmp_path):
path = tmp_path / "config.yml"
with open(path, "w") as f:
yaml.dump({"user_token": "foo-bar", "baz": 1}, f)

with pytest.warns(RuntimeWarning, match="Unknown field 'baz' found in config"):
Config.from_path(path)

0 comments on commit 21fea35

Please sign in to comment.