File: test_stringlist.py

package info (click to toggle)
domdf-python-tools 3.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,784 kB
  • sloc: python: 10,838; makefile: 7
file content (580 lines) | stat: -rw-r--r-- 16,328 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# stdlib
import pickle
import textwrap
from textwrap import dedent
from typing import no_type_check

# 3rd party
import pytest

# this package
from domdf_python_tools.stringlist import DelimitedList, Indent, StringList, joinlines, splitlines


class TestStringList:

	def test_creation(self):
		assert not StringList()
		assert not StringList([])
		assert not StringList(())

		assert StringList([1]) == ['1']
		assert StringList(['1']) == ['1']
		assert StringList('1') == ['1']
		assert StringList("1\n") == ['1', '']

		with pytest.raises(TypeError, match="'int' object is not iterable"):
			StringList(1)  # type: ignore

	def test_append(self):
		sl = StringList()

		sl.append('')
		assert sl == ['']

		sl.append('')
		assert sl == ['', '']

		sl.append("hello")
		assert sl == ['', '', "hello"]

		sl.append("world\n\n\n")
		assert sl == ['', '', "hello", "world", '', '', '']

		sl.append("1234")
		assert sl == ['', '', "hello", "world", '', '', '', "1234"]

	def test_insert(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])

		sl.insert(0, "foo")
		assert sl == ["foo", '', '', "hello", "world", '', '', '', "1234"]

		sl.insert(1, "bar")
		assert sl == ["foo", "bar", '', '', "hello", "world", '', '', '', "1234"]

		sl.insert(0, "1234")
		assert sl == ["1234", "foo", "bar", '', '', "hello", "world", '', '', '', "1234"]

		sl.insert(11, "baz")
		assert sl == ["1234", "foo", "bar", '', '', "hello", "world", '', '', '', "1234", "baz"]

		sl.insert(3, "\na line\n")
		assert sl == ["1234", "foo", "bar", '', "a line", '', '', '', "hello", "world", '', '', '', "1234", "baz"]

		sl.insert(100, "end")
		assert sl == [
				"1234", "foo", "bar", '', "a line", '', '', '', "hello", "world", '', '', '', "1234", "baz", "end"
				]

	def test_setitem(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])

		sl[0] = "foo"
		assert sl == ["foo", '', "hello", "world", '', '', '', "1234"]

		sl[1] = "bar"
		assert sl == ["foo", "bar", "hello", "world", '', '', '', "1234"]

		sl[2] = "\nhello\nworld\n"
		assert sl == ["foo", "bar", '', "hello", "world", '', "world", '', '', '', "1234"]

		sl[3:4] = "\nfoo\nbar\n", "baz"
		assert sl == ["foo", "bar", '', '', "foo", "bar", '', "baz", '', "world", '', '', '', "1234"]

		sl[3:5] = iter(["foo", "bar", "baz"])
		assert sl == ["foo", "bar", '', "foo", "bar", "baz", '', "baz", '', "world", '', '', '', "1234"]

	def test_blankline(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])

		sl.blankline()
		assert sl == ['', '', "hello", "world", '', '', '', "1234", '']

		sl.blankline()
		assert sl == ['', '', "hello", "world", '', '', '', "1234", '', '']

		sl.blankline(ensure_single=True)
		assert sl == ['', '', "hello", "world", '', '', '', "1234", '']

		sl.blankline(ensure_single=True)
		assert sl == ['', '', "hello", "world", '', '', '', "1234", '']

		sl.append('\t')
		sl.blankline(ensure_single=True)
		assert sl == ['', '', "hello", "world", '', '', '', "1234", '']

		sl.append("    ")
		sl.blankline(ensure_single=True)

		assert sl == ['', '', "hello", "world", '', '', '', "1234", '']

		sl.append("    ")
		sl.blankline(ensure_single=True)
		sl.blankline()
		assert sl == ['', '', "hello", "world", '', '', '', "1234", '', '']

	def test_slicing(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		assert sl[:-3] == ['', '', "hello", "world", '']
		assert sl[-3:] == ['', '', "1234"]

	def test_start_of_line_indents(self):
		assert StringList("Hello\n    World") == ["Hello", "    World"]
		assert StringList("Hello\n    World", convert_indents=True) == ["Hello", "\tWorld"]

	def test_negative_getitem(self):
		sl = StringList(['', '', "hello", "world", '', '', "abc", "1234"])

		assert sl[-1] == "1234"
		sl[-1] += "5678"
		assert sl == ['', '', "hello", "world", '', '', "abc", "12345678"]

		assert sl[-2] == "abc"
		sl[-2] += "def"
		assert sl == ['', '', "hello", "world", '', '', "abcdef", "12345678"]

	def test_indent_size(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])

		assert sl.indent_size == 0

		sl.indent_size = 7
		assert sl.indent_size == 7

		sl.set_indent_size()
		assert sl.indent_size == 0

		sl.set_indent_size(2)
		assert sl.indent_size == 2

		sl.indent_size += 1
		assert sl.indent_size == 3

		sl.indent_size -= 2
		assert sl.indent_size == 1

	def test_indent_type(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])

		assert sl.indent_type == '\t'

		with pytest.raises(ValueError, match="'type' cannot an empty string."):
			sl.indent_type = ''

		assert sl.indent_type == '\t'

		sl.indent_type = ' '
		assert sl.indent_type == ' '

		sl.set_indent_type('\t')
		assert sl.indent_type == '\t'

		sl.set_indent_type(' ')
		assert sl.indent_type == ' '

		with pytest.raises(ValueError, match="'type' cannot an empty string."):
			sl.set_indent_type('')

		assert sl.indent_type == ' '

		sl.set_indent_type()
		assert sl.indent_type == '\t'

	def test_indent(self):
		sl = StringList()
		sl.set_indent_size(1)

		sl.append("Indented")

		assert sl == ["\tIndented"]

		sl.set_indent_type("    ")

		sl.append("Indented")

		assert sl == ["\tIndented", "    Indented"]

		expected_list = [
				"class Foo:",
				'',
				"\tdef bar(self, listicle: List[Item]):",
				"\t\t...",
				'',
				"\tdef __repr__(self) -> str:",
				'\t\treturn "Foo()"',
				'',
				]

		expected_string = dedent(
				"""\
		class Foo:

			def bar(self, listicle: List[Item]):
				...

			def __repr__(self) -> str:
				return "Foo()"
		"""
				)

		sl = StringList()
		sl.append("class Foo:")
		sl.blankline(True)
		sl.set_indent_size(1)
		sl.append("def bar(self, listicle: List[Item]):")
		sl.indent_size += 1
		sl.append("...")
		sl.indent_size -= 1
		sl.blankline(True)
		sl.append("def __repr__(self) -> str:")
		sl.indent_size += 1
		sl.append('return "Foo()"')
		sl.indent_size -= 1
		sl.blankline(True)
		sl.set_indent_size(0)

		assert sl == expected_list
		assert str(sl) == expected_string
		assert sl == expected_string

		sl = StringList()
		sl.append("class Foo:")
		sl.blankline(True)

		with sl.with_indent('\t', 1):
			sl.append("def bar(self, listicle: List[Item]):")
			with sl.with_indent('\t', 2):
				sl.append("...")
			sl.blankline(True)
			sl.append("def __repr__(self) -> str:")
			with sl.with_indent('\t', 2):
				sl.append('return "Foo()"')
			sl.blankline(True)

		assert sl.indent_size == 0

		assert sl == expected_list
		assert str(sl) == expected_string
		assert sl == expected_string

		sl = StringList()
		sl.append("class Foo:")
		sl.blankline(True)

		with sl.with_indent_size(1):
			sl.append("def bar(self, listicle: List[Item]):")
			with sl.with_indent_size(2):
				sl.append("...")
			sl.blankline(True)
			sl.append("def __repr__(self) -> str:")
			with sl.with_indent_size(2):
				sl.append('return "Foo()"')
			sl.blankline(True)

		assert sl.indent_size == 0

		assert sl == expected_list
		assert str(sl) == expected_string
		assert sl == expected_string

		sl = StringList()
		sl.append("class Foo:")
		sl.set_indent(Indent(0, "    "))
		sl.blankline(True)

		with sl.with_indent_size(1):
			sl.append("def bar(self, listicle: List[Item]):")
			with sl.with_indent_size(2):
				sl.append("...")
			sl.blankline(True)
			sl.append("def __repr__(self) -> str:")
			with sl.with_indent_size(2):
				sl.append('return "Foo()"')
			sl.blankline(True)

		assert sl.indent_size == 0

		assert sl == [x.expandtabs(4) for x in expected_list]
		assert str(sl) == expected_string.expandtabs(4)
		assert sl == expected_string.expandtabs(4)

		sl = StringList()
		sl.append("class Foo:")
		sl.set_indent("    ", 0)
		sl.blankline(True)

		with sl.with_indent_size(1):
			sl.append("def bar(self, listicle: List[Item]):")
			with sl.with_indent_size(2):
				sl.append("...")
			sl.blankline(True)
			sl.append("def __repr__(self) -> str:")
			with sl.with_indent_size(2):
				sl.append('return "Foo()"')
			sl.blankline(True)

		assert sl.indent_size == 0

		assert sl == [x.expandtabs(4) for x in expected_list]
		assert str(sl) == expected_string.expandtabs(4)
		assert sl == expected_string.expandtabs(4)

		sl = StringList()
		sl.append("class Foo:")
		sl.blankline(True)

		with sl.with_indent_size(1):
			sl.append("def bar(self, listicle: List[Item]):")
			with sl.with_indent_size(2):
				sl.append("...")
			sl.blankline(True)
			sl.append("def __repr__(self) -> str:")
			with sl.with_indent_size(2):
				with sl.with_indent_type("    "):
					sl.append('return "Foo()"')
			sl.blankline(True)

		assert sl.indent_size == 0

		expected_list[-2] = '        return "Foo()"'
		assert sl == expected_list
		assert str(sl) == expected_string.replace('\t\treturn "Foo()"', '        return "Foo()"')
		assert sl == expected_string.replace('\t\treturn "Foo()"', '        return "Foo()"')

	def test_convert_indents(self):
		sl = StringList(convert_indents=True)

		sl.append("    Indented")

		assert sl == ["\tIndented"]

	def test_set_indent_error(self):
		sl = StringList()
		with pytest.raises(TypeError, match="'size' argument cannot be used when providing an 'Indent' object."):
			sl.set_indent(Indent(0, "    "), 5)

	def test_extend(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		sl.extend(["\nfoo\nbar\n    baz"])

		assert sl == ['', '', "hello", "world", '', '', '', "1234", '', "foo", "bar", "    baz"]

	def test_clear(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		sl.clear()

		assert sl == []

	def test_copy(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		sl2 = sl.copy()

		assert sl == sl2
		assert sl2 == ['', '', "hello", "world", '', '', '', "1234"]
		assert isinstance(sl2, StringList)

	def test_count(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		assert sl.count("hello") == 1

	def test_count_blanklines(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		assert sl.count_blanklines() == 5

	def test_index(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		assert sl.index("hello") == 2

	def test_pop(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		assert sl.pop(2) == "hello"
		assert sl == ['', '', "world", '', '', '', "1234"]
		assert isinstance(sl, StringList)

	def test_remove(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		sl.remove("hello")
		assert sl == ['', '', "world", '', '', '', "1234"]
		assert isinstance(sl, StringList)

	def test_reverse(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		sl.reverse()
		assert sl == ["1234", '', '', '', "world", "hello", '', '']
		assert isinstance(sl, StringList)

	def test_sort(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		sl.sort()
		assert sl == ['', '', '', '', '', "1234", "hello", "world"]
		assert isinstance(sl, StringList)

		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		sl.sort(reverse=True)
		assert sl == ["world", "hello", "1234", '', '', '', '', '']
		assert isinstance(sl, StringList)

	def test_str(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		assert str(sl) == "\n\nhello\nworld\n\n\n\n1234"
		sl = StringList(['', '', "hello", "world", '', '', '', "1234", ''])
		assert str(sl) == "\n\nhello\nworld\n\n\n\n1234\n"

	def test_bytes(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		assert bytes(sl) == b"\n\nhello\nworld\n\n\n\n1234"
		sl = StringList(['', '', "hello", "world", '', '', '', "1234", ''])
		assert bytes(sl) == b"\n\nhello\nworld\n\n\n\n1234\n"

	@pytest.mark.xfail()
	def test_pickle(self):
		sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
		loaded = pickle.loads(pickle.dumps(sl))  # nosec: B301
		assert sl == loaded
		assert sl.indent == loaded.indent
		assert isinstance(loaded, StringList)


class TestIndent:

	def test_creation(self):
		indent = Indent()
		assert indent.size == 0
		assert indent.type == '\t'

		indent = Indent(3, "    ")
		assert indent.size == 3
		assert indent.type == "    "

	def test_iter(self):
		indent = Indent(3, "    ")
		assert tuple(indent) == (3, "    ")
		assert list(iter(indent)) == [3, "    "]

	def test_size(self):
		indent = Indent()

		indent.size = 1
		assert indent.size == 1

		indent.size = '2'  # type: ignore
		assert indent.size == 2

		indent.size = 3.0  # type: ignore
		assert indent.size == 3

	def test_type(self):
		indent = Indent()

		indent.type = "    "
		assert indent.type == "    "

		indent.type = ' '
		assert indent.type == ' '

		indent.type = 1  # type: ignore
		assert indent.type == '1'

		indent.type = ">>> "
		assert indent.type == ">>> "

		with pytest.raises(ValueError, match="'type' cannot an empty string."):
			indent.type = ''

	def test_str(self):
		assert str(Indent()) == ''
		assert str(Indent(1)) == '\t'
		assert str(Indent(5)) == "\t\t\t\t\t"
		assert str(Indent(type="    ")) == ''
		assert str(Indent(1, type="    ")) == "    "
		assert str(Indent(5, type="    ")) == "    " * 5
		assert str(Indent(type=">>> ")) == ''
		assert str(Indent(1, type=">>> ")) == ">>> "

	def test_repr(self):
		assert repr(Indent()) == "Indent(size=0, type='\\t')"
		assert repr(Indent(1)) == "Indent(size=1, type='\\t')"
		assert repr(Indent(5)) == "Indent(size=5, type='\\t')"
		assert repr(Indent(type="    ")) == "Indent(size=0, type='    ')"
		assert repr(Indent(1, type="    ")) == "Indent(size=1, type='    ')"
		assert repr(Indent(5, type="    ")) == "Indent(size=5, type='    ')"
		assert repr(Indent(type=">>> ")) == "Indent(size=0, type='>>> ')"
		assert repr(Indent(1, type=">>> ")) == "Indent(size=1, type='>>> ')"

	def test_eq(self):
		assert Indent() == Indent()
		assert Indent() == (0, '\t')
		assert Indent() == ''

		assert Indent(1, "    ") == Indent(1, "    ")
		assert Indent(1, "    ") == (1, "    ")
		assert Indent(1, "    ") == "    "

		assert Indent(2, '\t') == Indent(2, '\t')
		assert Indent(2, '\t') == (2, '\t')
		assert Indent(2, '\t') == "\t\t"

		assert Indent() != 1

	def test_pickle(self):
		indent = Indent(2, "    ")
		assert indent == pickle.loads(pickle.dumps(indent))  # nosec: B301


def test_delimitedlist():
	data = DelimitedList(['a', 'b', 'c', 'd', 'e'])

	assert data.__format__(", ") == "a, b, c, d, e"
	assert data.__format__("; ") == "a; b; c; d; e"
	assert data.__format__(';') == "a;b;c;d;e"
	assert data.__format__('\n') == "a\nb\nc\nd\ne"

	assert f"{data:, }" == "a, b, c, d, e"
	assert f"{data:; }" == "a; b; c; d; e"
	assert f"{data:;}" == "a;b;c;d;e"
	assert f"{data:\n}" == "a\nb\nc\nd\ne"

	assert f"{data:, }" == "a, b, c, d, e"
	assert f"{data:; }" == "a; b; c; d; e"
	assert f"{data:;}" == "a;b;c;d;e"
	assert f"{data:\n}" == "a\nb\nc\nd\ne"


joinlines_splitlines_param = pytest.mark.parametrize(
		"string, lines",
		[
				("abc\ndef\n\rghi", [("abc", '\n'), ("def", '\n'), ('', '\r'), ("ghi", '')]),
				("abc\ndef\n\r\nghi", [("abc", '\n'), ("def", '\n'), ('', "\r\n"), ("ghi", '')]),
				("abc\ndef\r\nghi", [("abc", '\n'), ("def", "\r\n"), ("ghi", '')]),
				("abc\ndef\r\nghi\n", [("abc", '\n'), ("def", "\r\n"), ("ghi", '\n')]),
				("abc\ndef\r\nghi\n\r", [("abc", '\n'), ("def", "\r\n"), ("ghi", '\n'), ('', '\r')]),
				("\nabc\ndef\r\nghi\n\r", [('', '\n'), ("abc", '\n'), ("def", "\r\n"), ("ghi", '\n'), ('', '\r')]),
				("abcdef", [("abcdef", '')]),
				]
		)


@joinlines_splitlines_param
def test_splitlines(string, lines):
	assert splitlines(string) == lines


@joinlines_splitlines_param
def test_joinlines(string, lines):
	assert string == joinlines(lines)


@no_type_check
def test_stringlist_textwrap_indent():
	sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
	assert textwrap.indent(sl, "    ") == "\n\n    hello\n    world\n\n\n\n    1234\n"
	assert textwrap.indent(sl, '\t') == "\n\n\thello\n\tworld\n\n\n\n\t1234\n"
	assert textwrap.indent(sl, ">>> ") == "\n\n>>> hello\n>>> world\n\n\n\n>>> 1234\n"


def test_stringlist_splitlines():
	sl = StringList(['', '', "hello", "world", '', '', '', "1234"])
	assert sl.splitlines() is sl
	assert list(sl.splitlines()) == ['', '', "hello", "world", '', '', '', "1234"]
	assert sl.splitlines(keepends=True) == ['\n', '\n', "hello\n", "world\n", '\n', '\n', '\n', "1234\n"]