Skip to content

Commit dee33d7

Browse files
committed
Rearranged tests and added some new ones.
1 parent ee43215 commit dee33d7

File tree

4 files changed

+221
-66
lines changed

4 files changed

+221
-66
lines changed

domdf_python_tools/utils.py

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535

3636
def as_text(value: Any) -> str:
3737
"""
38-
Convert the given value to a string.
38+
Convert the given value to a string. ``None`` is converted to ``''``.
3939
4040
:param value: Value to convert to a string
4141
@@ -126,7 +126,7 @@ def list2str(the_list: Iterable, sep: str = ",") -> str:
126126
return sep.join([str(x) for x in the_list])
127127

128128

129-
list2string = list2str
129+
tuple2str = list2string = list2str
130130

131131

132132
def permutations(data: Iterable[Any], n: int = 2) -> List[Tuple[Any]]:
@@ -206,16 +206,3 @@ def str2tuple(input_string: str, sep: str = ",") -> Tuple[int]:
206206

207207
return tuple(int(x) for x in input_string.split(sep))
208208

209-
210-
def tuple2str(input_tuple: Iterable[Any], sep: str = ",") -> str:
211-
"""
212-
Convert an iterable, such as a tuple into a comma-separated string.
213-
214-
:param input_tuple: The iterable to be joined into a string
215-
:param sep: The separator in the string. Default `,`
216-
:type sep: str
217-
218-
:rtype: str
219-
"""
220-
221-
return sep.join([str(x) for x in input_tuple])

tests/test_bases.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,17 @@
77
88
"""
99

10+
# stdlib
1011
import copy
1112
import pickle
13+
from collections import UserList
1214

15+
# 3rd party
1316
import pytest
1417

15-
from domdf_python_tools.bases import Dictable
18+
# this package
19+
from domdf_python_tools.bases import Dictable, namedlist
20+
from domdf_python_tools.utils import printr, printt
1621

1722

1823
class Person(Dictable):
@@ -90,3 +95,23 @@ def test_subclass(self):
9095
child = Child("Bob", 12, "Big School")
9196
assert person == child
9297
assert "School" not in person.__dict__
98+
99+
100+
def test_namedlist(capsys):
101+
mylist = namedlist()
102+
assert isinstance(mylist(), UserList)
103+
104+
ShoppingList = namedlist("ShoppingList")
105+
shopping_list = ShoppingList(["egg and bacon", "egg sausage and bacon", "egg and spam", "egg bacon and spam"])
106+
assert isinstance(shopping_list, UserList)
107+
assert shopping_list[0] == "egg and bacon"
108+
109+
printt(shopping_list)
110+
printr(shopping_list)
111+
print(shopping_list)
112+
113+
captured = capsys.readouterr()
114+
stdout = captured.out.split("\n")
115+
assert stdout[0] == "<class 'domdf_python_tools.bases.namedlist.<locals>.NamedList'>"
116+
assert stdout[1] == "['egg and bacon', 'egg sausage and bacon', 'egg and spam', 'egg bacon and spam']"
117+
assert stdout[2] == "ShoppingList['egg and bacon', 'egg sausage and bacon', 'egg and spam', 'egg bacon and spam']"

