From 148b8f15d02daba3f66057d7917082cdefde212e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20F=C3=A4hrmann?= Date: Thu, 14 Feb 2019 11:15:19 +0100 Subject: [PATCH] update tests for util.py --- gallery_dl/util.py | 10 ++++++---- test/test_util.py | 37 +++++++++++++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/gallery_dl/util.py b/gallery_dl/util.py index ccd5d55f..2ec28f14 100644 --- a/gallery_dl/util.py +++ b/gallery_dl/util.py @@ -75,9 +75,9 @@ def transform_dict(a, func): a[key] = func(value) -def number_to_string(value): +def number_to_string(value, numbers=(int, float)): """Convert numbers (int, float) to string; Return everything else as is.""" - return str(value) if isinstance(value, (int, float)) else value + return str(value) if value.__class__ in numbers else value def expand_path(path): @@ -141,8 +141,10 @@ SPECIAL_EXTRACTORS = {"oauth", "recursive", "test"} class UniversalNone(): - """None-style object that also supports __getattr__ and __getitem__""" - def __getattr__(self, _): + """None-style object that supports more operations than None itself""" + __slots__ = () + + def __getattribute__(self, _): return self def __getitem__(self, _): diff --git a/test/test_util.py b/test/test_util.py index 2a1909c0..d6c5f9f2 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -8,12 +8,12 @@ # published by the Free Software Foundation. import unittest -import gallery_dl.util as util -import gallery_dl.exception as exception import sys import random import string +from gallery_dl import util, text, exception + class TestRange(unittest.TestCase): @@ -309,6 +309,39 @@ class TestOther(unittest.TestCase): {1: {2: {3: {4: {"1": "A", "3": "C"}}}}}), {1: {2: {3: {4: {"1": "A", "2": "b", "3": "C"}}}}}) + def test_transform_dict(self): + d = {} + util.transform_dict(d, str) + self.assertEqual(d, {}) + + d = {1: 123, 2: "123", 3: True, 4: None} + util.transform_dict(d, str) + self.assertEqual( + d, {1: "123", 2: "123", 3: "True", 4: "None"}) + + d = {1: 123, 2: "123", 3: "foo", 4: {11: 321, 12: "321", 13: "bar"}} + util.transform_dict(d, text.parse_int) + self.assertEqual( + d, {1: 123, 2: 123, 3: 0, 4: {11: 321, 12: 321, 13: 0}}) + + def test_number_to_string(self, f=util.number_to_string): + self.assertEqual(f(1) , "1") + self.assertEqual(f(1.0) , "1.0") + self.assertEqual(f("1.0") , "1.0") + self.assertEqual(f([1]) , [1]) + self.assertEqual(f({1: 2}), {1: 2}) + self.assertEqual(f(True) , True) + self.assertEqual(f(None) , None) + + def test_universal_none(self): + obj = util.NONE + + self.assertFalse(obj) + self.assertEqual(str(obj), str(None)) + self.assertEqual(repr(obj), repr(None)) + self.assertIs(obj.attr, obj) + self.assertIs(obj["key"], obj) + if __name__ == '__main__': unittest.main()