def _populate_product(self, product): logger.info(product.to_dict()) vendor, _ = Vendor.objects.get_or_create(name=product.vendor, ) try: product_type, _ = ProductType.objects.get_or_create( name=product.product_type, slug=slugify(product.product_type)) except IntegrityError as ie: logger.exception("Yeah some duplicate slug. generate a new one") output_string = 'NOCODE_' + ''.join( random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) product_type, _ = ProductType.objects.get_or_create( name=product.product_type, slug=output_string) variants = [] product_by_handle = Product.objects.filter(slug=product.handle) product_by_id = Product.objects.filter(metadata__shopify_id=product.id) if product_by_handle.exists(): product_obj = product_by_handle if product_by_id.exists(): product_obj = product_by_id if not product_by_handle.exists() or product_by_id.exists(): try: product_obj, _ = Product.objects.get_or_create( vendor=vendor, product_type=product_type, title=product.title, slug=product.handle, description=product.body_html, max_price=0, min_price=0, metadata={ "shopify_id": product.id, "shopify_tags": product.tags, }) except IntegrityError as ie: logger.info("Issue with sync") ErrorSyncLog.objects.create( metadata={ "type": "product", "errors": str(ie), "data": product.to_dict() }) prices = [] for variant in product.variants: logger.info(variant.to_dict()) variant_exists_by_id = ProductVariant.objects.filter( metadata__shopify_id=variant.id).exists() output_string = 'NOCODE_' + ''.join( random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) if not variant_exists_by_id: prices.append(variant.price) try: variant_obj = ProductVariant.objects.create( sku=variant.sku if variant.sku else variant.id, barcode=variant.barcode if variant.barcode else output_string, price=variant.price, cost_price=variant.price, product=product_obj, weight=Weight(lb=variant.weight), metadata={ "shopify_id": variant.id, "shopify_inventory_item_id": variant.inventory_item_id, }) variants.append(variant_obj) max_price = max(*prices) min_price = min(*prices) try: product_obj.max_price = max_price product_obj.min_price = min_price product_obj.save() except ValidationError as e: logger.exception("The value isn't valid. moving on %s", e) stock = Stock.objects.create( warehouse=Warehouse.objects.first(), product_variant=variant_obj, quantity=0, ) if variant.inventory_quantity > 0: logger.info("Inventory is Positive") stock.increase_stock( quantity=variant.inventory_quantity, commit=True) else: logger.info("Negative Inventory") except IntegrityError as ie: logger.info("Issue with sync") ErrorSyncLog.objects.create( metadata={ "type": "variant", "errors": str(ie), "data": variant.to_dict() })
def convert_lbs_to_kg(initial_number): return round(Weight(lb=initial_number).kg, 5)
def get_total_weight(self): # Cannot use `sum` as it parses an empty Weight to an int weights = Weight(kg=0) for line in self: weights += line.variant.get_weight() * line.quantity return weights
def test_get_products_data(product, product_with_image, collection, image, channel_USD): # given product.description = { "blocks": [{ "data": { "text": "This is an example description." }, "type": "paragraph" }] } product.weight = Weight(kg=5) product.save(update_fields=["description", "weight"]) collection.products.add(product) variant = product.variants.first() VariantMedia.objects.create(variant=variant, media=product.media.first()) products = Product.objects.all() export_fields = set( value for mapping in ProductExportFields.HEADERS_TO_FIELDS_MAPPING.values() for value in mapping.values()) warehouse_ids = [ str(warehouse.pk) for warehouse in Warehouse.objects.all() ] attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()] channel_ids = [str(channel.pk) for channel in Channel.objects.all()] variants = [] for variant in product.variants.all(): for attr in variant.attributes.all(): attribute_ids.append(str(attr.assignment.attribute.pk)) variant.weight = Weight(kg=3) variants.append(variant) ProductVariant.objects.bulk_update(variants, ["weight"]) variants = [] for variant in product_with_image.variants.all(): variant.weight = None variants.append(variant) ProductVariant.objects.bulk_update(variants, ["weight"]) # when result_data = get_products_data(products, export_fields, attribute_ids, warehouse_ids, channel_ids) # then expected_data = [] for product in products.order_by("pk"): id = graphene.Node.to_global_id("Product", product.pk) product_data = { "id": id, "name": product.name, "description_as_str": json.dumps(product.description), "category__slug": product.category.slug, "product_type__name": product.product_type.name, "charge_taxes": product.charge_taxes, "collections__slug": ("" if not product.collections.all() else product.collections.first().slug), "product_weight": ("{} g".format(int(product.weight.value)) if product.weight else ""), "media__image": ("" if not product.media.all() else "http://mirumee.com{}".format( product.media.first().image.url)), } product_data = add_product_attribute_data_to_expected_data( product_data, product, attribute_ids) product_data = add_channel_to_expected_product_data( product_data, product, channel_ids) for variant in product.variants.all(): data = { "variants__sku": variant.sku, "variants__media__image": ("" if not variant.media.all() else "http://mirumee.com{}".format( variant.media.first().image.url)), "variant_weight": ("{} g".foramt(int(variant.weight.value)) if variant.weight else ""), } data.update(product_data) data = add_stocks_to_expected_data(data, variant, warehouse_ids) data = add_variant_attribute_data_to_expected_data( data, variant, attribute_ids) data = add_channel_to_expected_variant_data( data, variant, channel_ids) expected_data.append(data) assert result_data == expected_data
# then assert result == expected_result def test_get_default_weight_unit(site_settings): # when result = get_default_weight_unit() # then assert result == site_settings.default_weight_unit @pytest.mark.parametrize( "default_weight_unit, expected_value", [ (WeightUnits.KILOGRAM, Weight(kg=1)), (WeightUnits.GRAM, Weight(g=1000)), (WeightUnits.POUND, Weight(lb=2.205)), (WeightUnits.OUNCE, Weight(oz=35.274)), ], ) def test_convert_weight_to_default_weight_unit(default_weight_unit, expected_value, site_settings): # given site_settings.default_weight_unit = default_weight_unit site_settings.save(update_fields=["default_weight_unit"]) # when result = convert_weight_to_default_weight_unit(Weight(kg=1)) # then
def test_applicable_shipping_methods_price_rate_use_proper_channel( shipping_zone, channel_USD, other_channel_USD ): # given # Price method with different min and max in channels to total to low to apply price_method_1 = shipping_zone.shipping_methods.create( type=ShippingMethodType.PRICE_BASED, ) # Price method with different min and max in channels total correct to apply price_method_2 = shipping_zone.shipping_methods.create( type=ShippingMethodType.PRICE_BASED, ) # Price method with different min and max in channels total to hight to apply price_method_3 = shipping_zone.shipping_methods.create( type=ShippingMethodType.PRICE_BASED, ) # Price method not assigned to channel price_method_4 = shipping_zone.shipping_methods.create( type=ShippingMethodType.PRICE_BASED, ) ShippingMethodChannelListing.objects.bulk_create( [ # price_method_1 ShippingMethodChannelListing( minimum_order_price=Money("10.0", "USD"), maximum_order_price=Money("100.0", "USD"), shipping_method=price_method_1, channel=channel_USD, ), ShippingMethodChannelListing( minimum_order_price=Money("1.0", "USD"), maximum_order_price=Money("100.0", "USD"), shipping_method=price_method_1, channel=other_channel_USD, ), # price_method_2 ShippingMethodChannelListing( minimum_order_price=Money("4.0", "USD"), maximum_order_price=Money("10.0", "USD"), shipping_method=price_method_2, channel=channel_USD, ), ShippingMethodChannelListing( minimum_order_price=Money("1.0", "USD"), maximum_order_price=Money("100.0", "USD"), shipping_method=price_method_2, channel=other_channel_USD, ), # price_method_3 ShippingMethodChannelListing( minimum_order_price=Money("1.0", "USD"), maximum_order_price=Money("4.0", "USD"), shipping_method=price_method_3, channel=channel_USD, ), ShippingMethodChannelListing( minimum_order_price=Money("1.0", "USD"), maximum_order_price=Money("100.0", "USD"), shipping_method=price_method_3, channel=other_channel_USD, ), # price_method_4 ShippingMethodChannelListing( minimum_order_price=Money("1.0", "USD"), maximum_order_price=Money("100.0", "USD"), shipping_method=price_method_4, channel=other_channel_USD, ), ] ) # when result = ShippingMethod.objects.applicable_shipping_methods( price=Money("5.0", "USD"), weight=Weight(kg=5), country_code="PL", channel_id=channel_USD.id, ) # then assert price_method_1 not in result assert price_method_3 not in result assert price_method_4 not in result assert price_method_2 in result
from measurement.measures import Weight # lb to kg to lb lbs = Weight(lb=173) kgs = Weight(kg=lbs.kg) print(lbs.lb == kgs.lb) # kg to lb to kg kgs = Weight(kg=40.5) lbs = Weight(lb=kgs.lb) print(lbs.kg == kgs.kg)
def convert_weight(weight, unit): # Weight amount from the Weight instance can be retrived in serveral units # via its properties. eg. Weight(lb=10).kg converted_weight = getattr(weight, unit) return Weight(**{unit: converted_weight})
def convert_weight(weight, unit): converted_weight = getattr(weight, unit) return Weight(**{unit: converted_weight})
# for more sophisticated setups, if you need to change connection settings (e.g. when using django-environ): # os.environ["DATABASE_URL"] = "postgres://*****:*****@localhost:54324/mydb" # Connect to Django ORM django.setup() from calorietracker.models import Log from django.contrib.auth import get_user_model from measurement.measures import Distance, Weight data = pd.read_csv("sampledata.csv") username = "******" user = get_user_model()(username=username) user.save() df = pd.DataFrame(data, columns=["Date", "Weight", "CO", "CI", "Steps"]).dropna() df["Date"] = df["Date"].apply( lambda x: datetime.datetime.strptime(x, "%d-%b").replace(year=2020)) df["Date"] = df["Date"].apply(lambda x: x.strftime("%Y-%m-%d")) for index, row in df.iterrows(): Log.objects.create( user=user, date=row["Date"], weight=Weight(lb=row["Weight"]), calories_in=row["CI"], calories_out=row["CO"], )
def zero_weight(): return Weight(kg=0)
from measurement.measures import Weight weight_1 = Weight(lb=125) weight_2 = Weight(kg=25) addedthem = weight_1 + weight_2 print(addedthem)
def OnTypeWeight(self, event): valuelb = self.weightlb.GetValue() valueoz = self.weightoz.GetValue() self.valuekg = float((Weight(lb=valuelb) + Weight(oz=valueoz)).kg)
def sync(self): user = ds_util.client.get(self.service.key.parent) if not user['preferences']['daily_weight_notif']: logging.debug( 'WeightTrendWorker: daily_weight_notif: not enabled: %s, %s', user.key, self.event.key, ) return to_imperial = user['preferences']['units'] == Preferences.Units.IMPERIAL # Calculate the trend. series_entity = Series.get(self.service.key) weight_trend = self._weight_trend(series_entity) time_frame = self._get_best_time_frame(weight_trend) if time_frame is None: logging.debug( 'WeightTrendWorker: daily_weight_notif: no timeframe: %s: %s', user.key, self.event.key, ) return if 'latest' not in weight_trend: logging.debug( 'WeightTrendWorker: daily_weight_notif: no latest: %s: %s', user.key, self.event.key, ) return latest_weight = weight_trend['latest']['weight'] if to_imperial: latest_weight = Weight(kg=latest_weight).lb time_frame_weight = weight_trend[time_frame]['weight'] if to_imperial: time_frame_weight = Weight(kg=time_frame_weight).lb time_frame_date = weight_trend[time_frame]['date'] delta = round(latest_weight - time_frame_weight, 1) unit = 'kg' if to_imperial: unit = 'lbs' if delta > 0: title = 'Up %.1f %s from %s' % (abs(delta), unit, time_frame) elif delta == 0: title = 'Weight unchanged since %s' % (time_frame,) else: title = 'Down %.1f %s from %s' % (abs(delta), unit, time_frame) body = 'You were %.1f %s on %s' % ( time_frame_weight, unit, format_date(time_frame_date.date(), format='medium'), ) # Find the best clients to send the message to. clients = fcm_util.best_clients(user.key) # Send the messages def notif_fn(client=None): return messaging.Message( notification=messaging.Notification(title=title, body=body), data={'refresh': 'weight'}, android=messaging.AndroidConfig( priority='high', # Wake up the device to notify. ttl=82800, # 23 hours # notification=messaging.AndroidNotification(), ), token=client['token'], ) fcm_util.send(self.event.key, clients, notif_fn)
def smooth_zero_weight_logs(user, method="lerp"): """ Resolves/updates log entries where user=user and weight=0 method is a string 'previous_avg' Replaces these weights with the average of the last 10 entries excluding other weight=0 entries 'lerp' Replace these weights with the linearlly interpolated weight using the previous nonzero weight, date and the next nonzero weight, date NOTE: lerp may allow weight=0 entries to remain in cases where there is no bounding nonzero weights available """ if method == "previous_avg": all_weights = list( Log.objects.filter(user=user).values_list( "date", "weight").order_by("date")) # list of tuples (date, weight) for i in range(len(all_weights)): entry = all_weights[i] # (date, weight) if entry[1] == Mass(g=0.0): # get last 10 weights previous = all_weights[i - 11:i - 1] # print("previous 10 weights", previous) # remove entries where weight is 0 previous = [ value[1] for value in previous if value[1] != Mass(g=0.0) ] # print("previous 10 weights without 0s", previous) # calculate average. if there is no elements in previous, set average to 0 if len((previous)): average = sum([value.lb for value in previous]) / len(previous) else: average = 0 # update this entry with average Log.objects.filter(user=user).filter(date=entry[0]).update( weight=Weight(lb=average)) print( "Updated", entry[0].strftime("%m/%d/%Y"), "with weight", Weight(lb=average), ) if method == "lerp": # first get all weight, dates as list of tuplesall_weights = list( all_logs = (Log.objects.filter(user=user).values_list( "date", "weight").order_by("date")) # list of tuples (date, weight) dates, weights = [e[0] for e in all_logs], [e[1] for e in all_logs] nonzeroweight_indices = [ i for i, e in enumerate(weights) if e != Weight(g=0) ] for i in range(len(dates)): if weights[i] == Weight(g=0): print("index", i, "has weight 0") # find previous date and weight that is non zero previous_found = next_found = False prev_search_index = next_search_index = i while prev_search_index >= 0 and previous_found == False: if prev_search_index in nonzeroweight_indices: w1 = weights[prev_search_index] y1 = dates[prev_search_index] previous_found = True else: prev_search_index -= 1 # find next date and weight that is non zero while next_search_index < len(weights) and next_found == False: if next_search_index in nonzeroweight_indices: w2 = weights[next_search_index] y2 = dates[next_search_index] next_found = True else: next_search_index += 1 if not (next_found and previous_found): # print("ERROR, failed to find a valid bounding weight entry") # print("next_found", next_found) # print("previous_found", previous_found) continue else: interpolated_weight = interpolate(w1, w2, y1, y2, dates[i]) # print(w1.lb, w2.lb, y1, y2, dates[i]) # print("interpolated as", interpolated_weight.lb) # update this entry with interpolated_weight Log.objects.filter(user=user).filter(date=dates[i]).update( weight=interpolated_weight) print( "Updated", dates[i].strftime("%m/%d/%Y"), "with weight", interpolated_weight, )
def zero_weight(): """Function used as a model's default.""" return Weight(kg=0)
def test_get_products_data(product, product_with_image, collection, image): # given product.weight = Weight(kg=5) product.save() collection.products.add(product) variant = product.variants.first() VariantImage.objects.create(variant=variant, image=product.images.first()) products = Product.objects.all() export_fields = set( value for mapping in ProductExportFields.HEADERS_TO_FIELDS_MAPPING.values() for value in mapping.values()) warehouse_ids = [ str(warehouse.pk) for warehouse in Warehouse.objects.all() ] attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()] variants = [] for variant in product.variants.all(): for attr in variant.attributes.all(): attribute_ids.append(str(attr.assignment.attribute.pk)) variant.weight = Weight(kg=3) variants.append(variant) ProductVariant.objects.bulk_update(variants, ["weight"]) variants = [] for variant in product_with_image.variants.all(): variant.weight = None variants.append(variant) ProductVariant.objects.bulk_update(variants, ["weight"]) # when result_data = get_products_data(products, export_fields, attribute_ids, warehouse_ids) # then expected_data = [] for product in products.order_by("pk"): product_data = { "id": product.id, "name": product.name, "is_published": product.is_published, "available_for_purchase": product.available_for_purchase, "visible_in_listings": product.visible_in_listings, "description": product.description, "category__slug": product.category.slug, "product_type__name": product.product_type.name, "charge_taxes": product.charge_taxes, "collections__slug": ("" if not product.collections.all() else product.collections.first().slug), "product_weight": ("{} g".format(int(product.weight.value * 1000)) if product.weight else ""), "images__image": ("" if not product.images.all() else "http://mirumee.com{}".format( product.images.first().image.url)), } product_data = add_product_attribute_data_to_expected_data( product_data, product, attribute_ids) for variant in product.variants.all(): data = { "variants__sku": variant.sku, "variants__currency": variant.currency, "variants__price_amount": variant.price_amount, "variants__cost_price_amount": variant.cost_price_amount, "variants__images__image": ("" if not variant.images.all() else "http://mirumee.com{}".format( variant.images.first().image.url)), "variant_weight": ("{} g".foramt(int(variant.weight.value * 1000)) if variant.weight else ""), } data.update(product_data) data = add_stocks_to_expected_data(data, variant, warehouse_ids) data = add_variant_attribute_data_to_expected_data( data, variant, attribute_ids) expected_data.append(data) assert result_data == expected_data
def to_python(self, value): value = super().to_python(value) if value is None: return value unit = get_default_weight_unit() return Weight(**{unit: value})
def processWeight(self): return float((Weight(lb=self.weightLb) + Weight(oz=self.weightOz)).kg)
assert "PL" in shipping_zone.countries result = ShippingMethod.objects.applicable_shipping_methods( price=Money(price, "USD"), weight=Weight(kg=0), country_code="PL", channel_id=channel_USD.id, ) result_ids = set([method.id for method in result]) assert len(result_ids) == len(result) assert (method in result) == shipping_included @pytest.mark.parametrize( "weight, min_weight, max_weight, shipping_included", ( (Weight(kg=1), Weight(kg=1), Weight(kg=2), True), # equal min weight (Weight(kg=10), Weight(kg=1), Weight(kg=10), True), # equal max weight (Weight(kg=5), Weight(kg=8), Weight(kg=15), False), # below min weight (Weight(kg=10), Weight(kg=1), Weight(kg=9), False), # above max weight (Weight(kg=10000000), Weight(kg=1), None, True), # no max weight limit (Weight(kg=10), Weight(kg=5), Weight(kg=15), True), ), ) # regular case def test_applicable_shipping_methods_weight( weight, min_weight, max_weight, shipping_included, shipping_zone, channel_USD ): method = shipping_zone.shipping_methods.create( minimum_order_weight=min_weight, maximum_order_weight=max_weight, type=ShippingMethodType.WEIGHT_BASED, )
for country in zone.countries] expected_choices = sorted(expected_choices, key=lambda choice: choice[1]) assert form.fields['country'].choices == expected_choices @pytest.mark.parametrize('minimum, maximum, value, result', ((10, None, 1500, True), (10, 20, 15, True), (10, 20, 20, True), (10, 20, 10, True), (10, 20, 9, False), (10, 21, 9, False))) def test_value_in_range(minimum, maximum, value, result): assert result == value_in_range(minimum, maximum, value) @pytest.mark.parametrize( 'weight, minimum_order_weight, maximum_order_weight, result', ((Weight(kg=15), Weight(kg=10), Weight(kg=20), True), (Weight(kg=15), Weight(kg=15), Weight(kg=20), True), (Weight(kg=15), Weight(kg=10), Weight(kg=15), True), (Weight(kg=15), Weight(kg=10), None, True), (Weight(kg=26), Weight(kg=10), Weight(kg=25), False), (Weight(kg=9), Weight(kg=10), Weight(kg=15), False))) def test_weight_shipping_method_applicable(weight, minimum_order_weight, maximum_order_weight, result): shipping_method = Mock(type=ShippingMethodType.WEIGHT_BASED, minimum_order_weight=minimum_order_weight, maximum_order_weight=maximum_order_weight) assert result == shipping_method_applicable(Money(0, 'USD'), weight, shipping_method) @pytest.mark.parametrize(
def create_fake_order(discounts, max_order_lines=5): channel = Channel.objects.all().order_by("?").first() customers = ( User.objects.filter(is_superuser=False) .exclude(default_billing_address=None) .order_by("?") ) customer = random.choice([None, customers.first()]) # 20% chance to be unconfirmed order. will_be_unconfirmed = random.choice([0, 0, 0, 0, 1]) if customer: address = customer.default_shipping_address order_data = { "user": customer, "billing_address": customer.default_billing_address, "shipping_address": address, } else: address = create_address() order_data = { "billing_address": address, "shipping_address": address, "user_email": get_email(address.first_name, address.last_name), } manager = get_plugins_manager() shipping_method_chanel_listing = ( ShippingMethodChannelListing.objects.filter(channel=channel) .order_by("?") .first() ) shipping_method = shipping_method_chanel_listing.shipping_method shipping_price = shipping_method_chanel_listing.price shipping_price = manager.apply_taxes_to_shipping(shipping_price, address) order_data.update( { "channel": channel, "shipping_method": shipping_method, "shipping_method_name": shipping_method.name, "shipping_price": shipping_price, } ) if will_be_unconfirmed: order_data["status"] = OrderStatus.UNCONFIRMED order = Order.objects.create(**order_data) lines = create_order_lines(order, discounts, random.randrange(1, max_order_lines)) order.total = sum([line.total_price for line in lines], shipping_price) weight = Weight(kg=0) for line in order: weight += line.variant.get_weight() order.weight = weight order.save() create_fake_payment(order=order) if not will_be_unconfirmed: create_fulfillments(order) return order
def test_get_day(self): self.client.unit_aware = True with patch.object(self.client, '_get_document_for_url') as get_doc: get_doc.return_value = self.get_html_document('diary.html') day = self.client.get_date(self.arbitrary_date1) expected_dict = { "lunch": [], "breakfast": [{ "nutrition_information": { "sodium": Weight(mg=380), "carbohydrates": Weight(g=44), "calories": Energy(Calorie=240), "fat": Weight(g=6), "sugar": Weight(g=8), "protein": Weight(g=10) }, "name": "Dave's Killer Bread - Blues Bread, 2 slice" }, { "nutrition_information": { "sodium": Weight(mg=100), "carbohydrates": Weight(g=0), "calories": Energy(Calorie=100), "fat": Weight(g=11), "sugar": Weight(g=0), "protein": Weight(g=0) }, "name": ("Earth Balance - " "Natural Buttery Spread - Original, 1 tbsp (14g)") }], "dinner": [{ "nutrition_information": { "sodium": Weight(mg=5), "carbohydrates": Weight(g=8), "calories": Energy(Calorie=288), "fat": Weight(g=0), "sugar": Weight(g=0), "protein": Weight(g=0) }, "name": "Wine - Pinot Noir Wine, 12 oz" }, { "nutrition_information": { "sodium": Weight(mg=1166), "carbohydrates": Weight(g=64), "calories": Energy(Calorie=690), "fat": Weight(g=48), "sugar": Weight(g=14), "protein": Weight(g=30) }, "name": "Generic - Baked Macaroni and Cheese, 14 grams" }], "snacks": [{ "nutrition_information": { "sodium": Weight(mg=80), "carbohydrates": Weight(g=3), "calories": Energy(Calorie=170), "fat": Weight(g=2), "sugar": Weight(g=2), "protein": Weight(g=36) }, "name": "Mrm - Dutch Chocolate Whey Protein, 2 scoop" }, { "nutrition_information": { "sodium": Weight(mg=338), "carbohydrates": Weight(g=36), "calories": Energy(Calorie=203), "fat": Weight(g=6), "sugar": Weight(g=34), "protein": Weight(g=2) }, "name": "Drinks - Almond Milk (Vanilla), 18 oz" }, { "nutrition_information": { "sodium": Weight(mg=0), "carbohydrates": Weight(g=48), "calories": Energy(Calorie=588), "fat": Weight(g=0), "sugar": Weight(g=0), "protein": Weight(g=0) }, "name": ("Dogfish Head 90 Minute Ipa - " "Beer, India Pale Ale, 24 oz") }] } actual_dict = day.get_as_dict() self.assertEquals( expected_dict, actual_dict, ) self.assertEquals( day.date, self.arbitrary_date1, ) self.assertEquals( day.complete, False, ) self.assertEquals( day.goals, { 'calories': Energy(Calorie=2500), 'carbohydrates': Weight(g=343), 'fat': Weight(g=84), 'protein': Weight(g=93), 'sodium': Weight(mg=2500), 'sugar': Weight(g=50), }) self.assertEquals( day.totals, { 'calories': Energy(Calorie=2279), 'carbohydrates': Weight(g=203), 'fat': Weight(g=73), 'protein': Weight(g=78), 'sodium': Weight(mg=2069), 'sugar': Weight(g=58), })
def weight(self): return Weight(kg=fake.pydecimal(1, 2, positive=True))
def zero_weight(): """Represent the zero weight value.""" return Weight(kg=0)
def test_convert_weight(): weight = Weight(kg=1) expected_result = Weight(g=1000) assert convert_weight(weight, WeightUnits.GRAM) == expected_result
def test_get_order_line_payload(order_line): order_line.variant.product.weight = Weight(kg=5) order_line.variant.product.save() payload = get_order_line_payload(order_line) attributes = order_line.variant.product.attributes.all() expected_attributes_payload = [] for attr in attributes: expected_attributes_payload.append({ "assignment": { "attribute": { "slug": attr.assignment.attribute.slug, "name": attr.assignment.attribute.name, } }, "values": [{ "name": value.name, "value": value.value, "slug": value.slug, "file_url": value.file_url, } for value in attr.values.all()], }) unit_tax_amount = (order_line.unit_price_gross_amount - order_line.unit_price_net_amount) total_gross = order_line.unit_price_gross * order_line.quantity total_net = order_line.unit_price_net * order_line.quantity total_tax = total_gross - total_net currency = order_line.currency assert payload == { "variant": { "id": order_line.variant_id, "first_image": None, "images": None, "weight": "", "is_preorder": False, "preorder_global_threshold": None, "preorder_end_date": None, }, "product": { "attributes": expected_attributes_payload, "first_image": None, "images": None, "weight": "5.0 kg", "id": order_line.variant.product.id, }, "translated_product_name": order_line.translated_product_name or order_line.product_name, "translated_variant_name": order_line.translated_variant_name or order_line.variant_name, "id": order_line.id, "product_name": order_line.product_name, "variant_name": order_line.variant_name, "product_sku": order_line.product_sku, "product_variant_id": order_line.product_variant_id, "is_shipping_required": order_line.is_shipping_required, "quantity": order_line.quantity, "quantity_fulfilled": order_line.quantity_fulfilled, "currency": order_line.currency, "unit_price_net_amount": quantize_price(order_line.unit_price_net_amount, currency), "unit_price_gross_amount": quantize_price(order_line.unit_price_gross_amount, currency), "unit_tax_amount": quantize_price(unit_tax_amount, currency), "total_gross_amount": quantize_price(total_gross.amount, currency), "total_net_amount": quantize_price(total_net.amount, currency), "total_tax_amount": quantize_price(total_tax.amount, currency), "tax_rate": order_line.tax_rate, "is_digital": order_line.is_digital, "digital_url": "", "unit_discount_amount": order_line.unit_discount_amount, "unit_discount_reason": order_line.unit_discount_reason, "unit_discount_type": order_line.unit_discount_type, "unit_discount_value": order_line.unit_discount_value, }
def get_weight(weight): if not weight: return zero_weight() value, unit = weight.split() return Weight(**{unit: value})
def convert_kg_to_lbs(initial_number): return round(Weight(kg=initial_number).lb, 5)