Skip to content

Commit

Permalink
modules/interface: Add routes() function
Browse files Browse the repository at this point in the history
Returns the routes associated with the interface, optionally filtered by scope
(`host`, `link` or `global`).

Signed-off-by: Benoît Knecht <bknecht@protonmail.ch>
  • Loading branch information
BenoitKnecht authored and philpep committed May 19, 2023
1 parent b545297 commit ca0f8bd
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions testinfra/modules/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import json

from testinfra.modules.base import Module
from testinfra.utils import cached_property

Expand Down Expand Up @@ -48,6 +50,26 @@ def addresses(self):
"""
raise NotImplementedError

def routes(self, scope=None):
"""Return the routes associated with the interface, optionally filtered by scope
("host", "link" or "global").
>>> host.interface("eth0").routes()
[{'dst': 'default',
'flags': [],
'gateway': '192.0.2.1',
'metric': 3003,
'prefsrc': '192.0.2.5',
'protocol': 'dhcp'},
{'dst': '192.0.2.0/24',
'flags': [],
'metric': 3003,
'prefsrc': '192.0.2.5',
'protocol': 'dhcp',
'scope': 'link'}]
"""
raise NotImplementedError

def __repr__(self):
return "<interface {}>".format(self.name)

Expand Down Expand Up @@ -109,6 +131,16 @@ def addresses(self):
addrs.append(splitted[1].split("/", 1)[0])
return addrs

def routes(self, scope=None):
cmd = f"{self._ip} --json route list dev %s"

if scope is None:
out = self.check_output(cmd, self.name)
else:
out = self.check_output(cmd + " scope %s", self.name, scope)

return json.loads(out)

@classmethod
def default(cls, family=None):
_default = cls(None, family=family)
Expand Down

0 comments on commit ca0f8bd

Please sign in to comment.