1import json
2
3from conftest import need_to_install_package_err
4
5import pytest
6
7import requests
8
9try:
10    from esptool.targets import CHIP_DEFS
11except ImportError:
12    need_to_install_package_err()
13
14
15FAMILIES_URL = (
16    "https://raw.githubusercontent.com/microsoft/uf2/master/utils/uf2families.json"
17)
18
19
20@pytest.fixture(scope="class")
21def uf2_json():
22    """Download UF2 family IDs from Microsoft UF2 repo and filter out ESP chips"""
23    res = requests.get(FAMILIES_URL)
24    assert res.status_code == 200
25    uf2_families_json = json.loads(res.content)
26    # filter out just ESP chips
27    chips = [
28        chip
29        for chip in uf2_families_json
30        if chip["short_name"].upper().startswith("ESP")
31    ]
32    return chips
33
34
35def test_check_uf2family_ids(uf2_json):
36    """Compare UF2 family IDs from Microsoft UF2 repo and with stored values"""
37    # check if all UF2 family ids match
38    for chip in uf2_json:
39        assert int(chip["id"], 0) == CHIP_DEFS[chip["short_name"].lower()].UF2_FAMILY_ID
40
41
42def test_check_uf2(uf2_json):
43    """Check if all non-beta chip definition has UF2 family id in esptool
44    and also in Microsoft repo
45    """
46    # remove beta chip definitions
47    esptool_chips = set(
48        [chip.upper() for chip in CHIP_DEFS.keys() if "beta" not in chip]
49    )
50    microsoft_repo_chips = set([chip["short_name"] for chip in uf2_json])
51    diff = esptool_chips.symmetric_difference(microsoft_repo_chips)
52    if diff:
53        out = []
54        # there was a difference between the chip support
55        for chip in diff:
56            if chip not in esptool_chips:
57                out.append(
58                    f"Missing chip definition for '{chip}' in esptool "
59                    "which was defined in Microsoft UF2 Github repo."
60                )
61            else:
62                out.append(
63                    f"Please consider adding support for chip '{chip}' "
64                    f"to the UF2 repository: {FAMILIES_URL}"
65                )
66        pytest.fail("\n".join(out))
67