Repository: bimmerconnected/bimmer_connected
Pull request #481 (2022-08-29 19:23:53)

Add fingerprint to dict function
## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->
As suggested in https://github.com/home-assistant/core/pull/74871#discussion_r956785356, this PR adds a function that returns the fingerprint files as dictionary (with key = filename and value = API response).

## Type of change
- [ ] Bugfix (non-breaking change which fixes an issue)
- [x] New feature (which adds functionality to this library)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #
- This PR is related to issue: https://github.com/home-assistant/core/pull/74871#discussion_r956785356

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [x] The code change is tested and works locally.
- [x] Tests have been added to verify that the new code works.


codecov-commenter: # [Codecov](https://codecov.io/gh/bimmerconnected/bimmer_connected/pull/481?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected) Report
> Merging [#481](https://codecov.io/gh/bimmerconnected/bimmer_connected/pull/481?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected) (58152e8) into [master](https://codecov.io/gh/bimmerconnected/bimmer_connected/commit/0121990cbcf1b192ac9bc2f5a90ec59d87670e03?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected) (0121990) will **not change** coverage.
> The diff coverage is `100.00%`.

```diff
@@            Coverage Diff            @@
##            master      #481   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           16        16           
  Lines         1221      1236   +15     
=========================================
+ Hits          1221      1236   +15     
```

| Flag | Coverage Δ | |
|---|---|---|
| 3.10.x | `100.00% <100.00%> (ø)` | |

Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected#carryforward-flags-in-the-pull-request-comment) to find out more.

| [Impacted Files](https://codecov.io/gh/bimmerconnected/bimmer_connected/pull/481?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected) | Coverage Δ | |
|---|---|---|
| [bimmer\_connected/account.py](https://codecov.io/gh/bimmerconnected/bimmer_connected/pull/481/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected#diff-YmltbWVyX2Nvbm5lY3RlZC9hY2NvdW50LnB5) | `100.00% <100.00%> (ø)` | |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=bimmerconnected)


Patch:
diff --git a/bimmer_connected/account.py b/bimmer_connected/account.py
index e06c366..3588463 100644
--- a/bimmer_connected/account.py
+++ b/bimmer_connected/account.py
@@ -1,10 +1,12 @@
 """Access to a MyBMW account and all vehicles therein."""
 
 import datetime
+import json
 import logging
 import pathlib
 from dataclasses import InitVar, dataclass, field
-from typing import List, Optional
+from tempfile import TemporaryDirectory
+from typing import Any, Dict, List, Optional
 
 import httpx
 
@@ -86,6 +88,26 @@ class MyBMWAccount:  # pylint: disable=too-many-instance-attributes
 
                     self.add_vehicle(vehicle_base, vehicle_state, fetched_at)
 
+    async def get_fingerprints(self) -> Dict[str, Any]:
+        """Retrieve vehicle data from BMW servers and return original responses as JSON."""
+        original_log_response_path = self.config.log_response_path
+        fingerprints = {}
+
+        try:
+            # Use a temporary directory to just get the files from one call to get_vehicles()
+            with TemporaryDirectory() as tempdir:
+                tempdir_path = pathlib.Path(tempdir)
+                self.config.log_response_path = tempdir_path
+                await self.get_vehicles()
+                for logfile in tempdir_path.iterdir():
+                    with open(logfile, "rb") as pointer:
+                        fingerprints[logfile.name] = json.load(pointer)
+        finally:
+            # Make sure that log_response_path is always set to the original value afterwards
+            self.config.log_response_path = original_log_response_path
+
+        return fingerprints
+
     def add_vehicle(self, vehicle_base: dict, vehicle_state: dict, fetched_at: datetime.datetime = None) -> None:
         """Add or update a vehicle from the API responses."""
 


Test patch:
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 4ddcc76..9880d56 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -32,7 +32,7 @@ jobs:
       - name: Upload coverage to Codecov
         uses: codecov/codecov-action@v3
         with:
-          fail_ci_if_error: true
+          fail_ci_if_error: false
           files: ./coverage.xml
           name: "pytest-${{ matrix.python-version }}"
           flags: "${{ matrix.python-version }}"
diff --git a/test/test_account.py b/test/test_account.py
index 9e9d391..7d41724 100644
--- a/test/test_account.py
+++ b/test/test_account.py
@@ -545,3 +545,17 @@ async def test_client_async_only():
     with httpx.Client(auth=MyBMWLoginRetry()) as client:
         with pytest.raises(RuntimeError):
             client.get("/eadrax-ucs/v1/presentation/oauth/config")
+
+
+@pytest.mark.asyncio
+async def test_get_fingerprints():
+    """Test get_fingerprints to JSON."""
+    with account_mock():
+        account = MyBMWAccount(TEST_USERNAME, TEST_PASSWORD, TEST_REGION)
+
+        fingerprints = await account.get_fingerprints()
+
+        assert len([f for f in fingerprints if f.startswith("vehicles")]) == 2
+        assert len([f for f in fingerprints if f.startswith("state_bmw")]) == len(ALL_FINGERPRINTS.get("bmw", {}))
+        assert len([f for f in fingerprints if f.startswith("state_mini")]) == len(ALL_FINGERPRINTS.get("mini", {}))
+        assert len([f for f in fingerprints if f.startswith("state")]) == get_fingerprint_count()