-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.py
More file actions
2949 lines (2546 loc) · 117 KB
/
Copy pathtests.py
File metadata and controls
2949 lines (2546 loc) · 117 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
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unit Tests for UnityScraper
Comprehensive test suite for all modules
"""
import unittest
import tempfile
import shutil
import json
import hashlib
import os
import sqlite3
import sys
import time
import zipfile
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
import requests
# Import modules to test
from main import Config, RateLimiter, UnityScraper
from database import DatabaseManager
from resume import ResumableDownloader, DownloadProgress, BatchDownloadManager
from consolemods_adapters import (
parse_multi_id_document,
parse_title_id_document,
short_code_to_titleid,
)
from knowledge_base import EntityRecord, Fact, Identifier, KnowledgeRepository
from dat_adapters import parse_dat
from external_tools import (
ExternalToolError,
ExternalToolRunner,
format_command,
split_arguments,
)
from external_tools_gui import bundled_xextool_path
from tool_catalog import ToolCatalog, ToolDefinition, operation_for
from knowledge_service import KnowledgeService
from knowledge_sources import (
CachedHttpClient,
KnowledgeImportService,
SourceAccessBlockedError,
SourceInfo,
)
from offline_knowledge import OfflineKnowledgeArchive
from library_service import GameSummary, LibraryService
from modern_gui import (
LE_FLUFFIE_CREATOR,
XEXTOOL_CREATOR,
UnityScraperDesktop,
navigation_shortcut,
)
from title_catalog import XboxUnityTitleCatalog
from wiki_adapters import extract_article_text, parse_sitemap
from backup_manager import (
BackupItem,
FtpBackupClient,
FtpTarget,
InvalidPackageError,
UnsafeArchiveError,
atomic_copy,
import_stfs_zip,
extract_stfs_files,
inspect_stfs,
inspect_xbe,
list_stfs_entries,
package_destination,
scan_local_target,
)
from backup_service import BackupRepository, BackupService
from api import UnityScraperAPI
from app_version import DISPLAY_VERSION
from app_paths import resolve_storage_paths
from platform_support import desktop_font_family, path_opener_command
from profile_manager import ProfileSaveManager, find_content_root, mask_identifier
from unityscraper.app.api.entrypoint import create_api
from unityscraper.app.cli import CliCommand, CliCommandRegistry, build_cli_registry
from unityscraper.app.cli.legacy import run_legacy_cli
from unityscraper.app.desktop.entrypoint import main as package_desktop_main
from unityscraper.core import APP_METADATA
from unityscraper.core.db import MigrationRegistry
from unityscraper.core.jobs import CancellationToken, JobProgress, JobResult, JobRunner
from unityscraper.core.paths import app_root as package_app_root
from unityscraper.core.paths import resource_path as package_resource_path
from unityscraper.core.version import DISPLAY_VERSION as PACKAGE_DISPLAY_VERSION
from unityscraper.domains.backups.service import BackupService as ModularBackupService
from unityscraper.domains.backups.migrations import ensure_backup_schema as DomainBackupSchema
from unityscraper.domains.knowledge.models import EntityRecord as ModularEntityRecord
from unityscraper.domains.library.models import GameSummary as ModularGameSummary
from unityscraper.domains.library.service import LibraryService as ModularLibraryService
from unityscraper.domains.packages.commands import InspectStfsPackage, InventoryStfsFileTable
from unityscraper.domains.packages.stfs import verify_stfs
from unityscraper.domains.tools.catalog import ToolCatalog as ModularToolCatalog
from unityscraper.domains.tools.models import ToolDefinition as ModularToolDefinition
from unityscraper.domains.tools.runner import ExternalToolRunner as ModularToolRunner
class TestPlatformSupport(unittest.TestCase):
"""Test cross-platform storage and desktop integration."""
def test_legacy_translations_are_repaired_at_load_time(self):
from i18n import TRANSLATIONS
self.assertEqual(TRANSLATIONS["es"]["settings"], "Configuraci\u00f3n")
self.assertEqual(TRANSLATIONS["ja"]["browse"], "\u53c2\u7167")
def test_bounded_language_pack_extends_navigation_with_english_fallback(self):
from i18n import init_translator
root = Path(tempfile.mkdtemp())
try:
(root / "nl.json").write_text(json.dumps({
"language": "nl", "strings": {"nav_library": "BIBLIOTHEEK"}
}), encoding="utf-8")
translator = init_translator("nl", root)
self.assertEqual(translator.get("nav_library"), "BIBLIOTHEEK")
self.assertEqual(translator.get("nav_settings"), "SETTINGS")
finally:
shutil.rmtree(root)
def test_linux_uses_xdg_directories(self):
home = Path("/home/tester")
paths = resolve_storage_paths(
os_name="posix",
platform_name="linux",
environ={
"XDG_DATA_HOME": "/xdg/data",
"XDG_CONFIG_HOME": "/xdg/config",
"XDG_CACHE_HOME": "/xdg/cache",
"XDG_STATE_HOME": "/xdg/state",
},
home=home,
)
self.assertEqual(paths.base, Path("/xdg/data/unityscraper"))
self.assertEqual(paths.config, Path("/xdg/config/unityscraper"))
self.assertEqual(paths.cache, Path("/xdg/cache/unityscraper"))
self.assertEqual(paths.logs, Path("/xdg/state/unityscraper/logs"))
def test_macos_uses_native_user_directories(self):
home = Path("/Users/tester")
paths = resolve_storage_paths(
os_name="posix", platform_name="darwin", environ={}, home=home
)
self.assertEqual(
paths.base, home / "Library" / "Application Support" / "UnityScraper"
)
self.assertEqual(paths.cache, home / "Library" / "Caches" / "UnityScraper")
self.assertEqual(paths.logs, home / "Library" / "Logs" / "UnityScraper")
def test_linux_xdg_defaults_follow_home(self):
home = Path("/home/tester")
paths = resolve_storage_paths(
os_name="posix",
platform_name="linux",
environ={},
home=home,
)
self.assertEqual(paths.base, home / ".local/share/unityscraper")
self.assertEqual(paths.config, home / ".config/unityscraper")
self.assertEqual(paths.cache, home / ".cache/unityscraper")
self.assertEqual(paths.logs, home / ".local/state/unityscraper/logs")
def test_linux_ignores_relative_xdg_values(self):
home = Path("/home/tester")
paths = resolve_storage_paths(
os_name="posix",
platform_name="linux",
environ={"XDG_CONFIG_HOME": "relative/config"},
home=home,
)
self.assertEqual(paths.config, home / ".config/unityscraper")
def test_portable_mode_keeps_everything_together(self):
paths = resolve_storage_paths(portable_root=Path("/opt/unityscraper"))
self.assertEqual(paths.base, Path("/opt/unityscraper/UnityScraperData"))
self.assertEqual(paths.config, paths.base / "config")
self.assertEqual(paths.cache, paths.base / "cache")
def test_platform_openers(self):
self.assertIsNone(path_opener_command(os_name="nt", platform_name="win32"))
self.assertEqual(
path_opener_command(os_name="posix", platform_name="darwin"),
["open"],
)
with patch("platform_support.shutil.which") as which:
which.side_effect = lambda command: "/usr/bin/gio" if command == "gio" else None
self.assertEqual(
path_opener_command(os_name="posix", platform_name="linux"),
["gio", "open"],
)
def test_desktop_font_is_defined(self):
self.assertTrue(desktop_font_family())
def test_linux_desktop_metadata_is_complete(self):
desktop = Path("packaging/linux/io.github.trapemall.UnityScraper.desktop")
metadata = Path("packaging/linux/io.github.trapemall.UnityScraper.metainfo.xml")
self.assertIn("Type=Application", desktop.read_text(encoding="utf-8"))
self.assertIn("@EXEC@", desktop.read_text(encoding="utf-8"))
import xml.etree.ElementTree as element_tree
root = element_tree.parse(metadata).getroot()
self.assertEqual(root.attrib["type"], "desktop-application")
self.assertEqual(
root.findtext("id"),
"io.github.trapemall.UnityScraper",
)
def test_pyinstaller_collects_package_modules(self):
spec = Path("UnityScraper.spec").read_text(encoding="utf-8")
self.assertIn("collect_submodules('unityscraper')", spec)
class TestModularFoundation(unittest.TestCase):
"""Test package ownership and legacy compatibility boundaries."""
def test_domain_service_exports_preserve_existing_implementations(self):
self.assertIs(ModularBackupService, BackupService)
self.assertIs(ModularLibraryService, LibraryService)
self.assertIs(ModularGameSummary, GameSummary)
self.assertIs(ModularEntityRecord, EntityRecord)
self.assertIs(ModularToolDefinition, ToolDefinition)
self.assertIs(ModularToolCatalog, ToolCatalog)
self.assertIs(ModularToolRunner, ExternalToolRunner)
def test_migrated_implementations_are_domain_owned(self):
self.assertEqual(
ModularLibraryService.__module__,
"unityscraper.domains.library.service",
)
self.assertEqual(
ModularGameSummary.__module__,
"unityscraper.domains.library.models",
)
self.assertEqual(
ModularToolCatalog.__module__,
"unityscraper.domains.tools.catalog",
)
self.assertEqual(
ModularToolRunner.__module__,
"unityscraper.domains.tools.runner",
)
def test_backup_schema_is_domain_owned_with_legacy_compatibility(self):
from backup_service import ensure_backup_schema as LegacyBackupSchema
self.assertIs(LegacyBackupSchema, DomainBackupSchema)
def test_package_inspection_command_returns_job_result(self):
root = Path(tempfile.mkdtemp())
try:
package = root / "save.bin"
header = bytearray(0x1791)
header[:4] = b"CON "
header[0x344:0x348] = (1).to_bytes(4, "big")
header[0x354:0x358] = bytes.fromhex("12345678")
header[0x360:0x364] = bytes.fromhex("53510804")
title = "Hitman: Absolution".encode("utf-16-be")
header[0x411:0x411 + len(title)] = title
package.write_bytes(header)
result = InspectStfsPackage().run(package)
self.assertEqual(result.status, "completed")
self.assertEqual(result.payload["package"]["title_id"], "53510804")
self.assertEqual(result.payload["package"]["display_name"], "Hitman: Absolution")
finally:
shutil.rmtree(root)
def test_package_inventory_command_returns_failed_job_result(self):
root = Path(tempfile.mkdtemp())
try:
package = root / "invalid.bin"
package.write_bytes(b"not a package")
result = InventoryStfsFileTable().run(package)
self.assertEqual(result.status, "failed")
self.assertEqual(result.payload["source"], str(package))
finally:
shutil.rmtree(root)
def test_core_paths_match_legacy_asset_resolution(self):
self.assertEqual(package_app_root(), Path.cwd())
self.assertTrue(package_resource_path("JSON.txt").is_file())
def test_core_metadata_matches_legacy_version(self):
self.assertEqual(PACKAGE_DISPLAY_VERSION, DISPLAY_VERSION)
self.assertEqual(APP_METADATA.name, "UnityScraper")
self.assertEqual(APP_METADATA.display_version, DISPLAY_VERSION)
def test_cli_registry_exposes_legacy_adapter(self):
registry = build_cli_registry()
command = registry.get("legacy")
self.assertIn("legacy", registry.as_dict())
self.assertEqual(command.description, "Run the existing full UnityScraper CLI surface.")
def test_cli_registry_rejects_duplicate_command_names(self):
registry = CliCommandRegistry()
command = CliCommand(name="example", description="Example", handler=lambda argv: 0)
registry.register(command)
with self.assertRaises(ValueError):
registry.register(command)
def test_legacy_cli_adapter_restores_sys_argv(self):
original = sys.argv[:]
with patch("main.main", return_value=None) as legacy:
result = run_legacy_cli(["--help"])
self.assertEqual(result, 0)
self.assertEqual(sys.argv, original)
self.assertEqual(legacy.call_count, 1)
def test_app_surface_entrypoints_delegate_lazily(self):
with patch("desktop_app.main", return_value=0) as desktop:
self.assertEqual(package_desktop_main(), 0)
with patch("api.UnityScraperAPI", return_value="api") as api_class:
self.assertEqual(create_api(), "api")
self.assertEqual(desktop.call_count, 1)
self.assertEqual(api_class.call_count, 1)
def test_job_progress_percent_is_bounded(self):
self.assertEqual(
JobProgress(status="running", message="working", current=5, total=10).percent,
50.0,
)
self.assertEqual(
JobProgress(status="running", message="over", current=15, total=10).percent,
100.0,
)
self.assertIsNone(JobProgress(status="running", message="unknown").percent)
def test_job_result_factories_set_terminal_state(self):
completed = JobResult.completed("done", count=2)
failed = JobResult.failed("failed", reason="example")
cancelled = JobResult.cancelled()
self.assertEqual(completed.status, "completed")
self.assertEqual(completed.payload["count"], 2)
self.assertIsNotNone(completed.finished_at)
self.assertEqual(failed.status, "failed")
self.assertEqual(failed.payload["reason"], "example")
self.assertIsNotNone(failed.finished_at)
self.assertEqual(cancelled.status, "cancelled")
self.assertIsNotNone(cancelled.finished_at)
def test_job_runner_normalizes_success_failure_and_progress(self):
progress = []
runner = JobRunner(progress_callback=progress.append)
success = runner.run(
"example",
lambda context: JobResult.completed("done", name=context.name),
)
failure = runner.run(
"failing",
lambda context: (_ for _ in ()).throw(RuntimeError("boom")),
)
self.assertEqual(success.status, "completed")
self.assertEqual(success.payload["name"], "example")
self.assertEqual(failure.status, "failed")
self.assertEqual(failure.payload["job"], "failing")
self.assertGreaterEqual(len(progress), 4)
self.assertEqual(progress[0].message, "example started")
def test_job_runner_honors_pre_cancelled_token(self):
token = CancellationToken()
token.cancel()
result = JobRunner().run(
"cancelled",
lambda context: JobResult.completed("should not run"),
token=token,
)
self.assertEqual(result.status, "cancelled")
self.assertEqual(result.payload["job"], "cancelled")
def test_domain_migration_registry_applies_once(self):
calls = []
def migration(connection):
calls.append("applied")
connection.execute("CREATE TABLE example_domain_table (id INTEGER PRIMARY KEY)")
registry = MigrationRegistry()
registry.register(domain="example", version=1, name="example schema", apply=migration)
with sqlite3.connect(":memory:") as connection:
first = registry.apply(connection)
second = registry.apply(connection)
table = connection.execute(
"""
SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'example_domain_table'
"""
).fetchone()
self.assertEqual([item.key for item in first], ["example:1"])
self.assertEqual(second, [])
self.assertEqual(calls, ["applied"])
self.assertIsNotNone(table)
class TestConfig(unittest.TestCase):
"""Test configuration management"""
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.config_file = Path(self.temp_dir) / "test_config.json"
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_default_config(self):
"""Test default configuration values"""
config = Config()
self.assertEqual(config.workers, 4)
self.assertEqual(config.rate_limit, 0.35)
self.assertEqual(config.timeout, 30)
self.assertFalse(config.use_https)
self.assertEqual(config.base_url, "http://xboxunity.net")
def test_save_and_load_config(self):
"""Test saving and loading configuration"""
config = Config()
config.workers = 8
config.rate_limit = 0.5
config.save_to_file(str(self.config_file))
# Load and verify
loaded_config = Config(str(self.config_file))
self.assertEqual(loaded_config.workers, 8)
self.assertEqual(loaded_config.rate_limit, 0.5)
def test_invalid_config_file(self):
"""Test handling of invalid config file"""
invalid_file = Path(self.temp_dir) / "invalid.json"
with open(invalid_file, 'w') as f:
f.write("not valid json{")
# Should use defaults without crashing
config = Config(str(invalid_file))
self.assertEqual(config.workers, 4)
class TestRateLimiter(unittest.TestCase):
"""Test rate limiting functionality"""
def test_rate_limiting(self):
"""Test that rate limiter enforces minimum interval"""
limiter = RateLimiter(0.1)
start = time.time()
limiter.wait()
limiter.wait()
elapsed = time.time() - start
# Should take at least 0.1 seconds for second call
self.assertGreaterEqual(elapsed, 0.1)
def test_concurrent_rate_limiting(self):
"""Test rate limiter is thread-safe"""
import threading
limiter = RateLimiter(0.05)
results = []
def test_thread():
start = time.time()
limiter.wait()
results.append(time.time() - start)
threads = [threading.Thread(target=test_thread) for _ in range(5)]
start = time.time()
for t in threads:
t.start()
for t in threads:
t.join()
total_time = time.time() - start
# 5 calls with 0.05s interval should take at least 0.2s
self.assertGreaterEqual(total_time, 0.2)
class TestUnityScraper(unittest.TestCase):
"""Test main scraper functionality"""
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.database = DatabaseManager(Path(self.temp_dir) / "scraper.db")
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_validate_titleid(self):
"""Test TitleID validation"""
# Valid TitleIDs
self.assertEqual(UnityScraper.validate_titleid('TESTID00'), 'TESTID00')
self.assertEqual(UnityScraper.validate_titleid('testid00'), 'TESTID00')
self.assertEqual(UnityScraper.validate_titleid('00000155'), '00000155')
# Invalid TitleIDs
self.assertIsNone(UnityScraper.validate_titleid('12345')) # Too short
self.assertIsNone(UnityScraper.validate_titleid('123456789')) # Too long
self.assertIsNone(UnityScraper.validate_titleid('GGGG8888')) # Invalid hex
self.assertIsNone(UnityScraper.validate_titleid('')) # Empty
@patch('main.UnityScraper._test_connection')
def test_scraper_initialization(self, mock_test):
"""Test scraper initialization"""
mock_test.return_value = None
config = Config()
scraper = UnityScraper(config, database=self.database)
self.assertIsNotNone(scraper.session)
self.assertIsNotNone(scraper.rate_limiter)
mock_test.assert_called_once()
@patch('requests.Session.get')
def test_make_request_success(self, mock_get):
"""Test successful HTTP request"""
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {'test': 'data'}
mock_get.return_value = mock_response
config = Config()
with patch.object(UnityScraper, '_test_connection'):
scraper = UnityScraper(config, database=self.database)
response = scraper._make_request('http://test.com')
self.assertIsNotNone(response)
self.assertEqual(response.status_code, 200)
@patch('requests.Session.get')
def test_make_request_rate_limit(self, mock_get):
"""Test handling of 429 rate limit"""
mock_response = Mock()
mock_response.status_code = 429
mock_get.return_value = mock_response
config = Config()
config.max_retries = 1
with patch.object(UnityScraper, '_test_connection'):
scraper = UnityScraper(config, database=self.database)
start = time.time()
response = scraper._make_request('http://test.com')
elapsed = time.time() - start
# Should have waited before retry
self.assertGreater(elapsed, 1.0)
class TestDatabaseManager(unittest.TestCase):
"""Test database functionality"""
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.db_path = Path(self.temp_dir) / "test.db"
self.db = DatabaseManager(str(self.db_path))
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_database_initialization(self):
"""Test database creation"""
self.assertTrue(self.db_path.exists())
def test_knowledge_schema_initialization(self):
"""Test normalized knowledge tables are created."""
with self.db.get_connection() as conn:
row = conn.execute(
"""
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name = 'knowledge_facts'
"""
).fetchone()
self.assertIsNotNone(row)
def test_backup_schema_initialization(self):
"""Test additive backup inventory and operation tables are created."""
expected = {
"backup_targets",
"backup_scans",
"backup_inventory",
"backup_operations",
}
with self.db.get_connection() as conn:
rows = conn.execute(
"""
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name LIKE 'backup_%'
"""
).fetchall()
self.assertTrue(expected.issubset({row["name"] for row in rows}))
def test_add_titleid(self):
"""Test adding TitleID"""
success = self.db.add_titleid(
'TESTID00',
name='Test Game',
publisher='Test Publisher'
)
self.assertTrue(success)
# Verify it was added
info = self.db.get_titleid_info('TESTID00')
self.assertIsNotNone(info)
self.assertEqual(info['name'], 'Test Game')
def test_add_duplicate_titleid(self):
"""Test updating existing TitleID"""
self.db.add_titleid('TESTID00', name='Game 1')
self.db.add_titleid('TESTID00', name='Game 2')
info = self.db.get_titleid_info('TESTID00')
self.assertEqual(info['name'], 'Game 2')
def test_add_title_update(self):
"""Test adding title update"""
self.db.add_titleid('TESTID00')
success = self.db.add_title_update(
'TESTID00',
media_id='12345678',
version='3',
download_url='http://test.com/update.bin'
)
self.assertTrue(success)
info = self.db.get_titleid_info('TESTID00')
self.assertEqual(len(info['updates']), 1)
self.assertEqual(info['updates'][0]['version'], '3')
def test_add_cover(self):
"""Test adding cover"""
self.db.add_titleid('TESTID00')
success = self.db.add_cover(
'TESTID00',
cover_url='http://test.com/cover.jpg',
cover_type='front'
)
self.assertTrue(success)
info = self.db.get_titleid_info('TESTID00')
self.assertEqual(len(info['covers']), 1)
self.assertEqual(info['covers'][0]['cover_type'], 'front')
def test_search_titleids(self):
"""Test searching TitleIDs"""
self.db.add_titleid('TESTID00', name='Test Game')
self.db.add_titleid('TESTID01', name='Call of Duty')
results = self.db.search_titleids('test')
self.assertEqual(len(results), 1)
self.assertEqual(results[0]['titleid'], 'TESTID00')
def test_statistics(self):
"""Test statistics generation"""
self.db.add_titleid('TESTID00', name='Game 1')
self.db.add_titleid('TESTID01', name='Game 2')
self.db.add_title_update('TESTID00', 'media1', 'v1', 'http://test.com')
stats = self.db.get_statistics()
self.assertEqual(stats['total_titleids'], 2)
self.assertEqual(stats['total_updates'], 1)
def test_export_to_json(self):
"""Test JSON export"""
self.db.add_titleid('TESTID00', name='Test Game')
export_file = Path(self.temp_dir) / "export.json"
success = self.db.export_to_json(str(export_file))
self.assertTrue(success)
self.assertTrue(export_file.exists())
with open(export_file) as f:
data = json.load(f)
self.assertIn('titleids', data)
self.assertIn('statistics', data)
def test_enrich_unknown_metadata_from_knowledge(self):
"""Test imported knowledge fills only unknown library fields."""
with self.db.get_connection() as conn:
repo = KnowledgeRepository(conn)
source_id = repo.upsert_source("test", "Test Source")
repo.upsert_entity_record(
EntityRecord(
"game",
"South Park: The Stick of Truth",
identifiers=(Identifier("titleid", "555308C5"),),
facts=(
Fact("title", "South Park: The Stick of Truth"),
Fact("publisher", "Ubisoft"),
),
),
source_id,
)
self.db.add_titleid("555308C5", name="Unknown", publisher="Unknown Publisher")
info = self.db.get_titleid_info("555308C5")
self.assertEqual(info["name"], "South Park: The Stick of Truth")
self.assertEqual(info["publisher"], "Ubisoft")
self.db.add_titleid("555308C5", name="User Name", publisher="User Publisher")
info = self.db.get_titleid_info("555308C5")
self.assertEqual(info["name"], "User Name")
self.assertEqual(info["publisher"], "User Publisher")
class TestXboxUnityTitleCatalog(unittest.TestCase):
"""Test persistent, HTTP-only XboxUnity title autocomplete data."""
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.db_path = Path(self.temp_dir) / "catalog.db"
self.database = DatabaseManager(self.db_path)
def tearDown(self):
shutil.rmtree(self.temp_dir)
@staticmethod
def _response(items, *, pages=1, page=0):
response = Mock()
response.url = (
"http://xboxunity.net/Resources/Lib/TitleList.php"
f"?category=0&count=100&page={page}"
)
response.raise_for_status.return_value = None
response.json.return_value = {
"Items": items,
"Count": len(items),
"Pages": pages,
"Page": page,
}
return response
def test_sync_caches_every_page_and_searches_name_or_titleid(self):
session = Mock()
session.get.side_effect = [
self._response(
[
{
"TitleID": "4D5307E6",
"Name": "Halo 3",
"TitleType": "360",
"Covers": "40",
"Updates": "12",
}
],
pages=2,
page=0,
),
self._response(
[
{
"TitleID": "4D53085B",
"Name": "Halo: Reach",
"TitleType": "360",
"Covers": "28",
"Updates": "11",
}
],
pages=2,
page=1,
),
]
catalog = XboxUnityTitleCatalog(
self.db_path,
session=session,
request_interval=0,
)
result = catalog.sync()
self.assertEqual(result.pages_fetched, 2)
self.assertEqual(catalog.count(), 2)
self.assertEqual(catalog.search("reach")[0].titleid, "4D53085B")
self.assertEqual(catalog.search("4D5307")[0].name, "Halo 3")
self.assertTrue(session.get.call_args_list[0].args[0].startswith("http://"))
def test_catalog_enrichment_never_replaces_a_known_name(self):
catalog = XboxUnityTitleCatalog(self.db_path)
catalog._store_page(
[
{"TitleID": "4D5307E6", "Name": "Halo 3", "TitleType": "360"},
{"TitleID": "4D53085B", "Name": "Halo: Reach", "TitleType": "360"},
],
"http://xboxunity.net/Resources/Lib/TitleList.php?page=0",
)
self.database.add_titleid("4D5307E6", name="4D5307E6")
self.database.add_titleid("4D53085B", name="My Preferred Reach Name")
self.assertEqual(self.database.get_titleid_info("4D5307E6")["name"], "Halo 3")
self.assertEqual(
self.database.get_titleid_info("4D53085B")["name"],
"My Preferred Reach Name",
)
def test_library_does_not_display_titleid_as_the_game_name(self):
self.database.add_titleid("555308C5")
games = LibraryService(self.db_path).list_games()
self.assertEqual(games[0].name, "Unknown game")
def test_library_uses_cached_catalog_name_before_sync_finishes(self):
self.database.add_titleid("53510804")
catalog = XboxUnityTitleCatalog(self.db_path)
catalog._store_page(
[{"TitleID": "53510804", "Name": "Hitman: Absolution", "TitleType": "360"}],
"http://xboxunity.net/Resources/Lib/TitleList.php?page=47",
)
library = LibraryService(self.db_path)
games = library.list_games("Hitman")
details = library.get_game_details("53510804")
self.assertEqual(games[0].name, "Hitman: Absolution")
self.assertEqual(details["title"]["name"], "Hitman: Absolution")
def test_failed_sync_keeps_page_progress_and_enriches_downloaded_names(self):
self.database.add_titleid("53510804")
session = Mock()
session.get.side_effect = [
self._response(
[{"TitleID": "53510804", "Name": "Hitman: Absolution"}],
pages=2,
page=0,
),
requests.ConnectionError("connection lost"),
]
catalog = XboxUnityTitleCatalog(
self.db_path,
session=session,
request_interval=0,
)
with self.assertRaises(requests.ConnectionError):
catalog.sync()
self.assertEqual(
self.database.get_titleid_info("53510804")["name"],
"Hitman: Absolution",
)
with self.database.get_connection() as connection:
run = connection.execute(
"""
SELECT status, pages_expected, pages_fetched, items_upserted
FROM xboxunity_catalog_sync_runs
ORDER BY id DESC
LIMIT 1
"""
).fetchone()
self.assertEqual(dict(run), {
"status": "failed",
"pages_expected": 2,
"pages_fetched": 1,
"items_upserted": 1,
})
def test_database_startup_repairs_names_from_an_interrupted_cache(self):
self.database.add_titleid("53510804")
catalog = XboxUnityTitleCatalog(self.db_path)
catalog._store_page(
[{"TitleID": "53510804", "Name": "Hitman: Absolution"}],
"http://xboxunity.net/Resources/Lib/TitleList.php?page=47",
)
reopened = DatabaseManager(self.db_path)
self.assertEqual(
reopened.get_titleid_info("53510804")["name"],
"Hitman: Absolution",
)
def test_non_http_xboxunity_base_url_is_rejected(self):
with self.assertRaises(ValueError):
XboxUnityTitleCatalog(self.db_path, base_url="https://xboxunity.net")
class TestExternalTools(unittest.TestCase):
"""Test shell-free execution for user-supplied command-line tools."""
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.input_path = Path(self.temp_dir) / "default.xex"
self.input_path.write_bytes(b"XEX2")
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_xextool_template_splits_into_an_argument_vector(self):
self.assertEqual(
split_arguments('-l "{input}"', windows=True),
["-l", "{input}"],
)
def test_runner_substitutes_input_without_shell_interpretation(self):
runner = ExternalToolRunner()
marker = "value; echo this-is-data"
result = runner.run(
sys.executable,
[
"-c",
"import sys; print(sys.argv[1]); print(sys.argv[2])",
marker,
"{input}",
],
input_path=self.input_path,
)
self.assertEqual(result.returncode, 0)
self.assertIn(marker, result.stdout)
self.assertIn(str(self.input_path.resolve()), result.stdout)
self.assertFalse(result.cancelled)
def test_runner_rejects_missing_executable_and_input(self):
runner = ExternalToolRunner()
with self.assertRaises(ExternalToolError):
runner.build_command(
Path(self.temp_dir) / "missing.exe",
["{input}"],
input_path=self.input_path,
)
with self.assertRaises(ExternalToolError):
runner.build_command(
sys.executable,
["{input}"],
input_path=Path(self.temp_dir) / "missing.xex",
)
def test_runner_supports_directory_input_and_output(self):
runner = ExternalToolRunner()
source = Path(self.temp_dir) / "source"
output = Path(self.temp_dir) / "output"
source.mkdir()
output.mkdir()
command = runner.build_command(
sys.executable,
["{input}", "{output}"],
input_path=source,
output_path=output,
input_kind="directory",
output_kind="directory",
)
self.assertEqual(command[1:], (str(source.resolve()), str(output.resolve())))
def test_unused_paths_are_ignored_for_launch_only_operations(self):
runner = ExternalToolRunner()
command = runner.build_command(
sys.executable,
(),
input_path=Path(self.temp_dir) / "stale-missing-input",
output_path=Path(self.temp_dir) / "stale-missing-output",
input_kind="none",
output_kind="none",
)
self.assertEqual(command, (str(Path(sys.executable).resolve()),))
def test_catalog_contains_requested_tools_and_excludes_omissions(self):
catalog = ToolCatalog(Path(self.temp_dir) / "config.json")
tool_ids = {tool.id for tool in catalog.definitions()}
self.assertTrue(
{
"xextool",
"extract-xiso",
"xenia",
"xenia-canary",
"velocity",
"iso2god",
"god2iso",
"xbox-image-browser",
"le-fluffie",
"custom",
}.issubset(tool_ids)
)