Verified Commit 02db2708 authored by Štěpán Henek's avatar Štěpán Henek 🐻

euci: add support for ip address parsing

Note that user can use dtype=IPv6Address or dtype=IPv4Address
the result will be IPv4Address or IPv6Address regardless of dtype
settings.
parent 69ef007a
Pipeline #65961 passed with stages
in 49 seconds
# Copyright (c) 2019, CZ.NIC, z.s.p.o. (http://www.nic.cz/)
# Copyright (c) 2020, CZ.NIC, z.s.p.o. (http://www.nic.cz/)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
......@@ -23,6 +23,7 @@
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import collections
import ipaddress
from uci import Uci, UciExceptionNotFound
from . import boolean
......@@ -41,13 +42,15 @@ class EUci(Uci):
def _get(value, dtype):
if dtype == str:
return value
if dtype == bool:
elif dtype == bool:
value = value.lower()
if value not in boolean.VALUES:
raise ValueError("invalid value '{}' for bool type".format(value))
return boolean.VALUES[value]
if dtype == int:
elif dtype == int:
return int(value)
elif dtype in (ipaddress.IPv4Address, ipaddress.IPv6Address):
return ipaddress.ip_address(value)
raise TypeError("'{}' is not supported type of data".format(dtype))
def get(self, *args, dtype=str, **kwargs):
......
# Copyright 2019, CZ.NIC z.s.p.o. (http://www.nic.cz/)
# Copyright 2020, CZ.NIC z.s.p.o. (http://www.nic.cz/)
#
# This file is part of the PyUCI.
#
......@@ -17,6 +17,8 @@
import pytest
import euci
from ipaddress import IPv4Address, IPv6Address
def test_get_string(tmpdir):
'Test get for no dtype (string in default)'
......@@ -172,3 +174,28 @@ config testing 'testing'
assert not u.get('test', 'testing', 'option', dtype=bool, list=False)
assert u.get('test', 'testing', 'list', dtype=bool, list=True) == (False, True)
assert not u.get('test', 'testing', 'list', dtype=bool, list=False)
def test_ip_address_type(tmpdir):
'Test ip address type'
tmpdir.join('test').write(
"""
config testing 'testing'
option option '0'
option one '192.168.1.1'
option two '::1'
list three '::2'
list three '10.0.0.1'
"""
)
with euci.EUci(confdir=tmpdir.strpath) as u:
assert u.get('test', 'testing', 'one', dtype=IPv4Address) == IPv4Address('192.168.1.1')
assert u.get('test', 'testing', 'one', dtype=IPv6Address) == IPv4Address('192.168.1.1')
assert u.get('test', 'testing', 'two', dtype=IPv4Address) == IPv6Address('::1')
assert u.get('test', 'testing', 'two', dtype=IPv6Address) == IPv6Address('::1')
assert u.get('test', 'testing', 'three', dtype=IPv4Address, list=True) == (
IPv6Address('::2'), IPv4Address('10.0.0.1')
)
assert u.get('test', 'testing', 'three', dtype=IPv6Address, list=True) == (
IPv6Address('::2'), IPv4Address('10.0.0.1')
)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment