cronometer-mcp 2.4.3__tar.gz → 2.4.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/PKG-INFO +2 -2
  2. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/README.md +1 -1
  3. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/RESEARCH-copy-repeat-gwt-rpc.md +1 -1
  4. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/cronometer_mcp/__init__.py +1 -1
  5. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/cronometer_mcp/client.py +62 -160
  6. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/cronometer_mcp/server.py +10 -9
  7. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/pyproject.toml +1 -1
  8. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/server.json +2 -2
  9. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/test_client.py +131 -121
  10. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/test_live.py +1 -1
  11. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/.github/workflows/drift.yml +0 -0
  12. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/.github/workflows/publish.yml +0 -0
  13. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/.gitignore +0 -0
  14. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/AGENTS.md +0 -0
  15. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/CLAUDE.md +0 -0
  16. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/LICENSE +0 -0
  17. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/SPEC-diary-groups.md +0 -0
  18. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/SPEC-streamable-http.md +0 -0
  19. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/cronometer_mcp/markdown.py +0 -0
  20. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/release.sh +0 -0
  21. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/__init__.py +0 -0
  22. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/test_diary_groups.py +0 -0
  23. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/test_drift.py +0 -0
  24. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/test_live_gate.py +0 -0
  25. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/test_markdown.py +0 -0
  26. {cronometer_mcp-2.4.3 → cronometer_mcp-2.4.4}/tests/test_server.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cronometer-mcp
3
- Version: 2.4.3
3
+ Version: 2.4.4
4
4
  Summary: MCP server for Cronometer nutrition data — pull food logs, macros, and micronutrients via the Model Context Protocol
5
5
  Project-URL: Homepage, https://github.com/cphoskins/cronometer-mcp
6
6
  Project-URL: Repository, https://github.com/cphoskins/cronometer-mcp
@@ -190,7 +190,7 @@ the credentials themselves keep full access.
190
190
  |------|-------------|
191
191
  | `search_foods` | Search the Cronometer food database |
192
192
  | `list_diary_groups` | List this account's diary groups and the values `diary_group` accepts |
193
- | `get_food_details` | Get full nutrition info and serving measure IDs for a food |
193
+ | `get_food_details` | List a food's serving measures with their gram weights |
194
194
  | `add_food_entry` | Add a food entry to the diary |
195
195
  | `remove_food_entry` | Remove a food entry from the diary |
196
196
  | `copy_day` | Copy all diary entries from one date to another |
@@ -166,7 +166,7 @@ the credentials themselves keep full access.
166
166
  |------|-------------|
167
167
  | `search_foods` | Search the Cronometer food database |
168
168
  | `list_diary_groups` | List this account's diary groups and the values `diary_group` accepts |
169
- | `get_food_details` | Get full nutrition info and serving measure IDs for a food |
169
+ | `get_food_details` | List a food's serving measures with their gram weights |
170
170
  | `add_food_entry` | Add a food entry to the diary |
171
171
  | `remove_food_entry` | Remove a food entry from the diary |
172
172
  | `copy_day` | Copy all diary entries from one date to another |
@@ -363,7 +363,7 @@ Methods captured during session initialization:
363
363
  - `getAllFood` - full nutrition data for all foods in current diary
364
364
  - `getDashboardConfig` - dashboard layout
365
365
  - `getBrazeEvents` - analytics events
366
- - `getFood` - detailed food data for a specific food
366
+ - `getFood` - detailed food data for a specific food (removed by 2026-12-05; now REST `GET /api/v3/food/{id}`)
367
367
  - `getCaloriesConsumedAndBurned` - energy balance
368
368
  - `getBiometrics` - biometric measurements
369
369
  - `getSleepBiometricsByDayAndMetricId` - sleep data
@@ -1,6 +1,6 @@
1
1
  """Cronometer MCP Server — nutrition data from Cronometer via MCP."""
2
2
 
3
- __version__ = "2.4.3"
3
+ __version__ = "2.4.4"
4
4
 
5
5
  from .client import CronometerClient
6
6
  from .markdown import generate_food_log_md
