swig: Add iterator for config options for python

Resolves: https://github.com/rpm-software-management/dnf5/issues/1579
This commit is contained in:
Pavla Kratochvilova 2025-06-16 16:13:57 +02:00
parent 2282ae41a5
commit 4a83440cb4
4 changed files with 52 additions and 0 deletions

View File

@ -151,5 +151,29 @@ create_config_option_attributes(ConfigMain)
%}
#endif
// The following adds a config options iterator in Python.
//
%define add_config_iterator(ClassName)
#if defined(SWIGPYTHON)
%pythoncode %{
import re
def ClassName##__iter__(self):
options = {}
for attr in dir(ClassName):
option_getter_match = re.search(r'get_(\w+)_option', attr)
if option_getter_match:
option_name = option_getter_match.group(1)
options[option_name] = self.__getattribute__('get_{}_option'.format(option_name))()
return iter(options.items())
ClassName.__iter__ = ClassName##__iter__
del ClassName##__iter__
%}
#endif
%enddef
add_config_iterator(ConfigMain)
// Deletes any previously defined catches
%catches();

View File

@ -169,6 +169,8 @@ add_iterator(SetRepoWeakPtr)
%pythoncode %{
conf.create_config_option_attributes(ConfigRepo)
%}
// Add configuration options iterator for Python.
add_config_iterator(ConfigRepo)
#endif
// Add attributes for getters/setters in Python.

View File

@ -86,3 +86,15 @@ class TestConfigurationOptions(base_test_case.BaseTestCase):
def test_get_unknown_option_by_attribute(self):
config = self.base.get_config()
self.assertRaises(AttributeError, lambda: config.xyz)
def test_iterate_options(self):
config = self.base.get_config()
config.proxy = 'abcd'
proxy_option = None
for name, option in config:
if name == 'proxy':
proxy_option = (name, option.get_value())
self.assertEqual(proxy_option, ('proxy', 'abcd'))

View File

@ -106,3 +106,17 @@ class TestRepo(base_test_case.BaseTestCase):
self.assertEqual(dl_cbs.fastest_mirror_cnt, 0)
self.assertEqual(dl_cbs.handle_mirror_failure_cnt, 0)
self.assertEqual(cbs.repokey_import_cnt, 0)
def test_iterate_config_options(self):
repoid = "repomd-repo1"
repo = self.add_repo_repomd(repoid, load=False)
config = repo.get_config()
config.proxy = 'abcd'
proxy_option = None
for name, option in config:
if name == 'proxy':
proxy_option = (name, option.get_value())
self.assertEqual(proxy_option, ('proxy', 'abcd'))