This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
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('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);
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { calculateNutriScore } from '../src/services/nutriScoreService.js';
|
||||
import { calculateProductRating } from '../src/services/ratingService.js';
|
||||
import { lookupProductByBarcode } from '../src/services/productApi.js';
|
||||
|
||||
const preferences = { avoidAllergens: [], preferredDiet: 'none' };
|
||||
|
||||
function product(nutrition, categoryTags = []) {
|
||||
return { id: 'test', name: 'Testprodukt', categoryTags, nutrition };
|
||||
}
|
||||
|
||||
test('calculates a good food grade from per-100g nutrients', () => {
|
||||
const item = product({
|
||||
energyKjPer100g: 500,
|
||||
saturatedFatPer100g: 0,
|
||||
sugarPer100g: 0,
|
||||
saltPer100g: 0,
|
||||
proteinPer100g: 10,
|
||||
fiberPer100g: 10,
|
||||
fruitVegetableLegumePercent: 0
|
||||
});
|
||||
assert.equal(calculateNutriScore(item)?.grade, 'A');
|
||||
assert.match(calculateProductRating(item, preferences).categoryScores.nutrition.message, /Berechneter Nutri-Score A/);
|
||||
});
|
||||
|
||||
test('high sugar, salt and saturated fat produce E even when positive data is absent', () => {
|
||||
const item = product({
|
||||
energyKjPer100g: 2000,
|
||||
saturatedFatPer100g: 10,
|
||||
sugarPer100g: 55,
|
||||
saltPer100g: 5
|
||||
});
|
||||
assert.equal(calculateNutriScore(item)?.grade, 'E');
|
||||
});
|
||||
|
||||
test('uses beverage thresholds and sweetener penalty', () => {
|
||||
const nutrition = {
|
||||
energyKjPer100g: 0,
|
||||
saturatedFatPer100g: 0,
|
||||
sugarPer100g: 0,
|
||||
saltPer100g: 0,
|
||||
proteinPer100g: 0,
|
||||
fiberPer100g: 0,
|
||||
fruitVegetableLegumePercent: 0,
|
||||
hasNonNutritiveSweeteners: false
|
||||
};
|
||||
assert.equal(calculateNutriScore(product(nutrition), true, false)?.grade, 'B');
|
||||
assert.equal(calculateNutriScore(product(nutrition), true, true)?.grade, 'A');
|
||||
assert.equal(calculateNutriScore(product({ ...nutrition, hasNonNutritiveSweeteners: true }), true, false)?.grade, 'C');
|
||||
});
|
||||
|
||||
test('does not apply cheese rules to a cheese sandwich', () => {
|
||||
const nutrition = {
|
||||
energyKjPer100g: 2000,
|
||||
saturatedFatPer100g: 5,
|
||||
sugarPer100g: 10,
|
||||
saltPer100g: 0.5,
|
||||
proteinPer100g: 20,
|
||||
fiberPer100g: 0,
|
||||
fruitVegetableLegumePercent: 0
|
||||
};
|
||||
assert.equal(calculateNutriScore(product(nutrition, ['en:cheese-sandwiches']))?.grade, 'D');
|
||||
assert.equal(calculateNutriScore(product(nutrition, ['en:cheeses']))?.grade, 'C');
|
||||
});
|
||||
|
||||
test('fat products use energy from saturated fat and do not need a total energy field', () => {
|
||||
const item = product({
|
||||
saturatedFatPer100g: 5, fatPer100g: 80, sugarPer100g: 0, saltPer100g: 0,
|
||||
proteinPer100g: 0, fiberPer100g: 0, fruitVegetableLegumePercent: 0
|
||||
}, ['en:vegetable-oils']);
|
||||
assert.equal(calculateNutriScore(item)?.grade, 'B');
|
||||
});
|
||||
|
||||
test('does not calculate a grade for excluded products', () => {
|
||||
const item = product({
|
||||
energyKjPer100g: 100, saturatedFatPer100g: 0, sugarPer100g: 0,
|
||||
saltPer100g: 0, proteinPer100g: 0, fiberPer100g: 0,
|
||||
fruitVegetableLegumePercent: 0
|
||||
}, ['en:alcoholic-beverages']);
|
||||
assert.equal(calculateNutriScore(item, true), null);
|
||||
});
|
||||
|
||||
test('missing or ambiguous nutrient values do not create a grade or skew overall rating', () => {
|
||||
const item = product({ sugarPer100g: 1 });
|
||||
assert.equal(calculateNutriScore(item), null);
|
||||
assert.equal(calculateProductRating(item, preferences).categoryScores.nutrition.hasKnownFacts, false);
|
||||
|
||||
const ambiguous = product({ energyKjPer100g: 500, saturatedFatPer100g: 0, sugarPer100g: 0, saltPer100g: 0 });
|
||||
assert.equal(calculateNutriScore(ambiguous), null);
|
||||
});
|
||||
|
||||
test('keeps a supplied Nutri-Score authoritative', () => {
|
||||
const item = product({ nutriScore: 'D', sugarPer100g: 0 });
|
||||
const nutritionRating = calculateProductRating(item, preferences).categoryScores.nutrition;
|
||||
assert.match(nutritionRating.message, /Nutri-Score D/);
|
||||
assert.doesNotMatch(nutritionRating.message, /Berechneter/);
|
||||
});
|
||||
|
||||
test('maps the Open Food Facts fields required by the fallback', async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ status: 1, product: {
|
||||
code: '12345',
|
||||
categories_tags: ['en:beverages'],
|
||||
additives_tags: ['en:e955'],
|
||||
nutrition_grades: 'b',
|
||||
environmental_score_grade: 'a',
|
||||
nutriments: {
|
||||
energy_100g: 100,
|
||||
sugars_100g: 2,
|
||||
'saturated-fat_100g': 0,
|
||||
salt_100g: 0,
|
||||
proteins_100g: 0,
|
||||
fiber_100g: 0,
|
||||
'fruits-vegetables-legumes-estimate-from-ingredients_100g': 0
|
||||
}
|
||||
} })
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await lookupProductByBarcode('12345');
|
||||
assert.equal(result.product.nutrition.energyKjPer100g, 100);
|
||||
assert.equal(result.product.nutrition.fiberPer100g, 0);
|
||||
assert.equal(result.product.nutrition.hasNonNutritiveSweeteners, true);
|
||||
assert.equal(result.product.nutrition.nutriScore, 'B');
|
||||
assert.equal(result.product.sustainability.ecoScore, 'A');
|
||||
assert.equal(calculateNutriScore(result.product, true)?.grade, 'D');
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { calculateProductRating } from '../src/services/ratingService.js';
|
||||
import { findAlternatives } from '../src/services/alternativesService.js';
|
||||
|
||||
const preferences = { avoidAllergens: [], preferredDiet: 'none' };
|
||||
const rate = (product, customPreferences = {}) => calculateProductRating(
|
||||
{ id: 'test', ...product }, { ...preferences, ...customPreferences }
|
||||
);
|
||||
|
||||
test('shows unknown when no category has reliable facts', () => {
|
||||
const rating = rate({});
|
||||
assert.equal(rating.overallScore, null);
|
||||
assert.equal(rating.overallStatus, 'unknown');
|
||||
});
|
||||
|
||||
test('missing budget and allergen data do not contribute neutral placeholder scores', () => {
|
||||
const rating = rate({ nutrition: { nutriScore: 'A' } });
|
||||
assert.equal(rating.categoryScores.budget.hasKnownFacts, false);
|
||||
assert.equal(rating.categoryScores.allergies.hasKnownFacts, false);
|
||||
assert.equal(rating.overallScore, 77);
|
||||
assert.equal(rating.limitedByMissingData, true);
|
||||
});
|
||||
|
||||
test('profile priorities actually change the category weighting', () => {
|
||||
const item = { nutrition: { nutriScore: 'A' }, sustainability: { ecoScore: 'E' } };
|
||||
const nutritionFirst = rate(item, { nutritionPriority: 'high', sustainabilityPriority: 'low' });
|
||||
const sustainabilityFirst = rate(item, { nutritionPriority: 'low', sustainabilityPriority: 'high' });
|
||||
assert.ok(nutritionFirst.overallScore > sustainabilityFirst.overallScore);
|
||||
});
|
||||
|
||||
test('ingredient text without animal terms is not treated as vegan proof', () => {
|
||||
const rating = rate({ ingredients: ['Weizenmehl'] }, { preferredDiet: 'vegan' });
|
||||
assert.equal(rating.categoryScores.ingredients.hasKnownFacts, false);
|
||||
assert.equal(rating.overallStatus, 'unknown');
|
||||
});
|
||||
|
||||
test('a confirmed avoided allergen still blocks the recommendation', () => {
|
||||
const rating = rate({
|
||||
allergens: ['Milch'], dataCompleteness: { allergens: true }, nutrition: { nutriScore: 'A' }
|
||||
}, { avoidAllergens: ['Milch'] });
|
||||
assert.equal(rating.overallScore, 0);
|
||||
assert.equal(rating.overallStatus, 'critical');
|
||||
assert.equal(rating.limitedByMissingData, false);
|
||||
});
|
||||
|
||||
test('Nutri-Score nutrients are not penalized twice', () => {
|
||||
const plain = rate({ nutrition: { nutriScore: 'C' } });
|
||||
const flagged = rate({ nutrition: { nutriScore: 'C', nutrientLevels: { sugars: 'high' } } });
|
||||
assert.equal(plain.categoryScores.nutrition.score, flagged.categoryScores.nutrition.score);
|
||||
});
|
||||
|
||||
test('missing values for personal goals do not invent a penalty', () => {
|
||||
const baseline = rate({ nutrition: { nutriScore: 'A' } });
|
||||
const lowSugar = rate({ nutrition: { nutriScore: 'A' } }, { preferredDiet: 'lowSugar' });
|
||||
const highProtein = rate({ nutrition: { nutriScore: 'A' } }, { preferredDiet: 'highProtein' });
|
||||
assert.equal(lowSugar.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score);
|
||||
assert.equal(highProtein.categoryScores.nutrition.score, baseline.categoryScores.nutrition.score);
|
||||
});
|
||||
|
||||
test('a critical additive in ingredient text counts without additive tags', () => {
|
||||
const rating = rate({ ingredients: ['Farbstoff E171'] });
|
||||
assert.equal(rating.categoryScores.ingredients.hasKnownFacts, true);
|
||||
assert.ok(rating.categoryScores.ingredients.score <= 24);
|
||||
});
|
||||
|
||||
test('flavoured water with sugar is not treated as plain water', () => {
|
||||
const rating = rate({
|
||||
name: 'Flavoured water',
|
||||
categoryTags: ['en:waters', 'en:flavored-waters'],
|
||||
nutrition: {
|
||||
energyKjPer100g: 80,
|
||||
sugarPer100g: 5,
|
||||
saturatedFatPer100g: 0,
|
||||
saltPer100g: 0,
|
||||
proteinPer100g: 0,
|
||||
fiberPer100g: 0,
|
||||
fruitVegetableLegumePercent: 0,
|
||||
hasNonNutritiveSweeteners: false
|
||||
}
|
||||
});
|
||||
assert.notEqual(rating.categoryScores.nutrition.score, 98);
|
||||
});
|
||||
|
||||
test('country names containing eu are not mistaken for the EU', () => {
|
||||
const peru = rate({ sustainability: { originCountry: 'Peru' } });
|
||||
const swiss = rate({ sustainability: { originCountry: 'Schweiz' } });
|
||||
assert.equal(peru.categoryScores.sustainability.score, 35);
|
||||
assert.equal(swiss.categoryScores.sustainability.score, 92);
|
||||
});
|
||||
|
||||
test('Eco-Score is not counted again through its environmental indicators', () => {
|
||||
const rating = rate({ sustainability: {
|
||||
ecoScore: 'E', carbonFootprintKgCo2ePerKg: 0.1,
|
||||
originCountry: 'Schweiz', packaging: 'Glas'
|
||||
} });
|
||||
assert.equal(rating.categoryScores.sustainability.score, 15);
|
||||
});
|
||||
|
||||
test('alternatives exclude products whose allergens need review', async () => {
|
||||
const source = {
|
||||
id: 'source', barcode: '1', name: 'Original', category: 'Snacks', categoryTags: ['en:snacks'],
|
||||
allergens: ['Milch'], dataCompleteness: { allergens: true }
|
||||
};
|
||||
const unknown = {
|
||||
id: 'unknown', barcode: '2', name: 'Unklar', category: 'Snacks', categoryTags: ['en:snacks'],
|
||||
allergens: [], dataCompleteness: { allergens: false }, nutrition: { nutriScore: 'A' }
|
||||
};
|
||||
const verified = {
|
||||
id: 'verified', barcode: '3', name: 'Bestätigt', category: 'Snacks', categoryTags: ['en:snacks'],
|
||||
allergens: ['Soja'], dataCompleteness: { allergens: true }, nutrition: { nutriScore: 'A' }
|
||||
};
|
||||
const alternatives = await findAlternatives(source, {
|
||||
...preferences, avoidAllergens: ['Milch'], offlineModeEnabled: true
|
||||
}, { unknown, verified });
|
||||
assert.deepEqual(alternatives.map((item) => item.product.id), ['verified']);
|
||||
});
|
||||
Reference in New Issue
Block a user