File: test_cli.py

package info (click to toggle)
python-bimmer-connected 0.16.3-1.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,304 kB
  • sloc: python: 4,469; makefile: 15
file content (300 lines) | stat: -rw-r--r-- 10,873 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
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
import contextlib
import json
import subprocess
import sys
from pathlib import Path

import httpx
import pytest
import respx

import bimmer_connected.cli
from bimmer_connected import __version__ as VERSION

from . import RESPONSE_DIR, get_fingerprint_count, load_response

ARGS_USER_PW_REGION = ["myuser", "mypassword", "rest_of_world"]
FIXTURE_CLI_HELP = "Connect to MyBMW/MINI API and interact with your vehicle."


def test_run_entrypoint():
    """Test if the entrypoint is installed correctly."""
    result = subprocess.run(["bimmerconnected", "--help"], capture_output=True, text=True)

    assert FIXTURE_CLI_HELP in result.stdout
    assert VERSION in result.stdout
    assert result.returncode == 0


def test_run_module():
    """Test if the module can be run as a python module."""
    result = subprocess.run(["python3", "-m", "bimmer_connected.cli", "--help"], capture_output=True, text=True)

    assert FIXTURE_CLI_HELP in result.stdout
    assert VERSION in result.stdout
    assert result.returncode == 0


@pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("cli_home_dir")
@pytest.mark.parametrize(
    ("vin", "expected_count"),
    [
        ("WBA00000000000F31", 1),
        ("WBA00000000000F31,WBA00000000DEMO03", 0),
        ("WBA00000000000Z99", 0),
    ],
)
def test_status_json_filtered(capsys: pytest.CaptureFixture, vin, expected_count):
    """Test the status command JSON output filtered by VIN."""

    sys.argv = ["bimmerconnected", "status", "-j", "-v", vin, *ARGS_USER_PW_REGION]
    with contextlib.suppress(SystemExit):
        bimmer_connected.cli.main()
    result = capsys.readouterr()

    if expected_count == 1:
        result_json = json.loads(result.out)
        assert isinstance(result_json, dict)
        assert result_json["vin"] == vin
    else:
        assert "Error: Could not find vehicle" in result.err


@pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("cli_home_dir")
def test_status_json_unfiltered(capsys: pytest.CaptureFixture):
    """Test the status command JSON output filtered by VIN."""

    sys.argv = ["bimmerconnected", "status", "-j", *ARGS_USER_PW_REGION]
    bimmer_connected.cli.main()
    result = capsys.readouterr()

    result_json = json.loads(result.out)
    assert isinstance(result_json, list)
    assert len(result_json) == get_fingerprint_count("states")


@pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("cli_home_dir")
@pytest.mark.parametrize(
    ("vin", "expected_count"),
    [
        ("WBA00000000000F31", 1),
        ("WBA00000000000F31,WBA00000000DEMO03", 0),
        ("WBA00000000000Z99", 0),
    ],
)
def test_status_filtered(capsys: pytest.CaptureFixture, vin, expected_count):
    """Test the status command text output filtered by VIN."""

    sys.argv = ["bimmerconnected", "status", "-v", vin, *ARGS_USER_PW_REGION]
    with contextlib.suppress(SystemExit):
        bimmer_connected.cli.main()
    result = capsys.readouterr()

    assert f"Found {get_fingerprint_count('states')} vehicles" in result.out

    if expected_count == 1:
        assert f"VIN: {vin}" in result.out
        assert result.out.count("VIN: ") == expected_count
    else:
        assert result.out.count("VIN: ") == expected_count


@pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("cli_home_dir")
def test_status_unfiltered(capsys: pytest.CaptureFixture):
    """Test the status command text output filtered by VIN."""

    sys.argv = ["bimmerconnected", "status", *ARGS_USER_PW_REGION]
    bimmer_connected.cli.main()
    result = capsys.readouterr()

    assert f"Found {get_fingerprint_count('states')} vehicles" in result.out
    assert result.out.count("VIN: ") == get_fingerprint_count("states")


@pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("bmw_log_all_responses")
def test_fingerprint(capsys: pytest.CaptureFixture, cli_home_dir: Path):
    """Test the fingerprint command."""

    sys.argv = ["bimmerconnected", "fingerprint", *ARGS_USER_PW_REGION]
    bimmer_connected.cli.main()
    result = capsys.readouterr()

    assert "fingerprint of the vehicles written to" in result.out

    files = list((cli_home_dir / "vehicle_fingerprint").rglob("*"))
    json_files = [f for f in files if f.suffix == ".json"]
    txt_files = [f for f in files if f.suffix == ".txt"]

    assert len(json_files) == (
        get_fingerprint_count("vehicles")
        + get_fingerprint_count("profiles")
        + get_fingerprint_count("states")
        + get_fingerprint_count("charging_settings")
    )
    assert len(txt_files) == 0


@pytest.mark.usefixtures("cli_home_dir")
def test_oauth_store_credentials(cli_home_dir: Path, bmw_fixture: respx.Router):
    """Test storing the oauth credentials."""

    assert (cli_home_dir / ".bimmer_connected.json").exists() is False

    sys.argv = ["bimmerconnected", "status", *ARGS_USER_PW_REGION]
    bimmer_connected.cli.main()

    assert bmw_fixture.routes["token"].call_count == 1
    assert bmw_fixture.routes["vehicles"].calls[0].request.headers["authorization"] == "Bearer some_token_string"

    assert (cli_home_dir / ".bimmer_connected.json").exists() is True
    oauth_storage = json.loads((cli_home_dir / ".bimmer_connected.json").read_text())

    assert set(oauth_storage.keys()) == {"access_token", "refresh_token", "gcid"}


# @pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("cli_home_dir")
def test_oauth_load_credentials(cli_home_dir: Path, bmw_fixture: respx.Router):
    """Test loading and storing the oauth credentials."""

    demo_oauth_data = {
        "access_token": "demo_access_token",
        "refresh_token": "demo_refresh_token",
        "gcid": "demo_gcid",
    }

    (cli_home_dir / ".bimmer_connected.json").write_text(json.dumps(demo_oauth_data))
    assert (cli_home_dir / ".bimmer_connected.json").exists() is True

    sys.argv = ["bimmerconnected", "status", *ARGS_USER_PW_REGION]

    bimmer_connected.cli.main()

    assert bmw_fixture.routes["token"].call_count == 0
    assert bmw_fixture.routes["vehicles"].calls[0].request.headers["authorization"] == "Bearer demo_access_token"

    assert (cli_home_dir / ".bimmer_connected.json").exists() is True
    oauth_storage = json.loads((cli_home_dir / ".bimmer_connected.json").read_text())

    assert set(oauth_storage.keys()) == {"access_token", "refresh_token", "gcid"}

    # no change as the old tokens are still valid
    assert oauth_storage["refresh_token"] == demo_oauth_data["refresh_token"]
    assert oauth_storage["access_token"] == demo_oauth_data["access_token"]
    assert oauth_storage["gcid"] == demo_oauth_data["gcid"]


@pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("cli_home_dir")
@pytest.mark.parametrize(
    ("filepath"),
    [
        (".bimmer_connected.json"),
        ("other-dir/myfile.json"),
    ],
)
def test_oauth_store_credentials_path(cli_home_dir: Path, tmp_path_factory: pytest.TempPathFactory, filepath: str):
    """Test storing the oauth credentials to another file."""

    new_folder = tmp_path_factory.mktemp("specific-path-")

    assert (cli_home_dir / ".bimmer_connected.json").exists() is False
    assert (new_folder / filepath).exists() is False

    sys.argv = [
        "bimmerconnected",
        "--oauth-store",
        str((new_folder / filepath).absolute()),
        "status",
        *ARGS_USER_PW_REGION,
    ]
    bimmer_connected.cli.main()

    assert (cli_home_dir / ".bimmer_connected.json").exists() is False
    assert (new_folder / filepath).exists() is True

    oauth_storage = json.loads((new_folder / filepath).read_text())

    assert set(oauth_storage.keys()) == {"access_token", "refresh_token", "gcid"}