tests/test_paths.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,17 @@
88
"""
99

1010
# stdlib
11+
import contextlib
1112
import pathlib
1213
from tempfile import TemporaryDirectory
1314

15+
# 3rd party
16+
import pytest
17+
1418
# this package
1519
from domdf_python_tools import paths
1620

21+
1722
# TODO: Still need tests for copytree, relpath, relpath2, delete, write,
1823
# read and append.
1924
# Some of those might want deprecating in favour of pathlib
@@ -62,3 +67,51 @@ def test_parent_path():
6267
assert paths.parent_path(dir2) == dir1
6368
assert paths.parent_path(dir3) == dir2
6469
assert str(paths.parent_path("spam/spam/spam")) == "spam/spam"
70+
71+
72+
@pytest.mark.parametrize("relto, relpath", [
73+
("/home/username/Documents/games/chess.py", "/home/username/Documents/letter.doc"),
74+
("/home/username/Documents", "letter.doc"),
75+
(pathlib.Path("/home/username/Documents/games/chess.py"), "/home/username/Documents/letter.doc"),
76+
(pathlib.Path("/home/username/Documents"), "letter.doc"),
77+
])
78+
def test_relpath(relto, relpath):
79+
path = "/home/username/Documents/letter.doc"
80+
assert paths.relpath(path, relative_to=relto) == pathlib.Path(relpath)
81+
assert isinstance(paths.relpath(path, relative_to=relto), pathlib.Path)
82+
83+
84+
class TestCurrentDirOperations:
85+
def test_append(self):
86+
file = pathlib.Path("paths_append_test_file.txt")
87+
file.write_text("initial content\n")
88+
paths.append("appended content", str(file))
89+
assert file.read_text() == "initial content\nappended content"
90+
file.unlink()
91+
92+
def test_delete(self):
93+
file = pathlib.Path("paths_delete_test_file.txt")
94+
file.write_text("initial content\n")
95+
paths.delete(str(file))
96+
assert not file.exists()
97+
98+
def test_read(self):
99+
file = pathlib.Path("paths_read_test_file.txt")
100+
file.write_text("initial content\n")
101+
assert paths.read(str(file)) == "initial content\n"
102+
file.unlink()
103+
104+
def test_write(self):
105+
file = pathlib.Path("paths_write_test_file.txt")
106+
file.write_text("initial content\n")
107+
paths.write("overwritten content", str(file))
108+
assert paths.read(str(file)) == "overwritten content"
109+
file.unlink()
110+
111+
@classmethod
112+
def teardown_class(cls):
113+
with contextlib.suppress(FileNotFoundError):
114+
pathlib.Path("paths_append_test_file.txt").unlink()
115+
pathlib.Path("paths_delete_test_file.txt").unlink()
116+
pathlib.Path("paths_read_test_file.txt").unlink()
117+
pathlib.Path("paths_write_test_file.txt").unlink()

tests/test_utils.py

Lines changed: 140 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -21,68 +21,87 @@ def test_pyversion():
2121
assert isinstance(pyversion, int)
2222

2323

24-
def test_str2tuple():
25-
assert isinstance(str2tuple("1,2,3"), tuple) # tests without spaces
26-
assert isinstance(str2tuple("1, 2, 3"), tuple) # tests with spaces
27-
assert isinstance(str2tuple("1; 2; 3", sep=";"), tuple) # tests with semicolon
28-
assert str2tuple("1,2,3") == (1, 2, 3)
29-
30-
31-
def test_tuple2str():
32-
assert isinstance(tuple2str(("1", "2", "3")), str)
33-
assert tuple2str((1, 2, 3)) == "1,2,3"
34-
35-
assert isinstance(tuple2str((1, 2, 3), sep=";"), str) # tests with semicolon
36-
assert tuple2str((1, 2, 3), sep=";") == "1;2;3"
24+
@pytest.mark.parametrize("value, expects", [
25+
(12345, "12345"),
26+
(123.45, "123.45"),
27+
([123.45], "[123.45]"),
28+
({123.45}, "{123.45}"),
29+
((123.45, ), "(123.45,)"),
30+
(None, ""),
31+
(pathlib.Path("."), "."),
32+
(decimal.Decimal("1234"), "1234"),
33+
])
34+
def test_as_text(value, expects):
35+
assert utils.as_text(value) == expects
36+
37+
38+
def test_check_dependencies(capsys):
39+
deps = ["pytest", "domdf_python_tools", "madeup_module"]
40+
41+
missing_deps = utils.check_dependencies(deps, False)
42+
assert isinstance(missing_deps, list)
43+
assert len(missing_deps) == 1
44+
assert missing_deps == ["madeup_module"]
45+
46+
missing_deps = utils.check_dependencies(deps)
47+
captured = capsys.readouterr()
48+
stdout = captured.out.split("\n")
49+
assert stdout[0] == "The following modules are missing."
50+
assert stdout[1] == "['madeup_module']"
51+
assert stdout[2] == "Please check the documentation."
52+
assert stdout[3] == ""
53+
assert isinstance(missing_deps, list)
54+
assert len(missing_deps) == 1
55+
assert missing_deps == ["madeup_module"]
56+
57+
missing_deps = utils.check_dependencies(["pytest"])
58+
captured = capsys.readouterr()
59+
stdout = captured.out.split("\n")
60+
assert stdout[0] == "All modules installed"
61+
assert stdout[1] == ""
62+
assert isinstance(missing_deps, list)
63+
assert len(missing_deps) == 0
64+
assert missing_deps == []
3765

3866

3967
def test_chunks():
4068
assert isinstance(chunks(list(range(100)), 5), types.GeneratorType)
4169
assert list(chunks(list(range(100)), 5))[0] == [0, 1, 2, 3, 4]
70+
assert list(chunks(["a", "b", "c"], 1)) == [["a"], ["b"], ["c"]]
4271

43-
44-
def test_list2str():
45-
assert isinstance(list2str([1, 2, 3]), str)
46-
assert list2str([1, 2, 3]) == "1,2,3"
47-
48-
assert isinstance(list2str([1, 2, 3], sep=";"), str) # tests with semicolon
49-
assert list2str((1, 2, 3), sep=";") == "1;2;3"
50-
51-
assert isinstance(list2string([1, 2, 3]), str)
52-
assert list2string([1, 2, 3]) == "1,2,3"
53-
54-
assert isinstance(list2string([1, 2, 3], sep=";"), str) # tests with semicolon
55-
assert list2string((1, 2, 3), sep=";") == "1;2;3"
72+
# TODO: cmp
5673

5774

58-
#
59-
#
60-
# def test_bdict_errors():
61-
# new_dict = bdict([("Key1", "Value1"), ("Key2", "Value2"), ("Key3", "Value3")])
62-
#
63-
# with pytest.raises(ValueError):
64-
# new_dict["Key1"] = 1234
65-
# with pytest.raises(ValueError):
66-
# new_dict["Value1"] = 1234
67-
# new_dict["Key1"] = "Value1"
68-
# new_dict["Value1"] = "Key1"
69-
#
70-
#
75+
@pytest.mark.parametrize("value, expects", [
76+
([1, 2, 3], "1,2,3"),
77+
(["a", "b", "c"], "a,b,c"),
78+
(["a", "b", 1, 2], "a,b,1,2"),
79+
(["a", 2, pathlib.Path("foo.txt")], "a,2,foo.txt"),
80+
])
81+
def test_list2str(value, expects):
82+
str_representation = list2str(value)
83+
assert isinstance(str_representation, str)
84+
assert str_representation == expects
7185

86+
str_representation = list2string(value)
87+
assert isinstance(str_representation, str)
88+
assert str_representation == expects
7289

73-
def test_as_text():
74-
assert utils.as_text(12345) == "12345"
75-
assert utils.as_text(123.45) == "123.45"
76-
assert utils.as_text([123.45]) == "[123.45]"
77-
assert utils.as_text({123.45}) == "{123.45}"
78-
assert utils.as_text((123.45, )) == "(123.45,)"
79-
assert utils.as_text(None) == ""
80-
assert utils.as_text(pathlib.Path(".")) == "."
81-
assert utils.as_text(decimal.Decimal("1234")) == "1234"
8290

91+
@pytest.mark.parametrize("value, expects", [
92+
([1, 2, 3], "1;2;3"),
93+
(["a", "b", "c"], "a;b;c"),
94+
(["a", "b", 1, 2], "a;b;1;2"),
95+
(["a", 2, pathlib.Path("foo.txt")], "a;2;foo.txt"),
96+
])
97+
def test_list2str_semicolon(value, expects):
98+
str_representation = list2str(value, sep=";")
99+
assert isinstance(str_representation, str)
100+
assert str_representation == expects
83101

84-
def test_split_len():
85-
assert utils.split_len("Spam Spam Spam Spam Spam Spam Spam Spam ", 5) == ["Spam "] * 8
102+
str_representation = list2string(value, sep=";")
103+
assert isinstance(str_representation, str)
104+
assert str_representation == expects
86105

87106

88107
def test_permutations():
@@ -137,3 +156,74 @@ def test_permutations():
137156

138157
with pytest.raises(ValueError):
139158
utils.permutations(data, 0)
159+
160+
161+
class CustomRepr:
162+
def __init__(self):
163+
pass
164+
165+
def __repr__(self):
166+
return "This is my custom __repr__!"
167+
168+
169+
class NoRepr:
170+
def __init__(self):
171+
pass
172+
173+
174+
def test_printr(capsys):
175+
utils.printr("This is a test")
176+
utils.printr(pathlib.PurePosixPath("foo.txt"))
177+
utils.printr(1234)
178+
utils.printr(12.34)
179+
utils.printr(CustomRepr())
180+
utils.printr(NoRepr())
181+
182+
captured = capsys.readouterr()
183+
stdout = captured.out.split("\n")
184+
assert stdout[0] == "'This is a test'"
185+
assert stdout[1] == "PurePosixPath('foo.txt')"
186+
assert stdout[2] == "1234"
187+
assert stdout[3] == "12.34"
188+
assert stdout[4] == "This is my custom __repr__!"
189+
assert stdout[5].startswith('')
190+
191+
192+
def test_printt(capsys):
193+
utils.printt("This is a test")
194+
utils.printt(pathlib.PurePosixPath("foo.txt"))
195+
utils.printt(1234)
196+
utils.printt(12.34)
197+
utils.printt(CustomRepr())
198+
utils.printt(NoRepr())
199+
200+
captured = capsys.readouterr()
201+
stdout = captured.out.split("\n")
202+
assert stdout[0] == "<class 'str'>"
203+
assert stdout[1] == "<class 'pathlib.PurePosixPath'>"
204+
assert stdout[2] == "<class 'int'>"
205+
assert stdout[3] == "<class 'float'>"
206+
assert stdout[4] == "<class 'tests.test_utils.CustomRepr'>"
207+
assert stdout[5] == "<class 'tests.test_utils.NoRepr'>"
208+
209+
210+
def test_split_len():
211+
assert utils.split_len("Spam Spam Spam Spam Spam Spam Spam Spam ", 5) == ["Spam "] * 8
212+
213+
214+
@pytest.mark.parametrize("value, expects", [
215+
("1,2,3", (1, 2, 3)), # tests without spaces
216+
("1, 2, 3", (1, 2, 3)), # tests with spaces
217+
])
218+
def test_str2tuple(value, expects):
219+
assert isinstance(str2tuple(value), tuple)
220+
assert str2tuple(value) == expects
221+
222+
223+
@pytest.mark.parametrize("value, expects", [
224+
("1;2;3", (1, 2, 3)), # tests without semicolon
225+
("1; 2; 3", (1, 2, 3)), # tests with semicolon
226+
])
227+
def test_str2tuple_semicolon(value, expects):
228+
assert isinstance(str2tuple(value, sep=";"), tuple)
229+
assert str2tuple(value, sep=";") == expects

0 commit comments

Comments
 (0)