def test_iterator_escape_whitespaces(self):
        uut = StringConverter("ta, chi, tsu, te, \\ to", list_delimiters=",")
        self.assertEqual(list(uut), ["ta", "chi", "tsu", "te", " to"])

        uut = StringConverter(r"/**, \ *\ , \ */", list_delimiters=",")
        self.assertEqual(list(uut), ["/**", " * ", " */"])

        uut = StringConverter(
            "abc\\\\ , def\\ \\ \\ ,   \\\\ unstrip \\\\\\  ",
            list_delimiters=",")
        self.assertEqual(list(uut), ["abc\\", "def   ", "\\ unstrip \\ "])
Beispiel #2
0
    def __init__(self,
                 key,
                 value,
                 origin='',
                 strip_whitespaces=True,
                 list_delimiters=(',', ';'),
                 from_cli=False,
                 remove_empty_iter_elements=True,
                 to_append=False):
        """
        Initializes a new Setting,

        :param key:                        The key of the Setting.
        :param value:                      The value, if you apply conversions
                                           to this object these will be applied
                                           to this value.
        :param origin:                     The originating file. This will be
                                           used for path conversions and the
                                           last part will be stripped of. If
                                           you want to specify a directory as
                                           origin be sure to end it with a
                                           directory separator.
        :param strip_whitespaces:          Whether to strip whitespaces from
                                           the value or not
        :param list_delimiters:            Delimiters for list conversion
        :param from_cli:                   True if this setting was read by the
                                           CliParser.
        :param remove_empty_iter_elements: Whether to remove empty elements in
                                           iterable values.
        :param to_append:                  The boolean value if setting value
                                           needs to be appended to a setting in
                                           the defaults of a section.
        """
        if not isinstance(from_cli, bool):
            raise TypeError('from_cli needs to be a boolean value.')

        if not isinstance(to_append, bool):
            raise TypeError('to_append needs to be a boolean value.')

        self.to_append = to_append

        StringConverter.__init__(
            self,
            value,
            strip_whitespaces=strip_whitespaces,
            list_delimiters=list_delimiters,
            remove_empty_iter_elements=remove_empty_iter_elements)

        self.from_cli = from_cli
        self.key = key
        self.origin = str(origin)
    def test_url(self):
        valid_urls = (
            # Scheme tests
            "http://url.com", "https://url.com", "url.com", "ftp://url.com",
            "ftps://url.com",
            # Domain tests
            "http://sub.subsub.url.com", "http://sub.url.com",
            "http://url.co.cc", "http://localhost", "http://sub.url123.com",
            "http://url123.co.cc", "http://1.1.1.1",
            "sub.subsub.url.com", "sub.url.com", "url.co.cc", "localhost",
            "1.1.1.1", "255.255.255.255", "url123.com", "url123.co.cc",
            "sub.url123.com",
            # Port number
            "localhost:8888", "1.1.1.1:80", "url.com:123456",
            # Paths
            "url.com/", "url.co.in/", "url.com/path/to/something",
            "url.co.in/path/to/something", "url.com/path/to/file.php")
        invalid_urls = (
            # Invalid types
            123, True, None,
            # Invalid links
            "unknown://url.com", "123", "abcd", "url.unknown",
            "user:[email protected]", "http://unknownlocalhost",
            "local_host/path")

        for url in valid_urls:
            try:
                StringConverter(url).__url__()
            except ValueError as exception:
                print(exception)
                self.fail("URL {} raised ValueError unexpectedly.".format(url))

        for url in invalid_urls:
            self.assertRaises(ValueError, self.uut.__url__)
