File: conftest.py

package info (click to toggle)
pyicloud 2.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 828 kB
  • sloc: python: 9,741; sh: 17; makefile: 3
file content (144 lines) | stat: -rw-r--r-- 4,955 bytes parent folder | download
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
"""Pytest configuration file for the pyicloud package."""

import os
import secrets
from unittest.mock import MagicMock, mock_open, patch

import pytest
from requests.cookies import RequestsCookieJar

from pyicloud.base import PyiCloudService
from pyicloud.services.contacts import ContactsService
from pyicloud.services.drive import COOKIE_APPLE_WEBAUTH_VALIDATE
from pyicloud.services.hidemyemail import HideMyEmailService
from pyicloud.session import PyiCloudSession
from tests import PyiCloudSessionMock
from tests.const_login import LOGIN_WORKING

BUILTINS_OPEN: str = "builtins.open"
EXAMPLE_DOMAIN: str = "https://example.com"


class FileSystemAccessError(Exception):
    """Raised when a test tries to access the file system."""


@pytest.fixture(autouse=True, scope="function")
def mock_mkdir():
    """Mock the mkdir function to prevent file system access."""
    mkdir = os.mkdir

    def my_mkdir(path, *args, **kwargs):
        if "python-test-results" not in path:
            raise FileSystemAccessError(
                f"You should not be creating directories in tests. {path}"
            )
        return mkdir(path, *args, **kwargs)

    with patch("os.mkdir", my_mkdir) as mkdir_mock:
        yield mkdir_mock


@pytest.fixture(autouse=True, scope="session")
def mock_open_fixture():
    """Mock the open function to prevent file system access."""
    builtins_open = open

    def my_open(path, *args, **kwargs):
        if "python-test-results" not in path:
            raise FileSystemAccessError(
                f"You should not be opening files in tests. {path}"
            )
        return builtins_open(path, *args, **kwargs)

    with patch(BUILTINS_OPEN, my_open) as open_mock:
        yield open_mock


@pytest.fixture
def pyicloud_service() -> PyiCloudService:
    """Create a PyiCloudService instance with mocked authenticate method."""
    with (
        patch("pyicloud.base.PyiCloudService.authenticate") as mock_authenticate,
        patch(BUILTINS_OPEN, new_callable=mock_open),
    ):
        # Mock the authenticate method during initialization
        mock_authenticate.return_value = None
        service = PyiCloudService("test@example.com", secrets.token_hex(32))
        return service


@pytest.fixture
def pyicloud_service_working(pyicloud_service: PyiCloudService) -> PyiCloudService:  # pylint: disable=redefined-outer-name
    """Set the service to a working state."""
    pyicloud_service.data = LOGIN_WORKING
    pyicloud_service._webservices = LOGIN_WORKING["webservices"]  # pylint: disable=protected-access
    with patch(BUILTINS_OPEN, new_callable=mock_open):
        pyicloud_service.session = PyiCloudSessionMock(
            pyicloud_service,
            "",
            cookie_directory="",
        )
        pyicloud_service.session._data = {"session_token": "valid_token"}  # pylint: disable=protected-access
    return pyicloud_service


@pytest.fixture
def pyicloud_session(pyicloud_service_working: PyiCloudService) -> PyiCloudSession:  # pylint: disable=redefined-outer-name
    """Mock the PyiCloudSession class."""
    pyicloud_service_working.session.cookies = MagicMock()
    return pyicloud_service_working.session


@pytest.fixture
def mock_session() -> MagicMock:
    """Fixture to create a mock PyiCloudSession."""
    return MagicMock(spec=PyiCloudSession)


@pytest.fixture
def contacts_service(mock_session: MagicMock) -> ContactsService:  # pylint: disable=redefined-outer-name
    """Fixture to create a ContactsService instance."""
    return ContactsService(
        service_root=EXAMPLE_DOMAIN,
        session=mock_session,
        params={"test_param": "value"},
    )


@pytest.fixture
def mock_photos_service() -> MagicMock:
    """Fixture for mocking PhotosService."""
    service = MagicMock()
    service.service_endpoint = EXAMPLE_DOMAIN
    service.params = {"dsid": "12345"}
    service.session = MagicMock()
    return service


@pytest.fixture
def mock_photo_library(mock_photos_service: MagicMock) -> MagicMock:  # pylint: disable=redefined-outer-name
    """Fixture for mocking PhotoLibrary."""
    library = MagicMock()
    library.service = mock_photos_service
    return library


@pytest.fixture
def hidemyemail_service(mock_session: MagicMock) -> HideMyEmailService:  # pylint: disable=redefined-outer-name
    """Fixture for initializing HideMyEmailService."""
    return HideMyEmailService(EXAMPLE_DOMAIN, mock_session, {"dsid": "12345"})


@pytest.fixture
def mock_service_with_cookies(
    pyicloud_service_working: PyiCloudService,  # pylint: disable=redefined-outer-name
) -> PyiCloudService:
    """Fixture to create a mock PyiCloudService with cookies."""
    jar = RequestsCookieJar()
    jar.set(COOKIE_APPLE_WEBAUTH_VALIDATE, "t=768y9u", domain="icloud.com", path="/")

    # Attach a real CookieJar so code that calls `.cookies.get()` keeps working.
    pyicloud_service_working.session.cookies = jar

    return pyicloud_service_working