import os import tempfile import pytest from room_cal.service_api.credentials import check_credentials, set_credentials @pytest.fixture(autouse=True) def isolated_data_home(tmp_path, monkeypatch): monkeypatch.setenv('ROOM_CAL_DATA_HOME', str(tmp_path)) def test_set_credentials_single_key(tmp_path): set_credentials('airbnb', {'AIRBNB_COOKIES': 'bev=abc; cdn=xyz'}) text = (tmp_path / 'airbnb.env').read_text() assert 'AIRBNB_COOKIES=bev=abc; cdn=xyz' in text assert 'AIRBNB_UPDATED_AT=' in text def test_set_credentials_multi_key(tmp_path): set_credentials('booking', { 'BOOKING_COOKIES': 'bui=1', 'BOOKING_SESSION': 'ses123', 'BOOKING_CSRF_TOKEN': 'csrf456', }) text = (tmp_path / 'booking.env').read_text() assert 'BOOKING_COOKIES=bui=1' in text assert 'BOOKING_SESSION=ses123' in text assert 'BOOKING_CSRF_TOKEN=csrf456' in text assert 'BOOKING_UPDATED_AT=' in text def test_set_credentials_upserts_in_place(tmp_path): (tmp_path / 'airbnb.env').write_text('AIRBNB_LISTING_ID=99\nAIRBNB_COOKIES=old\n') set_credentials('airbnb', {'AIRBNB_COOKIES': 'new-cookie'}) text = (tmp_path / 'airbnb.env').read_text() assert 'AIRBNB_COOKIES=new-cookie' in text assert 'old' not in text assert 'AIRBNB_LISTING_ID=99' in text def test_set_credentials_updates_timestamp_on_refresh(tmp_path): set_credentials('airbnb', {'AIRBNB_COOKIES': 'v1'}) first = (tmp_path / 'airbnb.env').read_text() set_credentials('airbnb', {'AIRBNB_COOKIES': 'v2'}) second = (tmp_path / 'airbnb.env').read_text() # Only one AIRBNB_UPDATED_AT line assert second.count('AIRBNB_UPDATED_AT=') == 1 assert 'AIRBNB_COOKIES=v2' in second def test_check_credentials_missing_file(tmp_path): result = check_credentials('airbnb') assert result['valid'] is False assert result['age_days'] is None assert 'not found' in result['reason'] def test_check_credentials_no_timestamp(tmp_path): (tmp_path / 'airbnb.env').write_text('AIRBNB_COOKIES=abc\n') result = check_credentials('airbnb') assert result['valid'] is True assert result['age_days'] is None assert 'timestamp' in result['reason'] def test_check_credentials_with_timestamp(tmp_path): set_credentials('airbnb', {'AIRBNB_COOKIES': 'abc'}) result = check_credentials('airbnb') assert result['valid'] is True assert result['age_days'] == 0 assert 'refreshed' in result['reason']