Fix error on missing labels

It seems a container can have "null" Labels so we need to handle that
case.
This commit is contained in:
Matthew Mead-Briggs 2019-04-24 07:46:23 -07:00
parent e66fb295f4
commit 0d48a757ef
2 changed files with 30 additions and 17 deletions

View File

@ -76,21 +76,25 @@ def filter_excluded_containers(containers, exclude_container_labels):
def should_exclude_container_with_labels(container, exclude_container_labels): def should_exclude_container_with_labels(container, exclude_container_labels):
for exclude_label in exclude_container_labels: if container['Labels']:
if exclude_label.value: for exclude_label in exclude_container_labels:
matching_keys = fnmatch.filter( if exclude_label.value:
container['Labels'].keys(), matching_keys = fnmatch.filter(
exclude_label.key, container['Labels'].keys(),
) exclude_label.key,
label_values_to_check = [ )
container['Labels'][matching_key] label_values_to_check = [
for matching_key in matching_keys container['Labels'][matching_key]
] for matching_key in matching_keys
if fnmatch.filter(label_values_to_check, exclude_label.value): ]
return True if fnmatch.filter(label_values_to_check, exclude_label.value):
else: return True
if fnmatch.filter(container['Labels'].keys(), exclude_label.key): else:
return True if fnmatch.filter(
container['Labels'].keys(),
exclude_label.key
):
return True
return False return False

View File

@ -75,6 +75,7 @@ def test_filter_excluded_containers():
{'Labels': {'too': 'lol'}}, {'Labels': {'too': 'lol'}},
{'Labels': {'toots': 'lol'}}, {'Labels': {'toots': 'lol'}},
{'Labels': {'foo': 'bar'}}, {'Labels': {'foo': 'bar'}},
{'Labels': None},
] ]
result = docker_gc.filter_excluded_containers(mock_containers, None) result = docker_gc.filter_excluded_containers(mock_containers, None)
assert mock_containers == list(result) assert mock_containers == list(result)
@ -86,7 +87,11 @@ def test_filter_excluded_containers():
mock_containers, mock_containers,
exclude_labels, exclude_labels,
) )
assert [mock_containers[0], mock_containers[2]] == list(result) assert [
mock_containers[0],
mock_containers[2],
mock_containers[4]
] == list(result)
exclude_labels = [ exclude_labels = [
docker_gc.ExcludeLabel(key='too*', value='lol'), docker_gc.ExcludeLabel(key='too*', value='lol'),
] ]
@ -94,7 +99,11 @@ def test_filter_excluded_containers():
mock_containers, mock_containers,
exclude_labels, exclude_labels,
) )
assert [mock_containers[0], mock_containers[3]] == list(result) assert [
mock_containers[0],
mock_containers[3],
mock_containers[4]
] == list(result)
def test_cleanup_images(mock_client, now): def test_cleanup_images(mock_client, now):