def test_sub_one_base_si_measure(self): milliliters = Volume(ml=200) fl_oz = Volume(us_oz=6.76280454) self.assertAlmostEqual( milliliters.standard, fl_oz.standard )
def weightconvert(): weight_1 = Weight(lb=125) weight_2 = Weight(kilogram=25) addedthem = weight_1 + weight_2 print("added: " + str(addedthem)) beans = Volume(us_cup=1.5) mtdew = Volume(us_oz=12) addedthem = (mtdew * 12) / beans print(addedthem)
def _get_water(self, document): water_header = document.xpath("//div[@class='water-counter']/p/a")[0] try: cups = int(water_header.tail.strip()) if self.unit_aware: return Volume(us_cup=cups) return cups except (ValueError, TypeError): return None
def _get_water(self, date: datetime.date) -> float: result = self._get_request_for_url( parse.urljoin( self.BASE_URL_SECURE, "/food/water", ) + "?date={date}".format(date=date.strftime("%Y-%m-%d"))) value = result.json()["item"]["milliliters"] if not self.unit_aware: return value return Volume(ml=value)
def _get_water(self, date): result = self._get_request_for_url( parse.urljoin( self.BASE_URL_SECURE, '/food/water', ) + "?date={date}".format(date=date.strftime('%Y-%m-%d'))) value = result.json()['item']['milliliters'] if not self.unit_aware: return value return Volume(ml=value)
def get_field_info(self, field): """ Overriding to add custom unit_choices to required fields. """ field_info = super().get_field_info(field) if field.field_name == "volume": field_info["unit_choices"] = get_choices( Volume.get_aliases(), first="cubic meter") elif field.field_name == "weight": field_info["unit_choices"] = get_choices( Weight.get_aliases(), first="gram") return field_info
def calculate_dissolve_volume(sugar_amount, sugar_type, og): """Calculate volume to disolve priming sugar :param float sugar_amount: Sugar amount in pounds Lb :param string sugar_type: Sugar type :param float og: OG in SG """ if sugar_type == "DRY_EXTRACT": ppg = 36 else: ppg = 46 print(sugar_amount, og) volume = abs(sugar_amount * ppg / (1 - og) / 1000.0) volume = volume - 0.1 * volume return Volume(us_g=volume)
def test_update_standard_field(self): """ Test successful update when updating a fields that's not volume or weight. """ # Given expected_name = "Item X" item = mommy.make("Item", name="XXXXXX", volume=Volume(cubic_meter=10)) # When serializer = ItemSerializer(item) serializer.update(item, {"name": expected_name}) # Then item.refresh_from_db() self.assertEqual(item.name, expected_name)
def test_update_unit_volume(self): """ Test successful update of unit volume. """ # Given expected_value = 1000.0 expected_standard_value = 1.0 item = mommy.make("Item", volume=Volume(cubic_meter=expected_value)) # When serializer = ItemSerializer(item) serializer.update(item, {"unit": "l"}) # Then item.refresh_from_db() self.assertEqual(item.volume.l, expected_value) self.assertEqual(item.volume.unit, self.default_volume_unit) self.assertEqual(item.volume.value, expected_standard_value) self.assertEqual(item.volume.standard, expected_standard_value) self.assertEqual(item.volume.cubic_meter, expected_standard_value)
def test_multiply_divide(self): vol = Volume(ML=100) result = vol * 2 self.assertEqual(result.ml, 200) result *= 2 self.assertEqual(result.ml, 400) with self.assertRaises(TypeError): vol * vol with self.assertRaises(TypeError): vol *= vol with self.assertRaises(TypeError): vol /= vol result /= 4 self.assertEqual(result.ml, 100) result = result / 2 self.assertEqual(result.ml, 50) result = vol / vol self.assertEqual(result, 1)
def test_fields(self): """ Test fields for serializer. """ # Given order = mommy.make("Order") purchase = mommy.make( "Purchase", price=10, item__volume=Volume(l=1), # noqa order=order, location=self.location) purchase.item.refresh_from_db() # To trigger MeasurementField updates expected_data = get_default_fields(purchase) expected_data.update({ "price": "10.000", "currency": "USD", "item": { "id": purchase.item.id, "name": purchase.item.name, "unit": "cubic_meter", "volume": 0.001, "weight": None, "brand": { "id": purchase.item.brand.id, "name": purchase.item.brand.name } }, "order": { "id": order.id, "date": order.date.isoformat(), "store": { "id": order.store.id, "name": order.store.name } }, "location": "Address, District, City, Country" }) # When serializer = PurchaseNestedSerializer(purchase) # Then self.assertEqual(loads(dumps(serializer.data)), expected_data)
def test_fields(self): """ Test fields for serializer. """ # Given item = mommy.make("Item", volume=Volume(l=1)) # noqa item.refresh_from_db() # To trigger MeasurementField updates expected_data = get_default_fields(item) expected_data.update({ "name": item.name, "unit": "cubic_meter", "volume": 0.001, "weight": None, "brand": { "id": item.brand.id, "name": item.brand.name } }) # When serializer = ItemNestedSerializer(item) # Then self.assertEqual(loads(dumps(serializer.data)), expected_data)
def test_fields_data(self): """ Test fields for serializer. """ # Given item = mommy.make( "Item", volume=Volume(l=1), # noqa weight=Weight(g=1)) item.refresh_from_db() # To trigger MeasurementField updates expected_data = get_default_fields(item) expected_data.update({ "name": item.name, "brand": item.brand.id, "unit": self.default_volume_unit, "volume": 0.001, "weight": 1.0 }) # When serializer = ItemSerializer(item) # Then self.assertEqual(loads(dumps(serializer.data)), expected_data)
def mass_to_volume_lookup(mass, ingredient): """ Given a - Weight object (kg, g, etc...), - ingredient (flour, sugar, etc...) Return the mass to volume ratio """ # Convert volume to liter # Convert mass to kilogram # ratios for 1 gram to 1 cup ratios = { 'flour': 1, } try: ratio = ratios[ingredient.lower()] except: ratio = 1 return Volume(us_cup=(mass.g * ratio))
def _set_volume_weight_fields(self, validated_data, unit, volume, weight): """ Set volume or weight using django-measurement field. Parameters: validated_data: dict Dict with validated data from serializer. unit: str Value for unit field volume: float Value for volume field weight: float Value for weight field Returns: dict, validated_data but with properly set volume/weight fields. """ if volume: validated_data["volume"] = Volume( **{unit or "cubic_meter": volume}) elif weight: validated_data["weight"] = Weight(**{unit or "g": weight}) return validated_data
def get_primary_volume(self): volume = self.expected_beer_volume.l trub_loss = volume * (float(self.trub_loss) / 100.0) dry_hopping_loss = volume * (float(self.dry_hopping_loss) / 100.0) volume = volume + trub_loss + dry_hopping_loss return Volume(l=volume)
def load_recipes(user): recipes = get_recipes_json() recipes_objects = [] for recipe in recipes: recipe_data = _clean_data(recipe["fields"]) style = models.Style.objects.filter( name__icontains=recipe_data["style"]) recipe_data["user"] = user if style.count() == 0: print( f"Did not fount a syle '{recipe_data['style']}' for '{recipe_data['name']}'" ) recipe_data["style"] = style[0] recipe_data["expected_beer_volume"] = Volume( **{ recipe_data["expected_beer_volume"].split()[-1].split("(")[0]: float(recipe_data["expected_beer_volume"].split()[0]) }) # print(recipe_data) new_recipe = models.Recipe(**recipe_data) new_recipe.save() fermentables = [] for fermentable in recipe["fermentables"]: data = _clean_data(fermentable) data["recipe"] = new_recipe data["amount"] = Weight(**{data["unit"]: data["amount"]}) data["color"] = BeerColor(ebc=data["color"]) del data["unit"] fermentable_ingredient = models.IngredientFermentable(**data) fermentable_ingredient.save() fermentables.append(fermentables) hops = [] for hop in recipe["hops"]: data = _clean_data(hop) data["recipe"] = new_recipe data["amount"] = Weight(**{data["unit"]: data["amount"]}) del data["unit"] data["time_unit"] = data["time_unit"].split("(")[0] hop_ingredient = models.IngredientHop(**data) hop_ingredient.save() hops.append(hops) yeasts = [] for yeast in recipe["yeasts"]: data = _clean_data(yeast) data["recipe"] = new_recipe data["amount"] = Weight(**{data["unit"]: data["amount"]}) del data["unit"] yeast_ingredient = models.IngredientYeast(**data) yeast_ingredient.save() yeasts.append(yeasts) extras = [] for extra in recipe["extras"]: data = _clean_data(extra) data["recipe"] = new_recipe data["amount"] = Weight(**{data["unit"]: data["amount"]}) del data["unit"] data["time_unit"] = data["time_unit"].split("(")[0] extra_ingredient = models.IngredientExtra(**data) extra_ingredient.save() extras.append(extras) mash_steps = [] for mash in recipe["mashing"]: data = _clean_data(mash) data["recipe"] = new_recipe data["temperature"] = Temperature(c=data["temp"]) del data["temp"] del data["time_unit"] mash_step = models.MashStep(**data) mash_step.save() mash_steps.append(mash_step) new_recipe.save() recipes_objects.append((recipe, new_recipe)) return recipes_objects
def my_size_transform(s): if 'ml' in s: v = Volume(milliliter=s.replace('ml', '')) elif 'L' in s: v = Volume(liter=s.replace('L', '')) return v.us_oz
def __init__(self, *args, **kwargs): super(RecipeModelForm, self).__init__(*args, **kwargs) if self.request.user.profile.general_units == "METRIC": unit_choices = (("l", "l"), ) elif self.request.user.profile.general_units == "IMPERIAL": unit_choices = (("us_g", "us_g"), ) else: raise ValueError( f"No unit choice {self.request.user.profile.general_units}") self.fields.update({ "expected_beer_volume": MeasurementField( label=_("Expected Beer Volume"), measurement=Volume, unit_choices=unit_choices, initial=Volume(l=20), ), }) self.helper = FormHelper() self.helper.form_tag = True self.helper.add_input( Submit("submit", _("Submit"), css_class="btn-primary")) self.helper.form_method = "POST" # self.helper.form_class = 'form-horizontal' self.helper.label_class = "col-md-6 create-label" self.helper.field_class = "col-md-6" self.helper.layout = Layout( Div( Fieldset( _("Recipe Information"), Field("type"), Field("name"), Field("style"), Field("is_public"), ), Fieldset( _("Batch Information"), Row( Column( Field("expected_beer_volume"), css_class="form-group col-md-6 mb-0", ), css_class="form-row", ), Row( Column( AppendedText("boil_time", "min"), css_class="form-group col-md-4 mb-0", ), Column( AppendedText("evaporation_rate", "%/h"), css_class="form-group col-md-4 mb-0", ), css_class="form-row", ), Row( Column( AppendedText("boil_loss", "%"), css_class="form-group col-md-4 mb-0", ), Column( AppendedText("trub_loss", "%"), css_class="form-group col-md-4 mb-0", ), Column( AppendedText("dry_hopping_loss", "%"), css_class="form-group col-md-4 mb-0", ), css_class="form-row", ), Row( Column( HTML( batch_info_stats.format( _("Boil Volume"), _("Pre-boil Gravity"), _("Primary Volume"), _("Secondary Volume"), )), css_class="form-group col-md-3 mb-0", ), css_class="form-row", ), ), Fieldset( _("Fermentables"), Row( Column( HTML( fermentable_info_stats.format( _("Gravity"), _("Color"), )), css_class="form-group col-md-4 mb-0", ), css_class="form-row", ), Row( layouts.RecipeFormsetLayout( "fermentables", "brewery/recipe/fermentable_formset.html"), css_class="form-row", ), ), Fieldset( _("Mash"), Row( Column( AppendedText("mash_efficiency", "%"), css_class="form-group col-md-4 mb-0", ), Column( AppendedText("liquor_to_grist_ratio", "?"), css_class="form-group col-md-4 mb-0", ), css_class="form-row", ), Row( layouts.RecipeFormsetLayout( "mash_steps", "brewery/recipe/mash_formset.html"), css_class="form-row", ), ), Fieldset( _("Hops"), Row( Column( HTML( hop_info_stats.format( _("Bitterness"), _("Bitterness Ratio"), )), css_class="form-group col-md-4 mb-0", ), css_class="form-row", ), Row( layouts.RecipeFormsetLayout( "hops", "brewery/recipe/hop_formset.html"), css_class="form-row", ), ), Fieldset( _("Yeasts"), layouts.RecipeFormsetLayout( "yeasts", "brewery/recipe/yeast_formset.html"), ), Fieldset( _("Extras"), layouts.RecipeFormsetLayout( "extras", "brewery/recipe/extra_formset.html"), ), Field("note"), HTML("<br>"), ), )
from rest_framework.test import APIClient from model_bakery import baker from model_bakery.generators import random_gen from measurement.measures import Volume, Mass, Temperature from brivo.utils.measures import BeerColor, BeerGravity from brivo.users.models import User, UserProfile, UserBrewery from brivo.brewery.models import Style from brivo.users.tests.factories import UserFactory baker.generators.add('brivo.brewery.fields.BeerColorField', lambda: BeerColor(srm=10)) baker.generators.add('brivo.brewery.fields.BeerGravityField', lambda: BeerGravity(plato=10)) baker.generators.add('brivo.brewery.fields.VolumeField', lambda: Volume(l=10)) baker.generators.add('brivo.brewery.fields.MassField', lambda: Mass(kg=1)) baker.generators.add('brivo.brewery.fields.TemperatureField', lambda: Temperature(c=10)) baker.generators.add('modelcluster.fields.ParentalKey', random_gen.gen_related) ROOT_DIR = Path(__file__).resolve(strict=True).parent @pytest.fixture(autouse=True) def media_storage(settings, tmpdir): settings.MEDIA_ROOT = tmpdir.strpath @pytest.fixture def user():
def test_truediv__distance(self): assert Volume("1 m³") / Distance("1 m") == Area("1 m²")
def test_imperial_flud_ounce(self): assert Volume("28.41306 mL") == Volume("1 imp fl oz")
def test_truediv__area(self): assert Volume("1 m³") / Area("1 m²") == Distance("1 m")
def test_truediv__super(self): assert Volume("1 m³") / 2 == Volume("0.5 m³")
def test_mul(self): assert Area("1 m²") * Distance("1 m") == Volume("1 m³")
def test_pow(self): assert Distance(m=1) ** 2 == Area("1 m²") assert Distance(m=1) ** 3 == Volume("1 m³") with pytest.raises(TypeError): Distance(m=1) ** 4
def test_litre(self): assert Volume("1 cubic metre") == Volume("1000 L") assert Volume("1 mL") == Volume("1e-6 m³")
def get_secondary_volume(self): volume = self.expected_beer_volume.l dry_hopping_loss = volume * (float(self.dry_hopping_loss) / 100.0) volume = volume + dry_hopping_loss return Volume(l=volume)
def test_mul__area(self): assert Distance(m=1) * Area(sq_m=1) == Volume("1 m³")
def test_us_fluid_ounce(self): assert Volume("29.57353 mL") == Volume("1 US fl oz")