From 66f0eab42fca2886b866fd31ad254acecc9a228f Mon Sep 17 00:00:00 2001 From: Philipp Spitzer Date: Tue, 15 Mar 2022 22:12:53 +0100 Subject: [PATCH] Create function optional_set. --- tests/test_lib_sledrun_wikitext_to_json.py | 16 +++++++++++++++- wrpylib/lib_sledrun_wikitext_to_json.py | 6 ++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/test_lib_sledrun_wikitext_to_json.py b/tests/test_lib_sledrun_wikitext_to_json.py index afbc25d..72c7c31 100644 --- a/tests/test_lib_sledrun_wikitext_to_json.py +++ b/tests/test_lib_sledrun_wikitext_to_json.py @@ -2,7 +2,21 @@ import unittest from mwparserfromhell import parse -from wrpylib.lib_sledrun_wikitext_to_json import get_sledrun_description +from wrpylib.lib_sledrun_wikitext_to_json import get_sledrun_description, optional_set + + +class TestOptionalSet(unittest.TestCase): + def test_optional_set_string(self): + h = {'a': 3} + optional_set(h, 'b', 5) + expected = {'a': 3, 'b': 5} + self.assertDictEqual(expected, h) + + def test_optional_set_none(self): + h = {'a': 3} + expected = h.copy() + optional_set(h, 'b', None) + self.assertDictEqual(expected, h) class TestGetSledrunDescription(unittest.TestCase): diff --git a/wrpylib/lib_sledrun_wikitext_to_json.py b/wrpylib/lib_sledrun_wikitext_to_json.py index 541551e..4fffb55 100644 --- a/wrpylib/lib_sledrun_wikitext_to_json.py +++ b/wrpylib/lib_sledrun_wikitext_to_json.py @@ -5,6 +5,12 @@ from mwparserfromhell.nodes import Template, Text, Tag from mwparserfromhell.wikicode import Wikicode +def optional_set(haystack: dict, key: str, value: Optional[Any]): + """Sets the key to value in haystack only if value is not None""" + if value is not None: + haystack[key] = value + + def get_sledrun_description(sledrun: Wikicode) -> Optional[str]: """Get description from sledrun""" for v in sledrun.get_sections(levels=[2], matches='Allgemeines', include_headings=False): -- 2.39.5