@@ -35,11 +35,14 @@ EXPORT_URL = "https://cronometer.com/export"
35
35
  # parameter type was removed from Cronometer's serialization policy, so
36
36
  # calling it returns IncompatibleRemoteServiceException.
37
37
  FOOD_SEARCH_URL = "https://cronometer.com/api/v3/user/{user_id}/food-search/string"
38
+ # Food details moved to REST too (observed 2026-12-05): the getFood RPC is gone
39
+ # from CronometerService and returns IncompatibleRemoteServiceException.
40
+ FOOD_URL = "https://cronometer.com/api/v3/food/{food_source_id}"
38
41
  GWT_NOCACHE_JS_URL = "https://cronometer.com/cronometer/cronometer.nocache.js"
39
42
  GWT_CACHE_JS_URL = "https://cronometer.com/cronometer/{permutation}.cache.js"
40
43
 
41
44
  # NCCDB "universal" measure_id that works for any food in updateDiary.
42
- # CRDB foods have food-specific measure_ids in their getFood response,
45
+ # CRDB foods have food-specific measure_ids in their get_food response,
43
46
  # but those IDs cause "ghost entries" (counted but invisible in diary).
44
47
  # Using an NCCDB measure_id (here: eggs' "mL chopped" measure) with the
45
48
  # correct weight_grams produces working entries for ALL food sources.
@@ -110,15 +113,6 @@ GWT_REMOVE_SERVING = (
110
113
  "J|I|{nonce}|1|2|3|4|3|5|6|7|8|{serving_id}|{user_id}|"
111
114
  )
112
115
 
