Skip to content

Commit

Permalink
Add an SSHConfig dict to provide type conversion helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
offbyone committed May 16, 2018
1 parent 413bf37 commit 2bc6862
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
26 changes: 26 additions & 0 deletions paramiko/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
Configuration file (aka ``ssh_config``) support.
"""

import collections
import fnmatch
import os
import re
Expand Down Expand Up @@ -295,3 +296,28 @@ def __str__(self):
# Cache
self.fqdn = fqdn
return self.fqdn


class SSHConfigDict(collections.UserDict):
"""A dictionary wrapper for ssh host configurations.
This class introduces some usage niceties for consumers of SSHConfig,
specifically around the issue of variable type conversions. This offers
as_bool(key) and as_int(key) for the current raw string values in
SSHConfig"""

def __init__(self, initialdata=None):
super(SSHConfigDict, self).__init__(initialdata)

def as_bool(self, key):
"""Express the key as a boolean value. Variations on 'yes' or boolean values
are accepted."""
val = self[key]
if isinstance(val, bool):
return val
return val.lower() == 'yes'

def as_int(self, key):
"""Express the key as a true integer, if possible. Raises an Error otherwise
(following conventional int conversion rules)"""
return int(self[key])
45 changes: 45 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# This file is part of Paramiko and subject to the license in /LICENSE in this
# repository

import pytest
from paramiko import config


def test_SSHConfigDict_construct_empty():
assert not config.SSHConfigDict()


def test_SSHConfigDict_construct_from_list():
assert config.SSHConfigDict([(1, 2)])[1] == 2


def test_SSHConfigDict_construct_from_dict():
assert config.SSHConfigDict({1: 2})[1] == 2


@pytest.mark.parametrize("true_ish", ("yes", "YES", "Yes", True))
def test_SSHConfigDict_as_bool_true_ish(true_ish):
assert config.SSHConfigDict({"key": true_ish}).as_bool("key") is True


@pytest.mark.parametrize("false_ish", ("no", "NO", "No", False))
def test_SSHConfigDict_as_bool(false_ish):
assert config.SSHConfigDict({"key": false_ish}).as_bool("key") is False


@pytest.mark.parametrize("int_val", ("42", 42))
def test_SSHConfigDict_as_int(int_val):
assert config.SSHConfigDict({"key": int_val}).as_int("key") == 42


@pytest.mark.parametrize("non_int", ("not an int", None, object()))
def test_SSHConfigDict_as_int_failures(non_int):
conf = config.SSHConfigDict({"key": non_int})

try:
int(non_int)
except Exception as e:
exception_type = type(e)

with pytest.raises(exception_type):
conf.as_int("key")

0 comments on commit 2bc6862

Please sign in to comment.