Skip to content

Commit bed3796

Browse files
committed
tests: major overhaul
- new fixtures: `caperr`, `tmp_file`, locks, `logger` - use more `monkeypatch`, `warns`, parameterisation - drop superfluous docstrings - drop some old python syntax Assisted-by: Claude Opus 5 <[email protected]>
1 parent 4d3d319 commit bed3796

18 files changed

Lines changed: 1335 additions & 1914 deletions

‎tests/conftest.py‎

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,70 @@
1-
"""Shared pytest config."""
21
import sys
2+
from io import StringIO
33

4-
from pytest import fixture
4+
from pytest import fixture, importorskip, skip
55

66
from tqdm import tqdm
77

88

9+
def _assert_no_instances(when):
10+
if instances := getattr(tqdm, '_instances', None):
11+
n = len(instances)
12+
instances.clear()
13+
raise OSError(f"{n} `tqdm` instances still in existence {when}-test")
14+
15+
916
@fixture(autouse=True)
1017
def pretest_posttest():
11-
"""Fixture for all tests ensuring environment cleanup"""
12-
try:
13-
sys.setswitchinterval(1)
14-
except AttributeError:
15-
sys.setcheckinterval(100) # deprecated
16-
17-
if getattr(tqdm, "_instances", False):
18-
n = len(tqdm._instances)
19-
if n:
20-
tqdm._instances.clear()
21-
raise OSError(f"{n} `tqdm` instances still in existence PRE-test")
18+
"""Ensure environment cleanup around every test"""
19+
sys.setswitchinterval(1)
20+
_assert_no_instances("PRE")
2221
yield
23-
if getattr(tqdm, "_instances", False):
24-
n = len(tqdm._instances)
25-
if n:
26-
tqdm._instances.clear()
27-
raise OSError(f"{n} `tqdm` instances still in existence POST-test")
22+
_assert_no_instances("POST")
23+
24+
25+
@fixture
26+
def caperr(capsys):
27+
"""shortcut for `capsys.readouterr().err` (and `assert not out`)"""
28+
def inner():
29+
out, err = capsys.readouterr()
30+
assert not out, f"Expected no stdout, got: {out}"
31+
return err
32+
yield inner
33+
34+
35+
@fixture
36+
def tmp_file():
37+
"""Writable in-memory text stream"""
38+
with StringIO() as file:
39+
yield file
40+
41+
42+
@fixture
43+
def tmp_file2():
44+
"""Second `tmp_file`, e.g. to separate two bars' output"""
45+
with StringIO() as file:
46+
yield file
47+
48+
49+
def _patch_lock(module):
50+
"""Swap tqdm's lock for a vanilla `RLock`, restoring it afterwards"""
51+
try:
52+
lock = importorskip(module).RLock()
53+
except OSError as err: # e.g. no /dev/shm
54+
skip(str(err))
55+
default_lock = tqdm.get_lock()
56+
tqdm.set_lock(lock)
57+
yield lock
58+
tqdm.set_lock(default_lock)
59+
60+
61+
@fixture
62+
def thread_lock():
63+
"""`threading.RLock` as tqdm's lock"""
64+
yield from _patch_lock('threading')
65+
66+
67+
@fixture
68+
def process_lock():
69+
"""`multiprocessing.RLock` as tqdm's lock"""
70+
yield from _patch_lock('multiprocessing')

‎tests/tests_asyncio.py‎

Lines changed: 35 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
"""Tests `tqdm.asyncio`."""
21
import asyncio
32
from functools import partial
43
from sys import platform
54
from time import time
65

7-
from tqdm.asyncio import tarange, tqdm_asyncio
6+
from pytest import mark
87

9-
from .tests_tqdm import StringIO, closing, mark
8+
from tqdm.asyncio import tarange, tqdm_asyncio
109

1110
tqdm = partial(tqdm_asyncio, miniters=0, mininterval=0)
1211
trange = partial(tarange, miniters=0, mininterval=0)
@@ -31,22 +30,19 @@ async def acount(*args, **kwargs):
3130