@pytest.mark.usefixtures("bmw_fixture")
@pytest.mark.usefixtures("cli_home_dir")
def test_oauth_store_credentials_disabled(cli_home_dir: Path):
    """Test NOT storing the oauth credentials."""

    assert (cli_home_dir / ".bimmer_connected.json").exists() is False

    sys.argv = ["bimmerconnected", "--disable-oauth-store", "status", *ARGS_USER_PW_REGION]
    bimmer_connected.cli.main()

    assert (cli_home_dir / ".bimmer_connected.json").exists() is False


@pytest.mark.usefixtures("cli_home_dir")
def test_login_refresh_token(cli_home_dir: Path, bmw_fixture: respx.Router):
    """Test logging in with refresh token."""

    # set up stored tokens
    demo_oauth_data = {
        "access_token": "outdated_access_token",
        "refresh_token": "demo_refresh_token",
        "gcid": "demo_gcid",
    }

    (cli_home_dir / ".bimmer_connected.json").write_text(json.dumps(demo_oauth_data))
    assert (cli_home_dir / ".bimmer_connected.json").exists() is True

    vehicle_routes = bmw_fixture.pop("vehicles")
    bmw_fixture.post("/eadrax-vcs/v5/vehicle-list", name="vehicles").mock(
        side_effect=[
            httpx.Response(401, json=load_response(RESPONSE_DIR / "auth" / "auth_error_wrong_password.json")),
            *[vehicle_routes.side_effect for _ in range(1000)],  # type: ignore[list-item]
        ]
    )

    sys.argv = ["bimmerconnected", "--debug", "status", *ARGS_USER_PW_REGION]
    bimmer_connected.cli.main()

    assert bmw_fixture.routes["token"].call_count == 1
    # TODO: The following doesn't work with MyBMWMockRouter.using = "httpx"
    # Need to wait for a respx update supporting httpx>=0.28.0 natively
    # assert bmw_fixture.routes["vehicles"].calls[0].request.headers["authorization"] == "Bearer outdated_access_token"
    assert bmw_fixture.routes["vehicles"].calls.last.request.headers["authorization"] == "Bearer some_token_string"

    assert (cli_home_dir / ".bimmer_connected.json").exists() is True


@pytest.mark.usefixtures("cli_home_dir")
def test_login_invalid_refresh_token(cli_home_dir: Path, bmw_fixture: respx.Router):
    """Test logging in with an invalid refresh token."""

    # set up stored tokens
    demo_oauth_data = {
        "refresh_token": "invalid_refresh_token",
        "gcid": "demo_gcid",
    }

    (cli_home_dir / ".bimmer_connected.json").write_text(json.dumps(demo_oauth_data))
    assert (cli_home_dir / ".bimmer_connected.json").exists() is True

    bmw_fixture.post("/gcdm/oauth/token", name="token").mock(
        side_effect=[
            httpx.Response(401, json=load_response(RESPONSE_DIR / "auth" / "auth_error_wrong_password.json")),
            *[httpx.Response(200, json=load_response(RESPONSE_DIR / "auth" / "auth_token.json")) for _ in range(1000)],
        ]
    )

    sys.argv = ["bimmerconnected", "status", *ARGS_USER_PW_REGION]
    bimmer_connected.cli.main()

    assert bmw_fixture.routes["token"].call_count == 2
    assert bmw_fixture.routes["authenticate"].call_count == 2
    assert bmw_fixture.routes["vehicles"].calls[0].request.headers["authorization"] == "Bearer some_token_string"

    assert (cli_home_dir / ".bimmer_connected.json").exists() is True