Beispiel #4
0
    def __extract_keys_and_value(self,
                                 line,
                                 delimiters,
                                 return_second_part_nonempty=False):
        """
        This method extracts the keys and values from the give string by
        splitting them based on the delimiters provided.

        :param line:                        The input string.
        :param delimiters:                  A list of delimiters to split the
                                            strings on.
        :param return_second_part_nonempty: If no delimiter is found and this
                                            is true the contents of the string
                                            will be returned as value
        :return:                            The parsed keys and values from a
                                            line.
        """
        key_part, value = self.__separate_by_first_occurrence(
            line, delimiters, True, return_second_part_nonempty)
        keys = list(
            StringConverter(key_part,
                            list_delimiters=self.key_delimiters).__iter__(
                                remove_backslashes=False))

        return keys, value
 def test_equality_comparision(self):
     self.assertEqual(StringConverter(" i dont know "),
                      StringConverter("i dont know"))
     self.assertNotEqual(StringConverter(" dont know "),
                         StringConverter("i dont know "))
     self.assertNotEqual(StringConverter(""),
                         StringConverter("i dont know "))
     self.assertNotEqual(5, StringConverter("i dont know "))
    def test_dict_escape_whitespaces(self):
        uut = StringConverter(
            "\\  : \\  , hello: \\ world, \\\\ A \\\\ : B\\ ")
        self.assertEqual(dict(uut), {" ": " ",
                                     "hello": " world",
                                     "\\ A \\": "B "})

        uut = StringConverter(r"/**, \ *\ , \ */")
        self.assertEqual(dict(uut), {"/**": "", " * ": "", " */": ""})

        uut = StringConverter("abc\\\\  :    qew, def\\ \\ \\ ,"
                              "   \\\\ unstrip \\\\\\  ")
        self.assertEqual(dict(uut), {"abc\\": "qew",
                                     "def   ": "",
                                     "\\ unstrip \\ ": ""})

        uut = StringConverter("A:B,C  :  D\\x \\a,42:\\n8 ",
                              strip_whitespaces=False)
        self.assertEqual(dict(uut), {"A": "B", "C  ": "  Dx a", "42": "n8 "})
Beispiel #7
0
def typed_list(conversion_func):
    """
    Creates a function that converts a setting into a list of elements each
    converted with the given conversion function.

    :param conversion_func: The conversion function that converts a string into
                            your desired list item object.
    :return:                A conversion function.
    """
    return lambda setting: [
        conversion_func(StringConverter(elem)) for elem in setting]
    def test_iterator_remove_empty_iter_elements(self):
        uut = StringConverter("a, b, c, , e, , g", list_delimiters=",")
        self.assertEqual(list(uut), ["a", "b", "c", "e", "g"])

        uut = StringConverter("a, , ,, e, , g",
                              list_delimiters=",",
                              remove_empty_iter_elements=True)
        self.assertEqual(list(uut), ["a", "e", "g"])

        uut = StringConverter(",,, ,",
                              list_delimiters=",",
                              remove_empty_iter_elements=True)
        self.assertEqual(list(uut), [])

        uut = StringConverter("a, b, c, , e, , g",
                              list_delimiters=",",
                              remove_empty_iter_elements=False)
        self.assertEqual(list(uut), ["a", "b", "c", "", "e", "", "g"])

        uut = StringConverter(",,, ,",
                              list_delimiters=",",
                              remove_empty_iter_elements=False)
        self.assertEqual(list(uut), ["", "", "", "", ""])
Beispiel #9
0
def ask_question(question,
                 default=None,
                 printer: Printer = None,
                 typecast=str,
                 **kwargs):
    """
    Asks the user a question and returns the answer.

    :param question:
        String to be used as question.
    :param default:
        The default answer to be returned if the user gives a void answer
        to the question.
    :param printer:
        The printer object used for console interactions. If this is not
        given, it defaults to a ``ConsolePrinter`` which prints outputs to
        the console.
    :param typecast:
        Type to cast the input to. Defaults to a ``str``.
    :param kwargs:
        The additional keyword arguments are held for backwards compatibility
        and for future use with the ``prompt_toolkit``.
    :return:
        The response from the user.
    """
    if printer is None:
        printer = ConsolePrinter()

    while True:
        printer.print(question, color="yellow", end=" ")
        if default:
            printer.print("[" + default + "]", end=" ")
        printer.print("")

        answer = input()
        if default and len(answer) == 0:
            answer = default

        try:
            answer = typecast(StringConverter(answer))
        except BaseException as e:
            printer.print(
                str(e) + "\nPlease enter a valid answer.",
                color="blue")
        else:
            return answer
 def test_float_conversion(self):
     self.assertEqual(float(self.uut), 1)
     self.uut.value = "0.5 "
     self.assertEqual(float(self.uut), 0.5)
     self.uut = StringConverter(" not a float ")
     self.assertRaises(ValueError, float, self.uut)
    def test_dict_conversion(self):
        self.uut = StringConverter("test")
        self.assertEqual(dict(self.uut), {"test": ""})
        self.uut = StringConverter("test, t")
        self.assertEqual(dict(self.uut), {"test": "", "t": ""})
        self.uut = StringConverter("test, t: v")
        self.assertEqual(dict(self.uut), {"test": "", "t": "v"})

        # Check escaping
        self.uut = StringConverter("test, t\\: v")
        self.assertEqual(dict(self.uut), {"test": "", "t: v": ""})
        self.uut = StringConverter("test, t\\: v: t")
        self.assertEqual(dict(self.uut), {"test": "", "t: v": "t"})
        self.uut = StringConverter("test\\, t\\: v: t")
        self.assertEqual(dict(self.uut), {"test, t: v": "t"})
        self.uut = StringConverter("test\\, t\\: v: t\\,")
        self.assertEqual(dict(self.uut), {"test, t: v": "t,"})

        # Check that lists ignore colons
        self.assertEqual(list(self.uut), ["test, t: v: t,"])