3231
@mark.asyncio
3332
async def test_break():
34-
"""Test asyncio break"""
3533
pbar = tqdm(count())
3634
async for _ in pbar:
3735
break
3836
pbar.close()
3937

4038

4139
@mark.asyncio
42-
async def test_generators(capsys):
43-
"""Test asyncio generators"""
40+
async def test_generators(caperr):
4441
with tqdm(count(), desc="counter") as pbar:
4542
async for i in pbar:
4643
if i >= 8:
4744
break
48-
_, err = capsys.readouterr()
49-
assert '9it' in err
45+
assert '9it' in caperr()
5046

5147
acounter = acount()
5248
try:
@@ -56,55 +52,45 @@ async def test_generators(capsys):
5652
break
5753
finally:
5854
await acounter.aclose()
59-
_, err = capsys.readouterr()
60-
assert '9it' in err
55+
assert '9it' in caperr()
6156

6257

6358
@mark.asyncio
64-
async def test_range():
65-
"""Test asyncio range"""
66-
with closing(StringIO()) as our_file:
67-
async for _ in tqdm(range(9), desc="range", file=our_file):
68-
pass
69-
assert '9/9' in our_file.getvalue()
70-
our_file.seek(0)
71-
our_file.truncate()
59+
async def test_range(caperr):
60+
async for _ in tqdm(range(9), desc="range"):
61+
pass
62+
assert '9/9' in caperr()
7263

73-
async for _ in trange(9, desc="trange", file=our_file):
74-
pass
75-
assert '9/9' in our_file.getvalue()
64+
async for _ in trange(9, desc="trange"):
65+
pass
66+
assert '9/9' in caperr()
7667

7768

7869
@mark.asyncio
79-
async def test_nested():
80-
"""Test asyncio nested"""
81-
with closing(StringIO()) as our_file:
82-
async for _ in tqdm(trange(9, desc="inner", file=our_file),
83-
desc="outer", file=our_file):
84-
pass
85-
assert 'inner: 100%' in our_file.getvalue()
86-
assert 'outer: 100%' in our_file.getvalue()
70+
async def test_nested(caperr):
71+
async for _ in tqdm(trange(9, desc="inner"), desc="outer"):
72+
pass
73+
err = caperr()
74+
assert 'inner: 100%' in err
75+
assert 'outer: 100%' in err
8776

8877

8978
@mark.asyncio
90-
async def test_coroutines():
91-
"""Test asyncio coroutine.send"""
92-
with closing(StringIO()) as our_file:
93-
with tqdm(count(), file=our_file) as pbar:
94-
async for i in pbar:
95-
if i == 9:
96-
pbar.send(-10)
97-
elif i < 0:
98-
assert i == -9
99-
break
100-
assert '10it' in our_file.getvalue()
79+
async def test_coroutine_send(caperr):
80+
with tqdm(count()) as pbar:
81+
async for i in pbar:
82+
if i == 9:
83+
pbar.send(-10)
84+
elif i < 0:
85+
assert i == -9
86+
break
87+
assert '10it' in caperr()
10188

10289

10390
@mark.slow
10491
@mark.asyncio
10592
@mark.parametrize("tol", [0.2 if platform.startswith("darwin") else 0.1])
106-
async def test_as_completed(capsys, tol):
107-
"""Test asyncio as_completed"""
93+
async def test_as_completed(caperr, tol):
10894
for retry in range(3):
10995
t = time()
11096
skew = time() - t
@@ -113,7 +99,7 @@ async def test_as_completed(capsys, tol):
11399
t = time() - t - 2 * skew
114100
try:
115101
assert 0.3 * (1 - tol) < t < 0.3 * (1 + tol), t
116-
_, err = capsys.readouterr()
102+
err = caperr()
117103
assert '30/30' in err
118104
except AssertionError:
119105
if retry == 2:
@@ -125,10 +111,9 @@ async def double(i):
125111

