import json from api import profile def test_fingerprint_generated_once(tmp_path): first = profile.load_or_create(tmp_path) assert profile.load_or_create(tmp_path) == first assert json.loads((tmp_path / profile.SETTINGS_FILE).read_text()) == first screen = first["fingerprint"]["screen"] assert screen["width"] >= profile.MIN_SCREEN[0] and screen["height"] >= profile.MIN_SCREEN[1] assert first["fingerprint"]["device_scale_factor"] >= 1 assert first["fingerprint"]["canvas_seed"] > 0 assert "user_agent" not in first def test_old_profile_settings_get_fingerprint(tmp_path): """Профиль из версии, где сохранялся user_agent клиента: UA отбрасывается, отпечаток создаётся.""" (tmp_path / profile.SETTINGS_FILE).write_text(json.dumps({"user_agent": "First/1"})) settings = profile.load_or_create(tmp_path) assert set(settings) == {"fingerprint"} def test_profiles_get_independent_fingerprints(tmp_path): """Отпечатки генерируются независимо: из выборки профилей получается больше одного варианта.""" variants = set() for i in range(30): d = tmp_path / str(i) d.mkdir() fp = profile.load_or_create(d)["fingerprint"] variants.add((fp["screen"]["width"], fp["screen"]["height"], fp["device_scale_factor"])) assert len(variants) > 1 def test_generate_falls_back_when_browserforge_fails(monkeypatch): class Failing: def generate(self, **kwargs): raise ValueError("Cannot generate headers") monkeypatch.setattr(profile, "FingerprintGenerator", Failing) fp = profile.generate_fingerprint(attempts=2) assert (fp["screen"], fp["device_scale_factor"]) == ({"width": 1920, "height": 1080}, 1) assert fp["canvas_seed"] > 0 def test_browser_kwargs(): kwargs = profile.browser_kwargs({"fingerprint": { "screen": {"width": 2560, "height": 1440}, "device_scale_factor": 1.25, "canvas_seed": 12345, }}) assert kwargs["additional_args"] == {"screen": {"width": 2560, "height": 1440}, "device_scale_factor": 1.25} assert "useragent" not in kwargs script = kwargs["init_script_content"] assert "const SEED = 12345 | 0;" in script and "__SEED__" not in script def test_profile_before_canvas_noise_gets_seed_and_keeps_screen(tmp_path): old = {"fingerprint": {"screen": {"width": 2560, "height": 1440}, "device_scale_factor": 2}} (tmp_path / profile.SETTINGS_FILE).write_text(json.dumps(old)) fp = profile.load_or_create(tmp_path)["fingerprint"] assert (fp["screen"], fp["device_scale_factor"]) == ({"width": 2560, "height": 1440}, 2) assert fp["canvas_seed"] > 0 assert profile.load_or_create(tmp_path)["fingerprint"] == fp def test_profiles_get_different_canvas_seeds(tmp_path): seeds = set() for i in range(20): (tmp_path / str(i)).mkdir() seeds.add(profile.load_or_create(tmp_path / str(i))["fingerprint"]["canvas_seed"]) assert len(seeds) == 20