Exemple #1
0
    def test_convert_weight_to_grams(self):
        """Convert units of weight to grams.
        """
        pound = Unit.objects.get(name='pound')
        grams_per_pound = convert_unit('pound', 'gram')
        self.failUnlessEqual(to_grams(pound), grams_per_pound)

        kilo = Unit.objects.get(name='kilogram')
        grams_per_kilo = convert_unit('kilogram', 'gram')
        self.failUnlessEqual(to_grams(kilo), grams_per_kilo)
Exemple #2
0
    def for_amount(self, to_quantity, to_unit):
        """ Return a `FoodNutritionInfo` for the given quantity and unit.
            """
        # If units are the same, scale by quantity alone
        if self.unit == to_unit:
            factor = float(to_quantity) / self.quantity
        else:
            # Scaling factor for a 1-gram serving size
            gram_serving = 1.0 / (helpers.to_grams(self.unit, self.food)
                                  * self.quantity)
            # Target quantity in grams
            target_grams = helpers.to_grams(to_unit, self.food) * to_quantity
            # Overall scaling factor to apply to all nutritional info
            factor = gram_serving * target_grams

        return FoodNutritionInfo(food=self.food, quantity=to_quantity,
                                 unit=to_unit, calories=factor
                                 * self.calories, fat_calories=factor
                                 * self.fat_calories, fat=factor * self.fat,
                                 carb=factor * self.carb, sodium=factor
                                 * self.sodium, protein=factor * self.protein,
                                 cholesterol=factor * self.cholesterol)
Exemple #3
0
    def test_convert_volume_to_grams(self):
        """Convert units of volume to grams.
        """
        # Two foods with very different densities
        honey = Food.objects.get(name='honey')
        paprika = Food.objects.get(name='paprika')

        # Two units of volume
        ml = Unit.objects.get(name='milliliter')
        cup = Unit.objects.get(name='cup')
        ml_per_cup = Equivalence.objects.get(unit=cup, to_unit=ml).to_quantity

        # Convert units of volume into grams
        # Without food, assume 1.0 g/ml
        self.failUnlessEqual(to_grams(ml), 1.0)
        self.failUnlessEqual(to_grams(cup), 1.0 * ml_per_cup)
        # With food, use its density
        self.failUnlessEqual(to_grams(ml, honey), honey.grams_per_ml)
        self.failUnlessEqual(to_grams(ml, paprika), paprika.grams_per_ml)
        self.failUnlessEqual(to_grams(cup, honey), honey.grams_per_ml * ml_per_cup)
        self.failUnlessEqual(to_grams(cup, paprika), paprika.grams_per_ml * ml_per_cup)