126112

127113
@mark.asyncio
128-
async def test_gather(capsys):
129-
"""Test asyncio gather"""
114+
async def test_gather(caperr):
130115
res = await gather(*map(double, range(30)))
131-
_, err = capsys.readouterr()
116+
err = caperr()
132117
assert '30/30' in err
133118
assert res == list(range(0, 30 * 2, 2))
134119

@@ -140,10 +125,9 @@ async def raise_exc(i):
140125

141126

142127
@mark.asyncio
143-
async def test_gather_exceptions(capsys):
144-
"""Test asyncio gather return_exceptions"""
128+
async def test_gather_exceptions(caperr):
145129
res = await gather(*map(raise_exc, range(3)), return_exceptions=True)
146-
_, err = capsys.readouterr()
130+
err = caperr()
147131
assert '3/3' in err
148132
assert isinstance(res[1], ValueError)
149133
assert res[0] == 0
@@ -174,11 +158,11 @@ async def __anext__(self):
174158

175159

176160
@mark.asyncio
177-
async def test_async_iterable(capsys):
161+
async def test_async_iterable(caperr):
178162
"""Test asyncio with async iterable (only __aiter__, no __anext__)"""
179163
result = []
180164
async for i in tqdm(AIterable(range(9)), desc="aiterable"):
181165
result.append(i)
182166
assert result == list(range(9))
183-
_, err = capsys.readouterr()
167+
err = caperr()
184168
assert '9it' in err

‎tests/tests_concurrent.py‎

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,25 @@
1-
"""
2-
Tests for `tqdm.contrib.concurrent`.
3-
"""
41
import sys
52

6-
from pytest import warns
3+
from pytest import mark, skip, warns
74

5+
from tqdm import TqdmWarning
6+
from tqdm.contrib import concurrent
87
from tqdm.contrib.concurrent import interpreter_map, process_map, thread_map
98

10-
from .tests_tqdm import TqdmWarning, importorskip, mark, skip
119

12-
13-
def incr(x):
14-
"""Dummy function"""
10+
def dummy_func(x):
1511
return x + 1
1612

1713

1814
@mark.parametrize("mapper", [interpreter_map, process_map, thread_map])
19-
def test_concurrent_map(mapper, capsys):
20-
"""Test contrib.concurrent.*_map"""
15+
def test_concurrent_map(mapper, caperr):
2116
a = range(9)
2217
b = [i + 1 for i in a]
2318
try:
24-
assert mapper(incr, a, miniters=1) == b
19+
assert mapper(dummy_func, a, miniters=1) == b
2520
except ImportError as err:
2621
skip(str(err))
27-
out, err = capsys.readouterr()
28-
assert not out
22+
err = caperr()
2923
assert '0/9' in err
3024

3125

@@ -78,11 +72,10 @@ def test_interpreter_map_lock(tmp_path):
7872
(['x' * 100, ('x',) * 1001], False),
7973
(['x' * 1001, ('x',) * 100], False),
8074
(['x' * 1001, ('x',) * 1001], True)])
81-
def test_chunksize_warning(iterables, should_warn):
82-
"""Test contrib.concurrent.process_map chunksize warnings"""
83-
patch = importorskip('unittest.mock').patch
84-
with patch('tqdm.contrib.concurrent._executor_map'):
85-
if should_warn:
86-
warns(TqdmWarning, process_map, incr, *iterables)
87-
else:
88-
process_map(incr, *iterables)
75+
def test_chunksize_warning(iterables, should_warn, monkeypatch):
76+
monkeypatch.setattr(concurrent, '_executor_map', lambda *_, **__: None)
77+
if should_warn:
78+
with warns(TqdmWarning):
79+
process_map(dummy_func, *iterables)
80+
else:
81+
process_map(dummy_func, *iterables)

0 commit comments

Comments
 (0)