Files
Shoppy/tests/environmentalService.test.mjs
T
Frederik Spirgi c995999823
Android Release Build / build-android (push) Successful in 14m6s
revamp app for more gainz
2026-11-18 11:55:53 +01:00

195 lines
10 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { importAgribalyse } from '../scripts/importAgribalyse.mjs';
import { mapOpenFoodFactsProduct, lookupProductByBarcode, searchProducts } from '../src/services/productApi.js';
import { enrichEnvironmentalProduct, productSpecificFootprint, ENVIRONMENTAL_RULES_VERSION } from '../src/services/environmentalService.js';
const off = (overrides = {}) => mapOpenFoodFactsProduct({
code: '12345678', product_name: 'Banana', categories_tags: ['en:fruits', 'en:bananas'],
quantity: '500 g', ...overrides
});
test('product-specific OFF footprint and Green-Score take priority over category impact', () => {
const product = off({
environmental_score_grade: 'b', environmental_score_score: 70,
categories_properties: { 'agribalyse_food_code:en': '13005' },
nutriments: { 'carbon-footprint_100g': 120 }
});
assert.equal(product.sustainability.ecoScore, 'B');
assert.equal(product.sustainability.ecoScoreScore, 70);
assert.equal(product.sustainability.footprint.status, 'product-specific');
assert.equal(product.sustainability.footprint.valueKgCo2ePerKg, 1.2);
assert.equal(product.sustainability.footprint.packageKgCo2e, 0.6);
});
test('missing product footprint falls back to verified AGRIBALYSE entry with indicators', () => {
const product = off({ categories_properties: { 'agribalyse_food_code:en': '13005' } });
const footprint = product.sustainability.footprint;
assert.equal(footprint.status, 'estimated');
assert.equal(footprint.sourceId, '13005');
assert.equal(footprint.valueKgCo2ePerKg, 0.909);
assert.equal(footprint.matchMethod, 'off-category-code');
assert.equal(footprint.datasetVersion, '3.2');
assert.equal(footprint.packageKgCo2e, 0.4545);
assert.equal(footprint.sourceUnit, 'kg CO2 eq/kg de produit');
assert.equal(footprint.indicators.landUse.unit, 'Pt/kg de produit');
assert.equal(footprint.indicators.waterScarcity.unit, 'm3 depriv./kg de produit');
assert.equal(footprint.indicators.singleScore.unit, 'mPt/kg de produit');
});
test('CO2 estimate does not create an official Green-Score', () => {
const product = off();
assert.equal(product.sustainability.footprint.status, 'estimated');
assert.equal(product.sustainability.ecoScore, undefined);
});
test('unrelated, conflicting and ambiguous categories remain unavailable', () => {
assert.equal(off({ categories_tags: ['en:unknown-food'], product_name: 'Mystery bar' }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ categories_tags: ['en:apples', 'en:bananas'] }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ product_name: 'Dried banana' }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ product_name: 'Banana smoothie', categories_tags: ['en:bananas', 'en:smoothies'] }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ product_name: 'Banana', categories_properties: { 'agribalyse_food_code:en': '20009' } }).sustainability.footprint.status, 'unavailable');
assert.equal(off({ ingredients_text: 'Banana, sugar' }).sustainability.footprint.status, 'unavailable');
});
test('similar names do not override structured categories', () => {
const banana = off();
const plantain = off({ product_name: 'Plantain banana', categories_tags: ['en:plantains'] });
const apple = off({ product_name: 'Apple', categories_tags: ['en:apples'] });
assert.equal(banana.sustainability.footprint.sourceId, '13005');
assert.equal(plantain.sustainability.footprint.status, 'unavailable');
assert.equal(apple.sustainability.footprint.sourceId, '13039');
});
test('exact name fallback is constrained by the food group and processing state', () => {
const tomato = off({ product_name: 'Tomato, raw', categories_tags: ['en:vegetables'] });
assert.equal(tomato.sustainability.footprint.sourceId, '20047_1');
assert.equal(tomato.sustainability.footprint.matchMethod, 'normalized-name-in-category');
assert.equal(off({ product_name: 'Tomato, raw', categories_tags: ['en:beverages'] }).sustainability.footprint.status, 'unavailable');
});
test('mass units and package reliability are handled without volume or drained-weight guesses', () => {
assert.equal(off({ quantity: '2 x 250 g' }).sustainability.footprint.packageQuantityGrams, 500);
assert.equal(off({ quantity: '1.5 kg' }).sustainability.footprint.packageQuantityGrams, 1500);
assert.equal(off({ quantity: '500 ml' }).sustainability.footprint.packageKgCo2e, undefined);
assert.equal(off({ quantity: '500 g, 350 g drained' }).sustainability.footprint.packageKgCo2e, undefined);
assert.equal(off({ quantity: 'unknown' }).sustainability.footprint.packageKgCo2e, undefined);
assert.equal(productSpecificFootprint({ 'carbon-footprint_100g': 0 }, '100 g').valueKgCo2ePerKg, 0);
assert.equal(productSpecificFootprint({ 'carbon-footprint_100g': 50 }, '500 ml').status, 'unavailable');
});
test('malformed and legacy OFF fields do not manufacture environmental values', () => {
assert.equal(productSpecificFootprint({ 'carbon-footprint_100g': 'bad' }, '100 g').status, 'unavailable');
const legacy = off({ ecoscore_grade: 'c', ecoscore_data: { agribalyse: { co2_total: 99 } }, categories_tags: [] });
assert.equal(legacy.sustainability.ecoScore, 'C');
assert.equal(legacy.sustainability.footprint.status, 'unavailable');
assert.equal(mapOpenFoodFactsProduct({ code: '9', categories_tags: null, ingredients_text: {}, ingredients_analysis_tags: null }).sustainability.footprint.status, 'unavailable');
});
test('cached product matches are reused and invalidated by rule/data version', () => {
const first = off();
assert.match(first.sustainability.environmentalCacheVersion, new RegExp(ENVIRONMENTAL_RULES_VERSION + '$'));
assert.strictEqual(enrichEnvironmentalProduct(first), first);
const stale = { ...first, sustainability: { ...first.sustainability, environmentalCacheVersion: 'old', footprint: { status: 'estimated', valueKgCo2ePerKg: 999 } } };
assert.equal(enrichEnvironmentalProduct(stale).sustainability.footprint.valueKgCo2ePerKg, 0.909);
const local = { id: 'sample-1', dataSource: 'local', sustainability: { carbonFootprintKgCo2ePerKg: 2 } };
assert.strictEqual(enrichEnvironmentalProduct(local), local);
});
test('offline cached scans work and OFF/network failures fail gracefully', async () => {
const cached = off();
const result = await lookupProductByBarcode(cached.barcode, { [cached.barcode]: cached }, true);
assert.equal(result.product.sustainability.footprint.status, 'estimated');
const originalFetch = globalThis.fetch;
try {
globalThis.fetch = async () => { throw new Error('offline'); };
assert.equal((await lookupProductByBarcode('987654321')).status, 'error');
assert.deepEqual(await searchProducts('banana', {}, false), []);
globalThis.fetch = async () => ({ ok: true, json: async () => null });
assert.equal((await lookupProductByBarcode('987654321')).status, 'notFound');
} finally {
globalThis.fetch = originalFetch;
}
});
test('stale product data refreshes online and remains usable offline', async () => {
const stale = {
...off({ product_name: 'Old name', allergens_tags: ['en:soybeans'] }),
fetchedAt: '2020-01-01T00:00:00.000Z', price: 3.5,
sustainability: { originCountry: 'Schweiz' }
};
const originalFetch = globalThis.fetch;
let requests = 0;
try {
globalThis.fetch = async () => {
requests += 1;
return { ok: true, json: async () => ({ status: 1, product: {
code: stale.barcode, product_name: 'New name', allergens_tags: ['en:milk'],
origins: 'Frankreich', countries_tags: ['en:switzerland']
} }) };
};
const refreshed = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: stale });
assert.equal(requests, 1);
assert.equal(refreshed.product.name, 'New name');
assert.equal(refreshed.product.price, undefined);
assert.equal(refreshed.product.sustainability.originCountry, 'Frankreich');
assert.equal(refreshed.product.sustainability.originSource, 'ingredient-origin');
assert.ok(Date.parse(refreshed.product.fetchedAt) > Date.parse(stale.fetchedAt));
const fresh = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: refreshed.product });
assert.equal(requests, 1);
assert.equal(fresh.product.name, 'New name');
const offline = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: stale }, true);
assert.equal(requests, 1);
assert.equal(offline.product.name, 'Old name');
assert.equal(offline.product.cacheStale, true);
globalThis.fetch = async () => { throw new Error('offline'); };
const fallback = await lookupProductByBarcode(stale.barcode, { [stale.barcode]: stale });
assert.equal(fallback.product.cacheStale, true);
assert.equal(fallback.product.name, 'Old name');
} finally {
globalThis.fetch = originalFetch;
}
});
test('a recent cache entry from the old nutrition schema reloads carbohydrates', async () => {
const cached = off({ code: '3017620422003', product_name: 'Test', nutriments: { sugars_100g: 56.3 } });
delete cached.nutritionSchemaVersion;
cached.manualOverrides = { nutrition: { sugarPer100g: 40 } };
const originalFetch = globalThis.fetch;
let requests = 0;
try {
globalThis.fetch = async () => {
requests += 1;
return { ok: true, json: async () => ({ status: 1, product: {
code: cached.barcode, product_name: 'Test', nutriments: {
sugars_100g: 56.3, carbohydrates_100g: 57.5
}
} }) };
};
const refreshed = await lookupProductByBarcode(cached.barcode, { [cached.barcode]: cached });
assert.equal(requests, 1);
assert.equal(refreshed.product.nutrition.carbohydratesPer100g, 57.5);
assert.equal(refreshed.product.nutrition.sugarPer100g, 40);
assert.equal(refreshed.product.nutritionSchemaVersion, 2);
const offline = await lookupProductByBarcode(cached.barcode, { [cached.barcode]: cached }, true);
assert.equal(requests, 1);
assert.equal(offline.product.cacheStale, true);
} finally {
globalThis.fetch = originalFetch;
}
});
test('ADEME import failure cannot replace the last good local snapshot', async () => {
let wrote = false;
await assert.rejects(importAgribalyse({
fetchJson: async () => { throw new Error('ADEME offline'); },
write: async () => { wrote = true; }
}), /ADEME offline/);
assert.equal(wrote, false);
});