113
- GWT_GET_FOOD = (
114
- "7|0|7|https://cronometer.com/cronometer/|"
115
- "{gwt_header}|"
116
- "com.cronometer.shared.rpc.CronometerService|"
117
- "getFood|java.lang.String/2004016611|"
118
- "I|{nonce}|"
119
- "1|2|3|4|2|5|6|7|{food_source_id}|"
120
- )
121
-
122
116
  GWT_GET_ALL_MACRO_SCHEDULES = (
123
117
  "7|0|7|https://cronometer.com/cronometer/|"
124
118
  "{gwt_header}|"
@@ -1067,25 +1061,43 @@ class CronometerClient:
1067
1061
  Unlike the old RPC, this returns both ids, so a follow-up get_food()
1068
1062
  call is no longer needed just to resolve food_id.
1069
1063
  """
1064
+ self.authenticate() # sets user_id, which the URL needs
1065
+ hits = self._rest_get_json(
1066
+ FOOD_SEARCH_URL.format(user_id=self.user_id),
1067
+ params={
1068
+ "query": query.upper(),
1069
+ "maxResults": max_results,
1070
+ "sources": "All",
1071
+ "categoryId": 0,
1072
+ "selectedTab": "ALL",
1073
+ "type": "All",
1074
+ },
1075
+ )
1076
+ return [self._map_search_hit(hit) for hit in hits]
1077
+
1078
+ def _rest_get_json(self, url: str, params: dict | None = None):
1079
+ """GET a cookie-authenticated REST endpoint and return its JSON.
1080
+
1081
+ Logs in again once on 401/403 or on a 200 that is not JSON (an
1082
+ expired session can land on the login page after a redirect).
1083
+ """
1070
1084
  self.authenticate()
1071
1085
  for attempt in range(2):
1072
- resp = self.session.get(
1073
- FOOD_SEARCH_URL.format(user_id=self.user_id),
1074
- params={
1075
- "query": query.upper(),
1076
- "maxResults": max_results,
1077
- "sources": "All",
1078
- "categoryId": 0,
1079
- "selectedTab": "ALL",
1080
- "type": "All",
1081
- },
1082
- timeout=REQUEST_TIMEOUT,
1083
- )
1086
+ resp = self.session.get(url, params=params, timeout=REQUEST_TIMEOUT)
1084
1087
  if resp.status_code in (401, 403) and not attempt:
1085
1088
  self._reauthenticate()
1086
1089
  continue
1087
1090
  resp.raise_for_status()
1088
- return [self._map_search_hit(hit) for hit in resp.json()]
1091
+ try:
1092
+ return resp.json()
1093
+ except ValueError:
1094
+ if not attempt:
1095
+ self._reauthenticate()
1096
+ continue
1097
+ raise RuntimeError(
1098
+ f"Cronometer response from {url} is not JSON, even after "
1099
+ f"logging in again (landed on {getattr(resp, 'url', url)})."
1100
+ ) from None
1089
1101
 
1090
1102
  @staticmethod
1091
1103
  def _map_search_hit(hit: dict) -> dict:
@@ -1274,6 +1286,8 @@ class CronometerClient:
1274
1286
  def get_food(self, food_source_id: int) -> dict:
1275
1287
  """Get detailed food information including available measures.
1276
1288
 
1289
+ Backed by FOOD_URL, not GWT-RPC: Cronometer removed the getFood RPC.
1290
+
1277
1291
  Args:
1278
1292
  food_source_id: Food source ID from find_foods results.
1279
1293
 
@@ -1281,149 +1295,37 @@ class CronometerClient:
1281
1295
  Dict with keys:
1282
1296
 
1283
1297
  - ``food_source_id`` (int): Echo of the input.
1284
- - ``raw_response`` (str): Raw GWT-RPC response for debugging.
1285
1298
  - ``measures`` (list[dict]): Available serving measures, each with:
1286
- - ``measure_id`` (int): Numeric ID needed by add_serving.
1287
- - ``description`` (str): Human-readable description
1288
- (e.g. ``"1 large - 50g"``).
1299
+ - ``measure_id`` (int): Cronometer's REST measure id. Not for
1300
+ add_serving: these ids exceed the 16 bits add_serving keeps,
1301
+ so pass measure_id=0 there with this measure's weight_grams.
1302
+ - ``description`` (str): Measure name (e.g. ``"large"``).
1289
1303
  - ``weight_grams`` (float): Weight in grams for this measure.
1290
- """
1291
- self.authenticate()
1292
- body = (
1293
- GWT_GET_FOOD
1294
- .replace("{gwt_header}", self.gwt_header)
1295
- .replace("{nonce}", self.nonce or "")
1296
- .replace("{food_source_id}", str(food_source_id))
1297
- )
1298
- raw = self._gwt_post(body)
1299
- return self._parse_get_food(raw, food_source_id)
1300
1304
 
1301
- @staticmethod
1302
- def _parse_get_food(raw: str, food_source_id: int) -> dict:
1303
- """Parse a getFood GWT-RPC response to extract measure information.
1304
-
1305
- The response contains food metadata and a list of Measure objects.
1306
- Each Measure has fields (reading backwards from the Measure type ref):
1307
-
1308
- i-6 description_ref (1-based string table index)
1309
- i-5 flags (0)
1310
- i-4 measure_id (integer, the key value needed by add_serving)
1311
- i-3 food_source_id
1312
- i-2 flags (0)
1313
- i-1 quantity (1.0)
1314
- i <Measure type ref>
1315
-
1316
- Weight in grams is a float that appears earlier in the token stream,
1317
- before the Measure$Type ref/back-ref for each measure.
1305
+ Derived measures are left out, as the GWT parser did before.
1318
1306
  """
1319
- result: dict = {
1320
- "food_source_id": food_source_id,
1321
- "measures": [],
1322
- }
1323
-
1324
- if not raw.startswith("//OK[") or not raw.endswith(",0,7]"):
1325
- return result
1326
-
1327
- # Extract string table
1328
- closing = ",0,7]"
1329
- st_close = len(raw) - len(closing) - 1
1330
- depth, pos, in_str = 1, st_close - 1, False
1331
- while pos >= 0 and depth > 0:
1332
- ch = raw[pos]
1333
- if ch == '"' and (pos == 0 or raw[pos - 1] != "\\"):
1334
- in_str = not in_str
1335
- elif not in_str:
1336
- if ch == "]":
1337
- depth += 1
1338
- elif ch == "[":
1339
- depth -= 1
1340
- pos -= 1
1341
- st_open = pos + 1
1342
- string_table: list[str] = json.loads(raw[st_open : st_close + 1])
1343
-
1344
- def _resolve(ref: int) -> str | None:
1345
- if 1 <= ref <= len(string_table):
1346
- return string_table[ref - 1]
1347
- return None
1348
-
1349
- # Find Measure class index in string table
1350
- measure_type_idx: int | None = None
1351
- for idx, entry in enumerate(string_table):
1352
- if entry.startswith("["):
1353
- continue
1354
- if "Measure/" in entry and "Measure$" not in entry and "Derived" not in entry:
1355
- if measure_type_idx is None:
1356
- measure_type_idx = idx + 1
1357
-
1358
- if measure_type_idx is None:
1359
- return result
1360
-
1361
- # Tokenize data section — preserve floats
1362
- data_section = raw[5:st_open].rstrip(",")
1363
- if not data_section:
1364
- return result
1365
-
1366
- tokens: list = []
1367
- for part in data_section.split(","):
1368
- part = part.strip()
1369
- if not part:
1370
- continue
1371
- # Handle quoted strings (e.g. serving_id in Food metadata)
1372
- if part.startswith('"') and part.endswith('"'):
1373
- tokens.append(part)
1374
- continue
1375
- try:
1376
- tokens.append(float(part) if "." in part else int(part))
1377
- except ValueError:
1378
- tokens.append(None)
1379
-
1380
- # Scan for Measure type-index occurrences and extract fields.
1381
- measures = []
1382
- for i, token in enumerate(tokens):
1383
- if token != measure_type_idx:
1384
- continue
1385
- if i < 6:
1307
+ food = self._rest_get_json(FOOD_URL.format(food_source_id=food_source_id))
1308
+ measures = food.get("measures") if isinstance(food, dict) else None
1309
+ if not isinstance(measures, list):
1310
+ raise ValueError(f"Food {food_source_id}: no measures list in response")
1311
+ result = []
1312
+ for m in measures:
1313
+ if not isinstance(m, dict):
1314
+ raise ValueError(f"Food {food_source_id}: malformed measure {m!r}")
1315
+ if m.get("derived"):
1386
1316
  continue
1387
-
1388
- measure_id_val = tokens[i - 4]
1389
-
1390
- if not isinstance(measure_id_val, int):
1391
- continue
1392
-
1393
- # Description ref is at i-6 for standard Measure layout, but
1394
- # CRDB foods with a boxed Double field shift it to i-7 or i-8.
1395
- # Scan multiple offsets to find a valid description string.
1396
- description = ""
1397
- for offset in (6, 7, 8):
1398
- if i < offset:
1399
- continue
1400
- ref = tokens[i - offset]
1401
- if isinstance(ref, int) and 1 <= ref <= len(string_table):
1402
- candidate = string_table[ref - 1]
1403
- if (candidate
1404
- and not candidate.startswith("com.")
1405
- and not candidate.startswith("java.")
1406
- and not candidate.startswith("[")):
1407
- description = candidate
1408
- break
1409
-
1410
- # Find weight_grams: it's the float that appears before the
1411
- # Measure$Type ref/back-ref, which is at i-7 or i-8.
1412
- # Scan backwards from i-7 to find the first float.
1413
- weight_grams = 0.0
1414
- for j in range(i - 7, max(i - 12, -1), -1):
1415
- if isinstance(tokens[j], float):
1416
- weight_grams = tokens[j]
1417
- break
1418
-
1419
- measures.append({
1420
- "measure_id": measure_id_val,
1421
- "description": description or "",
1422
- "weight_grams": round(weight_grams, 2),
1317
+ mid, grams = m.get("id"), m.get("value")
1318
+ if (not isinstance(mid, int) or not isinstance(grams, (int, float))
1319
+ or isinstance(mid, bool) or isinstance(grams, bool)):
1320
+ raise ValueError(
1321
+ f"Food {food_source_id}: malformed measure (id={mid!r}, value={grams!r})"
1322
+ )
1323
+ result.append({
1324
+ "measure_id": mid,
1325
+ "description": m.get("name") or "",
1326
+ "weight_grams": round(grams, 2),
1423
1327
  })
1424
-
1425
- result["measures"] = measures
1426
- return result
1328
+ return {"food_source_id": food_source_id, "measures": result}
1427
1329
 
1428
1330
  def add_serving(
1429
1331
  self,
@@ -469,7 +469,7 @@ def search_foods(query: str) -> str:
469
469
  """Search Cronometer's food database by name.
470
470
 
471
471
  Returns matching foods with their IDs and source information needed
472
- to add a serving (food_id, food_source_id, measure_id).
472
+ to add a serving (food_id, food_source_id).
473
473
 
474
474
  Args:
475
475
  query: Food name or keyword to search for (e.g. "eggs", "chicken breast").
@@ -494,8 +494,10 @@ def search_foods(query: str) -> str:
494
494
  def get_food_details(food_source_id: int) -> str:
495
495
  """Get detailed food information including available serving measures.
496
496
 
497
- Use this after search_foods to get the measure_id needed for add_food_entry.
498
- Returns all available serving sizes with their numeric IDs and gram weights.
497
+ Use this after search_foods to find a serving's gram weight (e.g. one
498
+ large egg = 50 g), then call add_food_entry with that weight_grams and
499
+ measure_id left at 0. The measure_id values listed here are for reference
500
+ only: don't pass them to add_food_entry.
499
501
 
500
502
  Args:
501
503
  food_source_id: Food source ID from search_foods results.
@@ -503,7 +505,6 @@ def get_food_details(food_source_id: int) -> str:
503
505
  try:
504
506
  client = _get_client()
505
507
  result = client.get_food(food_source_id)
506
- # Remove raw_response from the output to keep it clean
507
508
  output = {
508
509
  "status": "success",
509
510
  "food_source_id": result["food_source_id"],
@@ -526,12 +527,12 @@ def add_food_entry(
526
527
  ) -> str:
527
528
  """Add a food entry to the Cronometer diary.
528
529
 
529
- Use search_foods to find food_id and food_source_id, then
530
- get_food_details for measure_id and weight_grams.
530
+ Use search_foods to find food_id and food_source_id, and
531
+ get_food_details for a serving's weight_grams.
531
532
 
532
- For CRDB/custom foods, you can omit measure_id (defaults to a
533
- universal NCCDB measure that works for all food sources).
534
- When measure_id is omitted, quantity is set to weight_grams.
533
+ Leave measure_id at 0 (the default): it uses a universal gram-based
534
+ measure that works for all food sources, and quantity is set to
535
+ weight_grams. Don't pass measure_id values from get_food_details.
535
536
 
536
537
  Args:
537
538
  food_id: Numeric food ID from search_foods results.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cronometer-mcp"
7
- version = "2.4.3"
7
+ version = "2.4.4"
8
8
  description = "MCP server for Cronometer nutrition data — pull food logs, macros, and micronutrients via the Model Context Protocol"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/cphoskins/cronometer-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "2.4.3",
9
+ "version": "2.4.4",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "pypi",
13
13
  "identifier": "cronometer-mcp",
14
- "version": "2.4.3",
14
+ "version": "2.4.4",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -745,145 +745,155 @@ class TestFindFoodsIntegration:
745
745
  assert food["food_id"] == 66395420
746
746
 
747
747
 
748
- # ---------------------------------------------------------------------------
749
- # Helper to build synthetic GWT-RPC getFood responses for unit tests.
750
- # ---------------------------------------------------------------------------
751
-
752
- def _build_get_food_response(measures: list[dict], include_derived: bool = False) -> str:
753
- """Build a minimal //OK[...] getFood response with Measure objects.
748
+ class TestGetFood:
749
+ """Tests for get_food() — now backed by the REST food API.
754
750
 
755
- Each measure dict must have: description, measure_id, food_source_id, weight_grams
751
+ Cronometer removed the getFood GWT-RPC method (2026-12-05: it no longer
752
+ appears in the CronometerService method table, and calling it returns
753
+ IncompatibleRemoteServiceException). The web app now fetches
754
+ GET /api/v3/food/{food_source_id}.
756
755
  """
757
- import json as _json
758
756
 
759
- class_names = [
760
- "com.cronometer.shared.foods.models.Food/1234567890",
761
- "com.cronometer.shared.foods.models.Measure/2345678901",
762
- "com.cronometer.shared.foods.models.Measure$Type/3456789012",
763
- ]
764
- if include_derived:
765
- class_names.append(
766
- "com.cronometer.shared.measurement.DerivedMeasure/9876543210"
757
+ @staticmethod
758
+ def _measure(measure_id, name, grams, derived=False):
759
+ """One REST measure, trimmed from a live response (eggs, 464674)."""
760
+ return {
761
+ "id": measure_id,
762
+ "name": name,
763
+ "value": grams,
764
+ "amount": 1.0,
765
+ "type": "Weight",
766
+ "derived": derived,
767
+ "derivable": False,
768
+ "hidden": False,
769
+ "translations": [],
770
+ }
771
+
772
+ def _mock_get(self, client, payload, status=200):
773
+ resp = MagicMock(status_code=status, json=lambda: payload)
774
+ resp.raise_for_status = MagicMock()
775
+ get_mock = MagicMock(return_value=resp)
776
+ client._authenticated = True
777
+ client.user_id = "42"
778
+ client.session.get = get_mock
779
+ client.session.post = MagicMock(
780
+ side_effect=AssertionError("get_food must not use GWT-RPC")
767
781
  )
782
+ return get_mock
768
783
 
769
- data_strings: list[str] = []
784
+ def test_hits_rest_food_url(self, client):
785
+ get_mock = self._mock_get(client, {"id": 464674, "measures": []})
770
786
 
771
- def _intern(s: str) -> int:
772
- combined = class_names + data_strings
773
- if s in combined:
774
- return combined.index(s) + 1
775
- data_strings.append(s)
776
- return len(class_names) + len(data_strings)
787
+ client.get_food(464674)
777
788
 
778
- measure_type_idx = 2 # Measure class is at index 2 (1-based)
779
- measure_subtype_idx = 3 # Measure$Type
789
+ assert get_mock.call_args[0][0] == "https://cronometer.com/api/v3/food/464674"
780
790
 
781
- # Build data tokens: some food metadata, then Measure objects.
782
- # Food metadata prefix (simplified): string_table_size, 0, food_type_ref=1
783
- data_tokens: list = []
791
+ def test_maps_measures(self, client):
792
+ self._mock_get(client, {"id": 464674, "measures": [
793
+ self._measure(1072101, "large", 50.0),
794
+ self._measure(1072106, "tsp, chopped", 2.8333570200000002),
795
+ ]})
784
796
 
785
- for m in measures:
786
- desc_ref = _intern(m["description"])
787
- # Layout: weight_grams, ..., Measure$Type ref, ...,
788
- # desc_ref, 0, measure_id, food_source_id, 0, 1.0, Measure type ref
789
- data_tokens += [
790
- m["weight_grams"], # weight_grams (float)
791
- 0, # padding
792
- measure_subtype_idx, # Measure$Type ref
793
- 0, # ordinal
794
- desc_ref, # description (i-6 from Measure type ref)
795
- 0, # flags (i-5)
796
- m["measure_id"], # measure_id (i-4)
797
- m["food_source_id"], # food_source_id (i-3)
798
- 0, # flags (i-2)
799
- 1.0, # quantity (i-1)
800
- measure_type_idx, # Measure type ref (i)
801
- ]
797
+ result = client.get_food(464674)
802
798
 
803
- if include_derived:
804
- derived_type_idx = len(class_names) # 1-based
805
- data_tokens += [
806
- 100.0, 0, measure_subtype_idx, 0,
807
- _intern("mL"), 0, 999999, 12345, 0, 1.0,
808
- derived_type_idx,
799
+ assert result["food_source_id"] == 464674
800
+ assert result["measures"] == [
801
+ {"measure_id": 1072101, "description": "large", "weight_grams": 50.0},
802
+ {"measure_id": 1072106, "description": "tsp, chopped", "weight_grams": 2.83},
809
803
  ]
810
804
 
811
- string_table = class_names + data_strings
812
- st_json = _json.dumps(string_table)
805
+ def test_derived_measure_excluded(self, client):
806
+ self._mock_get(client, {"id": 500, "measures": [
807
+ self._measure(200, "tbsp", 14.0),
808
+ self._measure(999999, "mL", 1.0, derived=True),
809
+ ]})
813
810
 
814
- # Convert tokens: floats with decimal, ints without
815
- token_strs = []
816
- for t in data_tokens:
817
- if isinstance(t, float):
818
- token_strs.append(str(t))
819
- else:
820
- token_strs.append(str(t))
821
- tokens_str = ",".join(token_strs)
811
+ ids = [m["measure_id"] for m in client.get_food(500)["measures"]]
822
812
 
823
- return f"//OK[{tokens_str},{st_json},0,7]"
813
+ assert ids == [200]
824
814
 
815
+ def test_reauthenticates_once_on_401(self, client):
816
+ ok = MagicMock(status_code=200, json=lambda: {"id": 1, "measures": []})
817
+ denied = MagicMock(status_code=401)
818
+ client._authenticated = True
819
+ client.session.get = MagicMock(side_effect=[denied, ok])
820
+ with patch.object(client, "_reauthenticate") as reauth:
821
+ assert client.get_food(1)["measures"] == []
822
+ reauth.assert_called_once()
825
823
 
826
- class TestParseGetFood:
827
- """Unit tests for CronometerClient._parse_get_food (no network calls)."""
824
+ def test_http_error_raises(self, client):
825
+ get_mock = self._mock_get(client, {}, status=404)
826
+ get_mock.return_value.raise_for_status.side_effect = requests.HTTPError("404")
828
827
 
829
- def _parse(self, raw: str, fsid: int = 12345) -> dict:
830
- return CronometerClient._parse_get_food(raw, fsid)
828
+ with pytest.raises(requests.HTTPError):
829
+ client.get_food(1)
831
830
 
832
- def test_single_nccdb_measure(self):
833
- raw = _build_get_food_response([
834
- {"description": "1 large - 50g", "measure_id": 65541,
835
- "food_source_id": 464674, "weight_grams": 50.0},
836
- ])
837
- result = self._parse(raw)
838
- assert len(result["measures"]) == 1
839
- m = result["measures"][0]
840
- assert m["measure_id"] == 65541
841
- assert m["description"] == "1 large - 50g"
842
- assert m["weight_grams"] == 50.0
843
-
844
- def test_multiple_measures(self):
845
- raw = _build_get_food_response([
846
- {"description": "1 cup", "measure_id": 100,
847
- "food_source_id": 500, "weight_grams": 240.0},
848
- {"description": "1 tbsp", "measure_id": 101,
849
- "food_source_id": 500, "weight_grams": 15.0},
850
- ])
851
- result = self._parse(raw)
852
- assert len(result["measures"]) == 2
853
- ids = {m["measure_id"] for m in result["measures"]}
854
- assert ids == {100, 101}
855
-
856
- def test_derived_measure_excluded(self):
857
- """DerivedMeasure entries must NOT appear in the measures list."""
858
- raw = _build_get_food_response(
859
- [{"description": "1 tbsp", "measure_id": 200,
860
- "food_source_id": 500, "weight_grams": 14.0}],
861
- include_derived=True,
862
- )
863
- result = self._parse(raw)
864
- # Should only have the real Measure, not the DerivedMeasure
865
- ids = [m["measure_id"] for m in result["measures"]]
866
- assert 200 in ids
867
- assert 999999 not in ids
868
-
869
- def test_invalid_response_returns_empty(self):
870
- result = self._parse("//EX[error]", 12345)
871
- assert result["measures"] == []
872
-
873
- def test_no_measure_in_string_table(self):
874
- import json as _json
875
- st = ["com.cronometer.shared.foods.models.Food/123"]
876
- raw = f'//OK[1,0,{_json.dumps(st)},0,7]'
877
- result = self._parse(raw)
878
- assert result["measures"] == []
879
-
880
- def test_food_source_id_echoed(self):
881
- raw = _build_get_food_response([
882
- {"description": "1 oz", "measure_id": 300,
883
- "food_source_id": 55985, "weight_grams": 28.35},
884
- ])
885
- result = self._parse(raw, fsid=55985)
886
- assert result["food_source_id"] == 55985
831
+ @staticmethod
832
+ def _html_page():
833
+ """A 200 that is not JSON, e.g. a login page after a redirect."""
834
+ def not_json():
835
+ raise requests.JSONDecodeError("Expecting value", "<html>", 0)
836
+ return MagicMock(status_code=200, json=not_json, url="https://cronometer.com/login/")
837
+
838
+ def test_reauthenticates_once_on_non_json_page(self, client):
839
+ ok = MagicMock(status_code=200, json=lambda: {"id": 1, "measures": []})
840
+ client._authenticated = True
841
+ client.session.get = MagicMock(side_effect=[self._html_page(), ok])
842
+ with patch.object(client, "_reauthenticate") as reauth:
843
+ assert client.get_food(1)["measures"] == []
844
+ reauth.assert_called_once()
845
+
846
+ def test_non_json_after_relogin_raises_clear_error(self, client):
847
+ client._authenticated = True
848
+ client.session.get = MagicMock(side_effect=[self._html_page(), self._html_page()])
849
+ with patch.object(client, "_reauthenticate"):
850
+ with pytest.raises(RuntimeError, match="not JSON"):
851
+ client.get_food(1)
852
+
853
+ @pytest.mark.parametrize("payload", [
854
+ {"id": 1, "measures": None},
855
+ {"id": 1, "measures": [{"id": 5, "name": "large", "value": None}]},
856
+ {"id": 1, "measures": [{"name": "large", "value": 50.0}]},
857
+ {"id": 1, "measures": [{"id": 5, "name": "large"}]},
858
+ {"id": 1},
859
+ {"id": 1, "measures": [None]},
860
+ {"id": 1, "measures": ["large"]},
861
+ {"id": 1, "measures": [{"id": True, "name": "large", "value": 50.0}]},
862
+ {"id": 1, "measures": [{"id": 5, "name": "large", "value": False}]},
863
+ ])
864
+ def test_malformed_measures_raise_clear_error(self, client, payload):
865
+ self._mock_get(client, payload)
866
+ with pytest.raises(ValueError, match="measure"):
867
+ client.get_food(1)
868
+
869
+ def test_null_name_becomes_empty_string(self, client):
870
+ self._mock_get(client, {"id": 1, "measures": [
871
+ {"id": 5, "name": None, "value": 50.0}]})
872
+ assert client.get_food(1)["measures"][0]["description"] == ""
873
+
874
+
875
+ class TestFindFoodsReauth:
876
+ def test_reauthenticates_once_on_non_json_page(self, client):
877
+ ok = MagicMock(status_code=200, json=lambda: [])
878
+ client._authenticated = True
879
+ client.user_id = "42"
880
+ client.session.get = MagicMock(side_effect=[TestGetFood._html_page(), ok])
881
+ with patch.object(client, "_reauthenticate") as reauth:
882
+ assert client.find_foods("egg") == []
883
+ reauth.assert_called_once()
884
+
885
+ def test_logs_in_before_building_url(self, client):
886
+ """user_id is only known after login; the URL must not say user/None."""
887
+ client._authenticated = False
888
+ client.user_id = None
889
+ client.session.get = MagicMock(return_value=MagicMock(status_code=200, json=lambda: []))
890
+
891
+ def login():
892
+ client._authenticated = True
893
+ client.user_id = "42"
894
+ with patch.object(client, "authenticate", side_effect=login):
895
+ client.find_foods("egg")
896
+ assert "/user/42/" in client.session.get.call_args[0][0]
887
897
 
888
898
 
889
899
  class TestAddServing:
@@ -100,7 +100,7 @@ def test_servings_export_columns(test_day_exports):
100
100
  def test_food_search_and_details(c):
101
101
  hits = c.find_foods("egg")
102
102
  assert hits and {"food_id", "food_source_id", "name"} <= hits[0].keys()
103
- assert c.get_food(hits[0]["food_source_id"])
103
+ assert c.get_food(hits[0]["food_source_id"])["measures"]
104
104
 
105
105
 
106
106
  def test_diary_groups_parse(c):
File without changes
File without changes
File without changes