Beispiel #12
0
# condition_dict) and all values to floats while unset values default to 1.
counting_condition_dict = typed_ordered_dict(
    lambda setting: condition_dict[str(setting).lower()],
    float,
    1)

default_cc_dict = counting_condition_dict(StringConverter(
    """
used: 0,
returned: 1.4,
is_condition: 0,
in_condition: 1.4,
in_second_level_condition: 1.4,
in_third_level_condition: 1.0,
is_assignee: 0,
is_assigner: 0.6,
loop_content: 0,
second_level_loop_content,
third_level_loop_content,
is_param: 2,
is_called: 1.4,
is_call_param: 0.0,
in_sum: 2.0,
in_product: 0,
in_binary_operation,
member_accessed"""))


def get_difference(function_pair,
                   count_matrices,
                   average_calculation,
                   poly_postprocessing,
    def test_bool_conversion(self):
        self.assertEqual(bool(self.uut), True)
        self.uut.value = "yeah"
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("y")
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("yep")
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("positive")
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("nope")
        self.assertEqual(bool(self.uut), False)
        self.uut = StringConverter("nop")
        self.assertEqual(bool(self.uut), False)
        self.uut = StringConverter("negative")
        self.assertEqual(bool(self.uut), False)

        self.uut = StringConverter(" i dont know ")
        self.assertRaises(ValueError, bool, self.uut)
    def test_whitespace_stripping(self):
        self.assertEqual(str(self.uut), "1")

        self.uut = StringConverter("\n 1 \n", strip_whitespaces=False)
        self.assertEqual(str(self.uut), "\n 1 \n")
 def setUp(self):
     self.uut = StringConverter("\n \\1 \n ")
class StringConverterTest(unittest.TestCase):

    def setUp(self):
        self.uut = StringConverter("\n \\1 \n ")

    def test_construction(self):
        self.assertRaises(TypeError,
                          StringConverter,
                          "test",
                          strip_whitespaces=5)
        self.assertRaises(TypeError,
                          StringConverter,
                          "test",
                          list_delimiters=5)

    def test_whitespace_stripping(self):
        self.assertEqual(str(self.uut), "1")

        self.uut = StringConverter("\n 1 \n", strip_whitespaces=False)
        self.assertEqual(str(self.uut), "\n 1 \n")

    def test_int_conversion(self):
        self.assertEqual(int(self.uut), 1)
        self.uut = StringConverter(" not an int ")
        self.assertRaises(ValueError, int, self.uut)

    def test_float_conversion(self):
        self.assertEqual(float(self.uut), 1)
        self.uut.value = "0.5 "
        self.assertEqual(float(self.uut), 0.5)
        self.uut = StringConverter(" not a float ")
        self.assertRaises(ValueError, float, self.uut)

    def test_len(self):
        self.assertEqual(len(self.uut), 1)

    def test_iterator(self):
        self.uut = StringConverter("a, test with!!some challenge",
                                   list_delimiters=[",", " ", "!!"])
        self.assertEqual(list(self.uut),
                         ["a", "test", "with", "some", "challenge"])
        self.uut = StringConverter("a\\ \\,\\\\ test with!!some challenge",
                                   list_delimiters=[",", " ", "!!"])
        self.assertEqual(list(self.uut),
                         ["a ,\\", "test", "with", "some", "challenge"])
        self.uut = StringConverter("a, test with!some \\\\\\ challenge\\ ",
                                   list_delimiters=", !",
                                   strip_whitespaces=False)
        self.assertEqual(list(self.uut),
                         ["a", "test", "with", "some", "\\ challenge "])
        self.uut = StringConverter("a, test with!some \\\\\\ challenge\\ ",
                                   list_delimiters=", !",
                                   strip_whitespaces=True)
        self.assertEqual(list(self.uut),
                         ["a", "test", "with", "some", "\\ challenge "])
        self.uut = StringConverter("testval", list_delimiters=[",", "¸"])
        self.uut.value = "a\\n,bug¸g"
        self.assertEqual(list(self.uut), ["an", "bug", "g"])
        self.assertEqual(list(self.uut.__iter__(False)), ["a\\n", "bug", "g"])

        self.assertTrue("bug" in self.uut)
        self.assertFalse("but" in self.uut)

        self.uut = StringConverter("a, test, \n",
                                   list_delimiters=[","],
                                   strip_whitespaces=True)
        self.assertEqual(list(self.uut), ["a", "test"])
        self.uut = StringConverter("a, test, \n",
                                   list_delimiters=[","],
                                   strip_whitespaces=False)
        self.assertEqual(list(self.uut), ["a", " test", " \n"])

        uut = StringConverter("A,B,C  ,  D\\x \\a,42,\\n8 ",
                              strip_whitespaces=False)
        self.assertEqual(list(uut), ["A", "B", "C  ", "  Dx a", "42", "n8 "])

    def test_iterator_escape_whitespaces(self):
        uut = StringConverter("ta, chi, tsu, te, \\ to", list_delimiters=",")
        self.assertEqual(list(uut), ["ta", "chi", "tsu", "te", " to"])

        uut = StringConverter(r"/**, \ *\ , \ */", list_delimiters=",")
        self.assertEqual(list(uut), ["/**", " * ", " */"])

        uut = StringConverter(
            "abc\\\\ , def\\ \\ \\ ,   \\\\ unstrip \\\\\\  ",
            list_delimiters=",")
        self.assertEqual(list(uut), ["abc\\", "def   ", "\\ unstrip \\ "])

    def test_iterator_remove_empty_iter_elements(self):
        uut = StringConverter("a, b, c, , e, , g", list_delimiters=",")
        self.assertEqual(list(uut), ["a", "b", "c", "e", "g"])

        uut = StringConverter("a, , ,, e, , g",
                              list_delimiters=",",
                              remove_empty_iter_elements=True)
        self.assertEqual(list(uut), ["a", "e", "g"])

        uut = StringConverter(",,, ,",
                              list_delimiters=",",
                              remove_empty_iter_elements=True)
        self.assertEqual(list(uut), [])

        uut = StringConverter("a, b, c, , e, , g",
                              list_delimiters=",",
                              remove_empty_iter_elements=False)
        self.assertEqual(list(uut), ["a", "b", "c", "", "e", "", "g"])

        uut = StringConverter(",,, ,",
                              list_delimiters=",",
                              remove_empty_iter_elements=False)
        self.assertEqual(list(uut), ["", "", "", "", ""])

    def test_dict_escape_whitespaces(self):
        uut = StringConverter(
            "\\  : \\  , hello: \\ world, \\\\ A \\\\ : B\\ ")
        self.assertEqual(dict(uut), {" ": " ",
                                     "hello": " world",
                                     "\\ A \\": "B "})

        uut = StringConverter(r"/**, \ *\ , \ */")
        self.assertEqual(dict(uut), {"/**": "", " * ": "", " */": ""})

        uut = StringConverter("abc\\\\  :    qew, def\\ \\ \\ ,"
                              "   \\\\ unstrip \\\\\\  ")
        self.assertEqual(dict(uut), {"abc\\": "qew",
                                     "def   ": "",
                                     "\\ unstrip \\ ": ""})

        uut = StringConverter("A:B,C  :  D\\x \\a,42:\\n8 ",
                              strip_whitespaces=False)
        self.assertEqual(dict(uut), {"A": "B", "C  ": "  Dx a", "42": "n8 "})

    def test_dict_conversion(self):
        self.uut = StringConverter("test")
        self.assertEqual(dict(self.uut), {"test": ""})
        self.uut = StringConverter("test, t")
        self.assertEqual(dict(self.uut), {"test": "", "t": ""})
        self.uut = StringConverter("test, t: v")
        self.assertEqual(dict(self.uut), {"test": "", "t": "v"})

        # Check escaping
        self.uut = StringConverter("test, t\\: v")
        self.assertEqual(dict(self.uut), {"test": "", "t: v": ""})
        self.uut = StringConverter("test, t\\: v: t")
        self.assertEqual(dict(self.uut), {"test": "", "t: v": "t"})
        self.uut = StringConverter("test\\, t\\: v: t")
        self.assertEqual(dict(self.uut), {"test, t: v": "t"})
        self.uut = StringConverter("test\\, t\\: v: t\\,")
        self.assertEqual(dict(self.uut), {"test, t: v": "t,"})

        # Check that lists ignore colons
        self.assertEqual(list(self.uut), ["test, t: v: t,"])

    def test_bool_conversion(self):
        self.assertEqual(bool(self.uut), True)
        self.uut.value = "yeah"
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("y")
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("yep")
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("positive")
        self.assertEqual(bool(self.uut), True)
        self.uut = StringConverter("nope")
        self.assertEqual(bool(self.uut), False)
        self.uut = StringConverter("nop")
        self.assertEqual(bool(self.uut), False)
        self.uut = StringConverter("negative")
        self.assertEqual(bool(self.uut), False)

        self.uut = StringConverter(" i dont know ")
        self.assertRaises(ValueError, bool, self.uut)

    def test_equality_comparision(self):
        self.assertEqual(StringConverter(" i dont know "),
                         StringConverter("i dont know"))
        self.assertNotEqual(StringConverter(" dont know "),
                            StringConverter("i dont know "))
        self.assertNotEqual(StringConverter(""),
                            StringConverter("i dont know "))
        self.assertNotEqual(5, StringConverter("i dont know "))

    def test_url(self):
        valid_urls = (
            # Scheme tests
            "http://url.com", "https://url.com", "url.com", "ftp://url.com",
            "ftps://url.com",
            # Domain tests
            "http://sub.subsub.url.com", "http://sub.url.com",
            "http://url.co.cc", "http://localhost", "http://sub.url123.com",
            "http://url123.co.cc", "http://1.1.1.1",
            "sub.subsub.url.com", "sub.url.com", "url.co.cc", "localhost",
            "1.1.1.1", "255.255.255.255", "url123.com", "url123.co.cc",
            "sub.url123.com",
            # Port number
            "localhost:8888", "1.1.1.1:80", "url.com:123456",
            # Paths
            "url.com/", "url.co.in/", "url.com/path/to/something",
            "url.co.in/path/to/something", "url.com/path/to/file.php")
        invalid_urls = (
            # Invalid types
            123, True, None,
            # Invalid links
            "unknown://url.com", "123", "abcd", "url.unknown",
            "user:[email protected]", "http://unknownlocalhost",
            "local_host/path")

        for url in valid_urls:
            try:
                StringConverter(url).__url__()
            except ValueError as exception:
                print(exception)
                self.fail("URL {} raised ValueError unexpectedly.".format(url))

        for url in invalid_urls:
            self.assertRaises(ValueError, self.uut.__url__)
 def test_int_conversion(self):
     self.assertEqual(int(self.uut), 1)
     self.uut = StringConverter(" not an int ")
     self.assertRaises(ValueError, int, self.uut)
Beispiel #18
0
 def __iter__(self, remove_backslashes=True):
     if self.to_append:
         raise ValueError('Iteration on this object is invalid because the '
                          'value is incomplete. Please access the value of '
                          'the setting in a section to iterate through it.')
     return StringConverter.__iter__(self, remove_backslashes)
    def test_iterator(self):
        self.uut = StringConverter("a, test with!!some challenge",
                                   list_delimiters=[",", " ", "!!"])
        self.assertEqual(list(self.uut),
                         ["a", "test", "with", "some", "challenge"])
        self.uut = StringConverter("a\\ \\,\\\\ test with!!some challenge",
                                   list_delimiters=[",", " ", "!!"])
        self.assertEqual(list(self.uut),
                         ["a ,\\", "test", "with", "some", "challenge"])
        self.uut = StringConverter("a, test with!some \\\\\\ challenge\\ ",
                                   list_delimiters=", !",
                                   strip_whitespaces=False)
        self.assertEqual(list(self.uut),
                         ["a", "test", "with", "some", "\\ challenge "])
        self.uut = StringConverter("a, test with!some \\\\\\ challenge\\ ",
                                   list_delimiters=", !",
                                   strip_whitespaces=True)
        self.assertEqual(list(self.uut),
                         ["a", "test", "with", "some", "\\ challenge "])
        self.uut = StringConverter("testval", list_delimiters=[",", "¸"])
        self.uut.value = "a\\n,bug¸g"
        self.assertEqual(list(self.uut), ["an", "bug", "g"])
        self.assertEqual(list(self.uut.__iter__(False)), ["a\\n", "bug", "g"])

        self.assertTrue("bug" in self.uut)
        self.assertFalse("but" in self.uut)

        self.uut = StringConverter("a, test, \n",
                                   list_delimiters=[","],
                                   strip_whitespaces=True)
        self.assertEqual(list(self.uut), ["a", "test"])
        self.uut = StringConverter("a, test, \n",
                                   list_delimiters=[","],
                                   strip_whitespaces=False)
        self.assertEqual(list(self.uut), ["a", " test", " \n"])

        uut = StringConverter("A,B,C  ,  D\\x \\a,42,\\n8 ",
                              strip_whitespaces=False)
        self.assertEqual(list(uut), ["A", "B", "C  ", "  Dx a", "42", "n8 "])