-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathtest_download_client.py
More file actions
423 lines (338 loc) · 18.7 KB
/
test_download_client.py
File metadata and controls
423 lines (338 loc) · 18.7 KB
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
"""Tests for DownloadClient: init, set_rule, add_torrent, rename, etc."""
import pytest
from unittest.mock import AsyncMock, patch, MagicMock
from module.models import Bangumi, Torrent
from module.models.config import Config
from module.downloader.download_client import DownloadClient
from test.factories import make_bangumi, make_torrent
@pytest.fixture
def download_client(mock_qb_client):
"""Create a DownloadClient with mocked internal client."""
with patch("module.downloader.download_client.settings") as mock_settings:
mock_settings.downloader.type = "qbittorrent"
mock_settings.downloader.host = "localhost:8080"
mock_settings.downloader.username = "admin"
mock_settings.downloader.password = "admin"
mock_settings.downloader.ssl = False
mock_settings.downloader.path = "/downloads/Bangumi"
mock_settings.bangumi_manage.group_tag = False
with patch(
"module.downloader.download_client.DownloadClient._DownloadClient__getClient",
return_value=mock_qb_client,
):
client = DownloadClient()
client.client = mock_qb_client
return client
# ---------------------------------------------------------------------------
# auth
# ---------------------------------------------------------------------------
class TestAuth:
async def test_auth_success(self, download_client, mock_qb_client):
"""auth() sets authed=True when client authenticates."""
mock_qb_client.auth.return_value = True
await download_client.auth()
assert download_client.authed is True
async def test_auth_failure(self, download_client, mock_qb_client):
"""auth() keeps authed=False when client fails."""
mock_qb_client.auth.return_value = False
await download_client.auth()
assert download_client.authed is False
# ---------------------------------------------------------------------------
# init_downloader
# ---------------------------------------------------------------------------
class TestInitDownloader:
async def test_sets_prefs_and_category(self, download_client, mock_qb_client):
"""init_downloader calls prefs_init with RSS config and adds category."""
with patch("module.downloader.download_client.settings") as mock_settings:
mock_settings.downloader.path = "/downloads/Bangumi"
await download_client.init_downloader()
mock_qb_client.prefs_init.assert_called_once()
prefs_arg = mock_qb_client.prefs_init.call_args[1]["prefs"]
assert prefs_arg["rss_auto_downloading_enabled"] is True
assert prefs_arg["rss_refresh_interval"] == 30
mock_qb_client.add_category.assert_called_once_with("BangumiCollection")
async def test_detects_path_when_empty(self, download_client, mock_qb_client):
"""When downloader.path is empty, fetches from app prefs."""
with patch("module.downloader.download_client.settings") as mock_settings:
mock_settings.downloader.path = ""
mock_qb_client.get_app_prefs.return_value = {"save_path": "/data"}
await download_client.init_downloader()
assert mock_settings.downloader.path != ""
assert "Bangumi" in mock_settings.downloader.path
async def test_category_already_exists_no_error(self, download_client, mock_qb_client):
"""If category already exists, logs debug but doesn't crash."""
mock_qb_client.add_category.side_effect = Exception("already exists")
with patch("module.downloader.download_client.settings") as mock_settings:
mock_settings.downloader.path = "/downloads/Bangumi"
# Should not raise
await download_client.init_downloader()
# ---------------------------------------------------------------------------
# set_rule
# ---------------------------------------------------------------------------
class TestSetRule:
async def test_generates_correct_rule(self, download_client, mock_qb_client):
"""set_rule creates a rule with correct mustContain and savePath."""
bangumi = make_bangumi(
title_raw="Mushoku Tensei",
filter="720,480",
official_title="Mushoku Tensei",
season=2,
year="2024",
)
with patch("module.downloader.path.settings") as mock_settings:
mock_settings.downloader.path = "/downloads/Bangumi"
mock_settings.bangumi_manage.group_tag = False
await download_client.set_rule(bangumi)
mock_qb_client.rss_set_rule.assert_called_once()
call_kwargs = mock_qb_client.rss_set_rule.call_args[1]
rule = call_kwargs["rule_def"]
assert rule["mustContain"] == "Mushoku Tensei"
# filter string is joined char-by-char with "|" (this is how the code works)
assert rule["mustNotContain"] == "|".join("720,480")
assert rule["enable"] is True
assert "Season 2" in rule["savePath"]
async def test_marks_bangumi_added(self, download_client, mock_qb_client):
"""set_rule sets data.added=True after creating the rule."""
bangumi = make_bangumi(added=False, filter="")
with patch("module.downloader.path.settings") as mock_settings:
mock_settings.downloader.path = "/downloads/Bangumi"
mock_settings.bangumi_manage.group_tag = False
await download_client.set_rule(bangumi)
assert bangumi.added is True
async def test_rule_name_set(self, download_client, mock_qb_client):
"""set_rule populates rule_name and save_path on the Bangumi."""
bangumi = make_bangumi(
official_title="My Anime",
season=1,
filter="",
rule_name=None,
save_path=None,
)
with patch("module.downloader.path.settings") as mock_settings:
mock_settings.downloader.path = "/downloads/Bangumi"
mock_settings.bangumi_manage.group_tag = False
await download_client.set_rule(bangumi)
assert bangumi.rule_name is not None
assert "My Anime" in bangumi.rule_name
assert bangumi.save_path is not None
async def test_rule_name_with_group_tag(self, download_client, mock_qb_client):
"""When group_tag=True, rule_name includes [group]."""
bangumi = make_bangumi(
official_title="My Anime",
group_name="SubGroup",
season=1,
filter="",
)
with patch("module.downloader.path.settings") as mock_settings:
mock_settings.downloader.path = "/downloads/Bangumi"
mock_settings.bangumi_manage.group_tag = True
await download_client.set_rule(bangumi)
assert "[SubGroup]" in bangumi.rule_name
# ---------------------------------------------------------------------------
# add_torrent
# ---------------------------------------------------------------------------
class TestAddTorrent:
async def test_magnet_url(self, download_client, mock_qb_client):
"""Magnet URLs are passed as torrent_urls, no file download."""
torrent = make_torrent(url="magnet:?xt=urn:btih:abc123")
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
result = await download_client.add_torrent(torrent, bangumi)
assert result is True
call_kwargs = mock_qb_client.add_torrents.call_args[1]
assert call_kwargs["torrent_urls"] == "magnet:?xt=urn:btih:abc123"
assert call_kwargs["torrent_files"] is None
async def test_file_url_downloads_content(self, download_client, mock_qb_client):
"""Non-magnet URLs trigger file download and pass as torrent_files."""
torrent = make_torrent(url="https://example.com/file.torrent")
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
mock_req.get_content = AsyncMock(return_value=b"torrent-file-data")
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
result = await download_client.add_torrent(torrent, bangumi)
assert result is True
call_kwargs = mock_qb_client.add_torrents.call_args[1]
assert call_kwargs["torrent_files"] == b"torrent-file-data"
assert call_kwargs["torrent_urls"] is None
async def test_list_magnet_urls(self, download_client, mock_qb_client):
"""List of magnet torrents are joined as list of URLs."""
torrents = [
make_torrent(url="magnet:?xt=urn:btih:aaa"),
make_torrent(url="magnet:?xt=urn:btih:bbb"),
make_torrent(url="magnet:?xt=urn:btih:ccc"),
]
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
result = await download_client.add_torrent(torrents, bangumi)
assert result is True
call_kwargs = mock_qb_client.add_torrents.call_args[1]
assert len(call_kwargs["torrent_urls"]) == 3
async def test_empty_list_returns_false(self, download_client, mock_qb_client):
"""Empty torrent list returns False without calling client."""
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
result = await download_client.add_torrent([], bangumi)
assert result is False
mock_qb_client.add_torrents.assert_not_called()
async def test_client_rejects_returns_false(self, download_client, mock_qb_client):
"""When client.add_torrents returns False, returns False."""
mock_qb_client.add_torrents.return_value = False
torrent = make_torrent(url="magnet:?xt=urn:btih:abc")
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
result = await download_client.add_torrent(torrent, bangumi)
assert result is False
async def test_client_rejects_status_is_failed(self, download_client, mock_qb_client):
"""When client.add_torrents returns False, tri-state API reports failed."""
mock_qb_client.add_torrents.return_value = False
mock_qb_client.torrents_info.return_value = []
torrent = make_torrent(url="magnet:?xt=urn:btih:def")
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
status = await download_client.add_torrent_with_status(torrent, bangumi)
assert status == "failed"
async def test_client_rejects_but_hash_exists_reports_exists(
self, download_client, mock_qb_client
):
"""Falsy add result with matching info-hash should be treated as exists."""
mock_qb_client.add_torrents.return_value = False
mock_qb_client.torrents_info.return_value = [
{"hash": "0123456789abcdef0123456789abcdef01234567", "name": "Other Name"}
]
torrent = make_torrent(
name="[Sub] Test Anime - 01 [1080p].mkv",
url="magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567",
)
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
status = await download_client.add_torrent_with_status(torrent, bangumi)
assert status == "exists"
async def test_client_rejects_but_name_exists_reports_exists(
self, download_client, mock_qb_client
):
"""Falsy add result with matching torrent name should be treated as exists."""
mock_qb_client.add_torrents.return_value = False
mock_qb_client.torrents_info.return_value = [
{"hash": "deadbeef", "name": "[Sub] Test Anime - 01 [1080p].mkv"}
]
torrent = make_torrent(
name="[Sub] Test Anime - 01 [1080p].mkv",
url="https://example.com/test-anime-01.torrent",
)
bangumi = make_bangumi()
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
mock_req.get_content = AsyncMock(return_value=b"torrent-file-data")
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
status = await download_client.add_torrent_with_status(torrent, bangumi)
assert status == "exists"
async def test_generates_save_path_if_missing(self, download_client, mock_qb_client):
"""When bangumi.save_path is empty, generates one."""
torrent = make_torrent(url="magnet:?xt=urn:btih:abc")
bangumi = make_bangumi(save_path=None)
with patch("module.downloader.download_client.RequestContent") as MockReq:
mock_req = AsyncMock()
MockReq.return_value.__aenter__ = AsyncMock(return_value=mock_req)
MockReq.return_value.__aexit__ = AsyncMock(return_value=False)
with patch("module.downloader.path.settings") as mock_settings:
mock_settings.downloader.path = "/downloads/Bangumi"
await download_client.add_torrent(torrent, bangumi)
assert bangumi.save_path is not None
# ---------------------------------------------------------------------------
# get_torrent_info / rename_torrent_file / delete_torrent
# ---------------------------------------------------------------------------
class TestClientDelegation:
async def test_get_torrent_info(self, download_client, mock_qb_client):
"""get_torrent_info delegates to client.torrents_info."""
mock_qb_client.torrents_info.return_value = [
{"hash": "abc", "name": "test", "save_path": "/test"}
]
result = await download_client.get_torrent_info()
mock_qb_client.torrents_info.assert_called_once_with(
status_filter="completed", category="Bangumi", tag=None
)
assert len(result) == 1
async def test_rename_torrent_file_success(self, download_client, mock_qb_client):
"""rename_torrent_file returns True on success."""
mock_qb_client.torrents_rename_file.return_value = True
result = await download_client.rename_torrent_file("hash1", "old.mkv", "new.mkv")
assert result is True
async def test_rename_torrent_file_failure(self, download_client, mock_qb_client):
"""rename_torrent_file returns False on failure."""
mock_qb_client.torrents_rename_file.return_value = False
result = await download_client.rename_torrent_file("hash1", "old.mkv", "new.mkv")
assert result is False
async def test_rename_torrent_file_passes_verify_flag(
self, download_client, mock_qb_client
):
"""rename_torrent_file forwards the verify kwarg to the underlying client."""
mock_qb_client.torrents_rename_file.return_value = True
await download_client.rename_torrent_file(
"hash1", "old.mkv", "new.mkv", verify=False
)
call_kwargs = mock_qb_client.torrents_rename_file.call_args[1]
assert call_kwargs["verify"] is False
async def test_delete_torrent(self, download_client, mock_qb_client):
"""delete_torrent delegates to client.torrents_delete."""
await download_client.delete_torrent("hash1", delete_files=True)
mock_qb_client.torrents_delete.assert_called_once_with("hash1", delete_files=True)
# ---------------------------------------------------------------------------
# add_tag
# ---------------------------------------------------------------------------
class TestAddTag:
async def test_add_tag_delegates_to_client(self, download_client, mock_qb_client):
"""add_tag delegates to client.add_tag."""
mock_qb_client.add_tag = AsyncMock(return_value=None)
download_client.client = mock_qb_client
await download_client.add_tag("deadbeef12345678", "ab:42")
mock_qb_client.add_tag.assert_called_once_with("deadbeef12345678", "ab:42")
async def test_add_tag_short_hash_no_error(self, download_client, mock_qb_client):
"""add_tag with a hash shorter than 8 chars does not crash the slice."""
mock_qb_client.add_tag = AsyncMock(return_value=None)
download_client.client = mock_qb_client
# Should not raise even for short hashes
await download_client.add_tag("abc", "ab:1")
# ---------------------------------------------------------------------------
# Context manager: ConnectionError on failed auth
# ---------------------------------------------------------------------------
class TestContextManagerAuth:
async def test_aenter_raises_on_auth_failure(self, download_client, mock_qb_client):
"""__aenter__ raises ConnectionError when auth fails."""
mock_qb_client.auth.return_value = False
download_client.authed = False
with pytest.raises(ConnectionError, match="authentication failed"):
await download_client.__aenter__()
async def test_aenter_succeeds_when_auth_passes(self, download_client, mock_qb_client):
"""__aenter__ returns self when auth succeeds."""
mock_qb_client.auth.return_value = True
download_client.authed = False
result = await download_client.__aenter__()
assert result is download_client
assert download_client.authed is True
async def test_aexit_calls_logout_when_authed(self, download_client, mock_qb_client):
"""__aexit__ calls logout and resets authed when session was active."""
download_client.authed = True
await download_client.__aexit__(None, None, None)
mock_qb_client.logout.assert_called_once()
assert download_client.authed is False