input
stringclasses
1 value
instruction
stringclasses
326 values
output
stringclasses
36 values
I need integration test for this code
I need integration test for this code import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from phonenumber_field.modelfields import PhoneNumberField from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import UppercaseCharField class AbstractAddress(models.Model): """ Superclass address object This is subclassed and extended to provide models for user, shipping and billing addresses. """ MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) POSTCODE_REQUIRED = 'postcode' in settings.OSCAR_REQUIRED_ADDRESS_FIELDS # Regex for each country. Not listed countries don't use postcodes # Based on http://en.wikipedia.org/wiki/List_of_postal_codes POSTCODES_REGEX = { 'AC': r'^[A-Z]{4}[0-9][A-Z]$', 'AD': r'^AD[0-9]{3}$', 'AF': r'^[0-9]{4}$', 'AI': r'^AI-2640$', 'AL': r'^[0-9]{4}$', 'AM': r'^[0-9]{4}$', 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3})$', 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'AT': r'^[0-9]{4}$', 'AU': r'^[0-9]{4}$', 'AX': r'^[0-9]{5}$', 'AZ': r'^AZ[0-9]{4}$', 'BA': r'^[0-9]{5}$', 'BB': r'^BB[0-9]{5}$', 'BD': r'^[0-9]{4}$', 'BE': r'^[0-9]{4}$', 'BG': r'^[0-9]{4}$', 'BH': r'^[0-9]{3,4}$', 'BL': r'^[0-9]{5}$', 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})', 'BN': r'^[A-Z]{2}[0-9]{4}$', 'BO': r'^[0-9]{4}$', 'BR': r'^[0-9]{5}(-[0-9]{3})?$', 'BT': r'^[0-9]{3}$', 'BY': r'^[0-9]{6}$', 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$', 'CC': r'^[0-9]{4}$', 'CH': r'^[0-9]{4}$', 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$', 'CN': r'^[0-9]{6}$', 'CO': r'^[0-9]{6}$', 'CR': r'^[0-9]{4,5}$', 'CU': r'^[0-9]{5}$', 'CV': r'^[0-9]{4}$', 'CX': r'^[0-9]{4}$', 'CY': r'^[0-9]{4}$', 'CZ': r'^[0-9]{5}$', 'DE': r'^[0-9]{5}$', 'DK': r'^[0-9]{4}$', 'DO': r'^[0-9]{5}$', 'DZ': r'^[0-9]{5}$', 'EC': r'^EC[0-9]{6}$', 'EE': r'^[0-9]{5}$', 'EG': r'^[0-9]{5}$', 'ES': r'^[0-9]{5}$', 'ET': r'^[0-9]{4}$', 'FI': r'^[0-9]{5}$', 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'FM': r'^[0-9]{5}(-[0-9]{4})?$', 'FO': r'^[0-9]{3}$', 'FR': r'^[0-9]{5}$', 'GA': r'^[0-9]{2}.*[0-9]{2}$', 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$', 'GE': r'^[0-9]{4}$', 'GF': r'^[0-9]{5}$', 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2})$', 'GI': r'^GX111AA$', 'GL': r'^[0-9]{4}$', 'GP': r'^[0-9]{5}$', 'GR': r'^[0-9]{5}$', 'GS': r'^SIQQ1ZZ$', 'GT': r'^[0-9]{5}$', 'GU': r'^[0-9]{5}$', 'GW': r'^[0-9]{4}$', 'HM': r'^[0-9]{4}$', 'HN': r'^[0-9]{5}$', 'HR': r'^[0-9]{5}$', 'HT': r'^[0-9]{4}$', 'HU': r'^[0-9]{4}$', 'ID': r'^[0-9]{5}$', 'IL': r'^[0-9]{7}$', 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$', 'IN': r'^[0-9]{6}$', 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'IQ': r'^[0-9]{5}$', 'IR': r'^[0-9]{5}-[0-9]{5}$', 'IS': r'^[0-9]{3}$', 'IT': r'^[0-9]{5}$', 'JE': r'^JE[0-9]{2}[A-Z]{2}$', 'JM': r'^JM[A-Z]{3}[0-9]{2}$', 'JO': r'^[0-9]{5}$', 'JP': r'^[0-9]{3}-?[0-9]{4}$', 'KE': r'^[0-9]{5}$', 'KG': r'^[0-9]{6}$', 'KH': r'^[0-9]{5}$', 'KR': r'^[0-9]{5}$', 'KY': r'^KY[0-9]-[0-9]{4}$', 'KZ': r'^[0-9]{6}$', 'LA': r'^[0-9]{5}$', 'LB': r'^[0-9]{8}$', 'LI': r'^[0-9]{4}$', 'LK': r'^[0-9]{5}$', 'LR': r'^[0-9]{4}$', 'LS': r'^[0-9]{3}$', 'LT': r'^(LT-)?[0-9]{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', 'MZ': r'^[0-9]{4}$', 'NA': r'^[0-9]{5}$', 'NC': r'^[0-9]{5}$', 'NE': r'^[0-9]{4}$', 'NF': r'^[0-9]{4}$', 'NG': r'^[0-9]{6}$', 'NI': r'^[0-9]{5}$', 'NL': r'^[0-9]{4}[A-Z]{2}$', 'NO': r'^[0-9]{4}$', 'NP': r'^[0-9]{5}$', 'NZ': r'^[0-9]{4}$', 'OM': r'^[0-9]{3}$', 'PA': r'^[0-9]{6}$', 'PE': r'^[0-9]{5}$', 'PF': r'^[0-9]{5}$', 'PG': r'^[0-9]{3}$', 'PH': r'^[0-9]{4}$', 'PK': r'^[0-9]{5}$', 'PL': r'^[0-9]{2}-?[0-9]{3}$', 'PM': r'^[0-9]{5}$', 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'PR': r'^[0-9]{5}$', 'PT': r'^[0-9]{4}(-?[0-9]{3})?$', 'PW': r'^[0-9]{5}$', 'PY': r'^[0-9]{4}$', 'RE': r'^[0-9]{5}$', 'RO': r'^[0-9]{6}$', 'RS': r'^[0-9]{5}$', 'RU': r'^[0-9]{6}$', 'SA': r'^[0-9]{5}$', 'SD': r'^[0-9]{5}$', 'SE': r'^[0-9]{5}$', 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$', 'SH': r'^(STHL1ZZ|TDCU1ZZ)$', 'SI': r'^(SI-)?[0-9]{4}$', 'SK': r'^[0-9]{5}$', 'SM': r'^[0-9]{5}$', 'SN': r'^[0-9]{5}$', 'SV': r'^01101$', 'SZ': r'^[A-Z][0-9]{3}$', 'TC': r'^TKCA1ZZ$', 'TD': r'^[0-9]{5}$', 'TH': r'^[0-9]{5}$', 'TJ': r'^[0-9]{6}$', 'TM': r'^[0-9]{6}$', 'TN': r'^[0-9]{4}$', 'TR': r'^[0-9]{5}$', 'TT': r'^[0-9]{6}$', 'TW': r'^([0-9]{3}|[0-9]{5})$', 'UA': r'^[0-9]{5}$', 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'UY': r'^[0-9]{5}$', 'UZ': r'^[0-9]{6}$', 'VA': r'^00120$', 'VC': r'^VC[0-9]{4}', 'VE': r'^[0-9]{4}[A-Z]?$', 'VG': r'^VG[0-9]{4}$', 'VI': r'^[0-9]{5}$', 'VN': r'^[0-9]{6}$', 'WF': r'^[0-9]{5}$', 'XK': r'^[0-9]{5}$', 'YT': r'^[0-9]{5}$', 'ZA': r'^[0-9]{4}$', 'ZM': r'^[0-9]{5}$', } title = models.CharField( pgettext_lazy("Treatment Pronouns for the customer", "Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, blank=True) # We use quite a few lines of an address as they are often quite long and # it's easier to just hide the unnecessary ones than add extra ones. line1 = models.CharField(_("First line of address"), max_length=255) line2 = models.CharField( _("Second line of address"), max_length=255, blank=True) line3 = models.CharField( _("Third line of address"), max_length=255, blank=True) line4 = models.CharField(_("City"), max_length=255, blank=True) state = models.CharField(_("State/County"), max_length=255, blank=True) postcode = UppercaseCharField( _("Post/Zip-code"), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', on_delete=models.CASCADE, verbose_name=_("Country")) #: A field only used for searching addresses - this contains all the #: relevant fields. This is effectively a poor man's Solr text field. search_text = models.TextField( _("Search text - used only for searching addresses"), editable=False) # Fields, used for `summary` property definition and hash generation. base_fields = hash_fields = ['salutation', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode', 'country'] def __str__(self): return self.summary class Meta: abstract = True verbose_name = _('Address') verbose_name_plural = _('Addresses') # Saving def save(self, *args, **kwargs): self._update_search_text() super().save(*args, **kwargs) def clean(self): # Strip all whitespace for field in ['first_name', 'last_name', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode']: if self.__dict__[field]: self.__dict__[field] = self.__dict__[field].strip() # Ensure postcodes are valid for country self.ensure_postcode_is_valid_for_country() def ensure_postcode_is_valid_for_country(self): """ Validate postcode given the country """ if not self.postcode and self.POSTCODE_REQUIRED and self.country_id: country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) if regex: msg = _("Addresses in %(country)s require a valid postcode") \ % {'country': self.country} raise exceptions.ValidationError(msg) if self.postcode and self.country_id: # Ensure postcodes are always uppercase postcode = self.postcode.upper().replace(' ', '') country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) # Validate postcode against regex for the country if available if regex and not re.match(regex, postcode): msg = _("The postcode '%(postcode)s' is not valid " "for %(country)s") \ % {'postcode': self.postcode, 'country': self.country} raise exceptions.ValidationError( {'postcode': [msg]}) def _update_search_text(self): search_fields = filter( bool, [self.first_name, self.last_name, self.line1, self.line2, self.line3, self.line4, self.state, self.postcode, self.country.name]) self.search_text = ' '.join(search_fields) # Properties @property def city(self): # Common alias return self.line4 @property def summary(self): """ Returns a single string summary of the address, separating fields using commas. """ return ", ".join(self.active_address_fields()) @property def salutation(self): """ Name (including title) """ return self.join_fields( ('title', 'first_name', 'last_name'), separator=" ") @property def name(self): return self.join_fields(('first_name', 'last_name'), separator=" ") # Helpers def get_field_values(self, fields): field_values = [] for field in fields: # Title is special case if field == 'title': value = self.get_title_display() elif field == 'country': try: value = self.country.printable_name except exceptions.ObjectDoesNotExist: value = '' elif field == 'salutation': value = self.salutation else: value = getattr(self, field) field_values.append(value) return field_values def get_address_field_values(self, fields): """ Returns set of field values within the salutation and country. """ field_values = [f.strip() for f in self.get_field_values(fields) if f] return field_values def generate_hash(self): """ Returns a hash of the address, based on standard set of fields, listed out in `hash_fields` property. """ field_values = self.get_address_field_values(self.hash_fields) # Python 2 and 3 generates CRC checksum in different ranges, so # in order to generate platform-independent value we apply # `& 0xffffffff` expression. return zlib.crc32(', '.join(field_values).upper().encode('UTF8')) & 0xffffffff def join_fields(self, fields, separator=", "): """ Join a sequence of fields using the specified separator """ field_values = self.get_field_values(fields) return separator.join(filter(bool, field_values)) def populate_alternative_model(self, address_model): """ For populating an address model using the matching fields from this one. This is used to convert a user address to a shipping address as part of the checkout process. """ destination_field_names = [ field.name for field in address_model._meta.fields] for field_name in [field.name for field in self._meta.fields]: if field_name in destination_field_names and field_name != 'id': setattr(address_model, field_name, getattr(self, field_name)) def active_address_fields(self): """ Returns the non-empty components of the address, but merging the title, first_name and last_name into a single line. It uses fields listed out in `base_fields` property. """ return self.get_address_field_values(self.base_fields) class AbstractCountry(models.Model): """ International Organization for Standardization (ISO) 3166-1 Country list. The field names are a bit awkward, but kept for backwards compatibility. pycountry's syntax of alpha2, alpha3, name and official_name seems sane. """ iso_3166_1_a2 = models.CharField( _('ISO 3166-1 alpha-2'), max_length=2, primary_key=True) iso_3166_1_a3 = models.CharField( _('ISO 3166-1 alpha-3'), max_length=3, blank=True) iso_3166_1_numeric = models.CharField( _('ISO 3166-1 numeric'), blank=True, max_length=3) #: The commonly used name; e.g. 'United Kingdom' printable_name = models.CharField(_('Country name'), max_length=128) #: The full official name of a country #: e.g. 'United Kingdom of Great Britain and Northern Ireland' name = models.CharField(_('Official name'), max_length=128) display_order = models.PositiveSmallIntegerField( _("Display order"), default=0, db_index=True, help_text=_('Higher the number, higher the country in the list.')) is_shipping_country = models.BooleanField( _("Is shipping country"), default=False, db_index=True) class Meta: abstract = True app_label = 'address' verbose_name = _('Country') verbose_name_plural = _('Countries') ordering = ('-display_order', 'printable_name',) def __str__(self): return self.printable_name or self.name @property def code(self): """ Shorthand for the ISO 3166 Alpha-2 code """ return self.iso_3166_1_a2 @property def numeric_code(self): """ Shorthand for the ISO 3166 numeric code. iso_3166_1_numeric used to wrongly be a integer field, but has to be padded with leading zeroes. It's since been converted to a char field, but the database might still contain non-padded strings. That's why the padding is kept. """ return "%.03d" % int(self.iso_3166_1_numeric) class AbstractShippingAddress(AbstractAddress): """ A shipping address. A shipping address should not be edited once the order has been placed - it should be read-only after that. NOTE: ShippingAddress is a model of the order app. But moving it there is tricky due to circular import issues that are amplified by get_model/get_class calls pre-Django 1.7 to register receivers. So... TODO: Once Django 1.6 support is dropped, move AbstractBillingAddress and AbstractShippingAddress to the order app, and move PartnerAddress to the partner app. """ phone_number = PhoneNumberField( _("Phone number"), blank=True, help_text=_("In case we need to call you about your order")) notes = models.TextField( blank=True, verbose_name=_('Instructions'), help_text=_("Tell us anything we should know when delivering " "your order.")) class Meta: abstract = True # ShippingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Shipping address") verbose_name_plural = _("Shipping addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractUserAddress(AbstractShippingAddress): """ A user's address. A user can have many of these and together they form an 'address book' of sorts for the user. We use a separate model for shipping and billing (even though there will be some data duplication) because we don't want shipping/billing addresses changed or deleted once an order has been placed. By having a separate model, we allow users the ability to add/edit/delete from their address book without affecting orders already placed. """ user = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='addresses', verbose_name=_("User")) #: Whether this address is the default for shipping is_default_for_shipping = models.BooleanField( _("Default shipping address?"), default=False) #: Whether this address should be the default for billing. is_default_for_billing = models.BooleanField( _("Default billing address?"), default=False) #: We keep track of the number of times an address has been used #: as a shipping address so we can show the most popular ones #: first at the checkout. num_orders_as_shipping_address = models.PositiveIntegerField( _("Number of Orders as Shipping Address"), default=0) #: Same as previous, but for billing address. num_orders_as_billing_address = models.PositiveIntegerField( _("Number of Orders as Billing Address"), default=0) #: A hash is kept to try and avoid duplicate addresses being added #: to the address book. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True, editable=False) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) def save(self, *args, **kwargs): """ Save a hash of the address fields """ # Save a hash of the address fields so we can check whether two # addresses are the same to avoid saving duplicates self.hash = self.generate_hash() # Ensure that each user only has one default shipping address # and billing address self._ensure_defaults_integrity() super().save(*args, **kwargs) def _ensure_defaults_integrity(self): if self.is_default_for_shipping: self.__class__._default_manager\ .filter(user=self.user, is_default_for_shipping=True)\ .update(is_default_for_shipping=False) if self.is_default_for_billing: self.__class__._default_manager\ .filter(user=self.user, is_default_for_billing=True)\ .update(is_default_for_billing=False) class Meta: abstract = True app_label = 'address' verbose_name = _("User address") verbose_name_plural = _("User addresses") ordering = ['-num_orders_as_shipping_address'] unique_together = ('user', 'hash') def validate_unique(self, exclude=None): super().validate_unique(exclude) qs = self.__class__.objects.filter( user=self.user, hash=self.generate_hash()) if self.id: qs = qs.exclude(id=self.id) if qs.exists(): raise exceptions.ValidationError({ '__all__': [_("This address is already in your address" " book")]}) class AbstractBillingAddress(AbstractAddress): class Meta: abstract = True # BillingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Billing address") verbose_name_plural = _("Billing addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractPartnerAddress(AbstractAddress): """ A partner can have one or more addresses. This can be useful e.g. when determining US tax which depends on the origin of the shipment. """ partner = models.ForeignKey( 'partner.Partner', on_delete=models.CASCADE, related_name='addresses', verbose_name=_('Partner')) class Meta: abstract = True app_label = 'partner' verbose_name = _("Partner address") verbose_name_plural = _("Partner addresses")
from django.test import TestCase from oscar.apps.address import models, forms from oscar.test.factories import UserFactory class TestUserAddressForm(TestCase): def setUp(self): self.user = UserFactory() self.country = models.Country.objects.create( iso_3166_1_a2='GB', name="UNITED KINGDOM") def test_merges_addresses_with_same_hash(self): data = { 'user': self.user, 'first_name': "Matus", 'last_name': "Moravcik", 'line1': "1 Egg Street", 'line4': "London", 'postcode': "N12 9RE", 'country': self.country} # Create two addresses, which are slightly different models.UserAddress.objects.create(**data) other = data.copy() other['first_name'] = 'Izidor' duplicate = models.UserAddress.objects.create(**other) # Edit duplicate to be same as original and check that the two # addresses are merged when the form saves. post_data = data.copy() post_data['country'] = self.country.iso_3166_1_a2 form = forms.UserAddressForm(self.user, post_data, instance=duplicate) self.assertFalse(form.is_valid()) self.assertTrue(len(form.errors['__all__']) > 0)
I need integration test for this code import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from phonenumber_field.modelfields import PhoneNumberField from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import UppercaseCharField class AbstractAddress(models.Model): """ Superclass address object This is subclassed and extended to provide models for user, shipping and billing addresses. """ MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) POSTCODE_REQUIRED = 'postcode' in settings.OSCAR_REQUIRED_ADDRESS_FIELDS # Regex for each country. Not listed countries don't use postcodes # Based on http://en.wikipedia.org/wiki/List_of_postal_codes POSTCODES_REGEX = { 'AC': r'^[A-Z]{4}[0-9][A-Z]$', 'AD': r'^AD[0-9]{3}$', 'AF': r'^[0-9]{4}$', 'AI': r'^AI-2640$', 'AL': r'^[0-9]{4}$', 'AM': r'^[0-9]{4}$', 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3})$', 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'AT': r'^[0-9]{4}$', 'AU': r'^[0-9]{4}$', 'AX': r'^[0-9]{5}$', 'AZ': r'^AZ[0-9]{4}$', 'BA': r'^[0-9]{5}$', 'BB': r'^BB[0-9]{5}$', 'BD': r'^[0-9]{4}$', 'BE': r'^[0-9]{4}$', 'BG': r'^[0-9]{4}$', 'BH': r'^[0-9]{3,4}$', 'BL': r'^[0-9]{5}$', 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})', 'BN': r'^[A-Z]{2}[0-9]{4}$', 'BO': r'^[0-9]{4}$', 'BR': r'^[0-9]{5}(-[0-9]{3})?$', 'BT': r'^[0-9]{3}$', 'BY': r'^[0-9]{6}$', 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$', 'CC': r'^[0-9]{4}$', 'CH': r'^[0-9]{4}$', 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$', 'CN': r'^[0-9]{6}$', 'CO': r'^[0-9]{6}$', 'CR': r'^[0-9]{4,5}$', 'CU': r'^[0-9]{5}$', 'CV': r'^[0-9]{4}$', 'CX': r'^[0-9]{4}$', 'CY': r'^[0-9]{4}$', 'CZ': r'^[0-9]{5}$', 'DE': r'^[0-9]{5}$', 'DK': r'^[0-9]{4}$', 'DO': r'^[0-9]{5}$', 'DZ': r'^[0-9]{5}$', 'EC': r'^EC[0-9]{6}$', 'EE': r'^[0-9]{5}$', 'EG': r'^[0-9]{5}$', 'ES': r'^[0-9]{5}$', 'ET': r'^[0-9]{4}$', 'FI': r'^[0-9]{5}$', 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'FM': r'^[0-9]{5}(-[0-9]{4})?$', 'FO': r'^[0-9]{3}$', 'FR': r'^[0-9]{5}$', 'GA': r'^[0-9]{2}.*[0-9]{2}$', 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$', 'GE': r'^[0-9]{4}$', 'GF': r'^[0-9]{5}$', 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2})$', 'GI': r'^GX111AA$', 'GL': r'^[0-9]{4}$', 'GP': r'^[0-9]{5}$', 'GR': r'^[0-9]{5}$', 'GS': r'^SIQQ1ZZ$', 'GT': r'^[0-9]{5}$', 'GU': r'^[0-9]{5}$', 'GW': r'^[0-9]{4}$', 'HM': r'^[0-9]{4}$', 'HN': r'^[0-9]{5}$', 'HR': r'^[0-9]{5}$', 'HT': r'^[0-9]{4}$', 'HU': r'^[0-9]{4}$', 'ID': r'^[0-9]{5}$', 'IL': r'^[0-9]{7}$', 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$', 'IN': r'^[0-9]{6}$', 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'IQ': r'^[0-9]{5}$', 'IR': r'^[0-9]{5}-[0-9]{5}$', 'IS': r'^[0-9]{3}$', 'IT': r'^[0-9]{5}$', 'JE': r'^JE[0-9]{2}[A-Z]{2}$', 'JM': r'^JM[A-Z]{3}[0-9]{2}$', 'JO': r'^[0-9]{5}$', 'JP': r'^[0-9]{3}-?[0-9]{4}$', 'KE': r'^[0-9]{5}$', 'KG': r'^[0-9]{6}$', 'KH': r'^[0-9]{5}$', 'KR': r'^[0-9]{5}$', 'KY': r'^KY[0-9]-[0-9]{4}$', 'KZ': r'^[0-9]{6}$', 'LA': r'^[0-9]{5}$', 'LB': r'^[0-9]{8}$', 'LI': r'^[0-9]{4}$', 'LK': r'^[0-9]{5}$', 'LR': r'^[0-9]{4}$', 'LS': r'^[0-9]{3}$', 'LT': r'^(LT-)?[0-9]{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', 'MZ': r'^[0-9]{4}$', 'NA': r'^[0-9]{5}$', 'NC': r'^[0-9]{5}$', 'NE': r'^[0-9]{4}$', 'NF': r'^[0-9]{4}$', 'NG': r'^[0-9]{6}$', 'NI': r'^[0-9]{5}$', 'NL': r'^[0-9]{4}[A-Z]{2}$', 'NO': r'^[0-9]{4}$', 'NP': r'^[0-9]{5}$', 'NZ': r'^[0-9]{4}$', 'OM': r'^[0-9]{3}$', 'PA': r'^[0-9]{6}$', 'PE': r'^[0-9]{5}$', 'PF': r'^[0-9]{5}$', 'PG': r'^[0-9]{3}$', 'PH': r'^[0-9]{4}$', 'PK': r'^[0-9]{5}$', 'PL': r'^[0-9]{2}-?[0-9]{3}$', 'PM': r'^[0-9]{5}$', 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'PR': r'^[0-9]{5}$', 'PT': r'^[0-9]{4}(-?[0-9]{3})?$', 'PW': r'^[0-9]{5}$', 'PY': r'^[0-9]{4}$', 'RE': r'^[0-9]{5}$', 'RO': r'^[0-9]{6}$', 'RS': r'^[0-9]{5}$', 'RU': r'^[0-9]{6}$', 'SA': r'^[0-9]{5}$', 'SD': r'^[0-9]{5}$', 'SE': r'^[0-9]{5}$', 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$', 'SH': r'^(STHL1ZZ|TDCU1ZZ)$', 'SI': r'^(SI-)?[0-9]{4}$', 'SK': r'^[0-9]{5}$', 'SM': r'^[0-9]{5}$', 'SN': r'^[0-9]{5}$', 'SV': r'^01101$', 'SZ': r'^[A-Z][0-9]{3}$', 'TC': r'^TKCA1ZZ$', 'TD': r'^[0-9]{5}$', 'TH': r'^[0-9]{5}$', 'TJ': r'^[0-9]{6}$', 'TM': r'^[0-9]{6}$', 'TN': r'^[0-9]{4}$', 'TR': r'^[0-9]{5}$', 'TT': r'^[0-9]{6}$', 'TW': r'^([0-9]{3}|[0-9]{5})$', 'UA': r'^[0-9]{5}$', 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'UY': r'^[0-9]{5}$', 'UZ': r'^[0-9]{6}$', 'VA': r'^00120$', 'VC': r'^VC[0-9]{4}', 'VE': r'^[0-9]{4}[A-Z]?$', 'VG': r'^VG[0-9]{4}$', 'VI': r'^[0-9]{5}$', 'VN': r'^[0-9]{6}$', 'WF': r'^[0-9]{5}$', 'XK': r'^[0-9]{5}$', 'YT': r'^[0-9]{5}$', 'ZA': r'^[0-9]{4}$', 'ZM': r'^[0-9]{5}$', } title = models.CharField( pgettext_lazy("Treatment Pronouns for the customer", "Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, blank=True) # We use quite a few lines of an address as they are often quite long and # it's easier to just hide the unnecessary ones than add extra ones. line1 = models.CharField(_("First line of address"), max_length=255) line2 = models.CharField( _("Second line of address"), max_length=255, blank=True) line3 = models.CharField( _("Third line of address"), max_length=255, blank=True) line4 = models.CharField(_("City"), max_length=255, blank=True) state = models.CharField(_("State/County"), max_length=255, blank=True) postcode = UppercaseCharField( _("Post/Zip-code"), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', on_delete=models.CASCADE, verbose_name=_("Country")) #: A field only used for searching addresses - this contains all the #: relevant fields. This is effectively a poor man's Solr text field. search_text = models.TextField( _("Search text - used only for searching addresses"), editable=False) # Fields, used for `summary` property definition and hash generation. base_fields = hash_fields = ['salutation', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode', 'country'] def __str__(self): return self.summary class Meta: abstract = True verbose_name = _('Address') verbose_name_plural = _('Addresses') # Saving def save(self, *args, **kwargs): self._update_search_text() super().save(*args, **kwargs) def clean(self): # Strip all whitespace for field in ['first_name', 'last_name', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode']: if self.__dict__[field]: self.__dict__[field] = self.__dict__[field].strip() # Ensure postcodes are valid for country self.ensure_postcode_is_valid_for_country() def ensure_postcode_is_valid_for_country(self): """ Validate postcode given the country """ if not self.postcode and self.POSTCODE_REQUIRED and self.country_id: country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) if regex: msg = _("Addresses in %(country)s require a valid postcode") \ % {'country': self.country} raise exceptions.ValidationError(msg) if self.postcode and self.country_id: # Ensure postcodes are always uppercase postcode = self.postcode.upper().replace(' ', '') country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) # Validate postcode against regex for the country if available if regex and not re.match(regex, postcode): msg = _("The postcode '%(postcode)s' is not valid " "for %(country)s") \ % {'postcode': self.postcode, 'country': self.country} raise exceptions.ValidationError( {'postcode': [msg]}) def _update_search_text(self): search_fields = filter( bool, [self.first_name, self.last_name, self.line1, self.line2, self.line3, self.line4, self.state, self.postcode, self.country.name]) self.search_text = ' '.join(search_fields) # Properties @property def city(self): # Common alias return self.line4 @property def summary(self): """ Returns a single string summary of the address, separating fields using commas. """ return ", ".join(self.active_address_fields()) @property def salutation(self): """ Name (including title) """ return self.join_fields( ('title', 'first_name', 'last_name'), separator=" ") @property def name(self): return self.join_fields(('first_name', 'last_name'), separator=" ") # Helpers def get_field_values(self, fields): field_values = [] for field in fields: # Title is special case if field == 'title': value = self.get_title_display() elif field == 'country': try: value = self.country.printable_name except exceptions.ObjectDoesNotExist: value = '' elif field == 'salutation': value = self.salutation else: value = getattr(self, field) field_values.append(value) return field_values def get_address_field_values(self, fields): """ Returns set of field values within the salutation and country. """ field_values = [f.strip() for f in self.get_field_values(fields) if f] return field_values def generate_hash(self): """ Returns a hash of the address, based on standard set of fields, listed out in `hash_fields` property. """ field_values = self.get_address_field_values(self.hash_fields) # Python 2 and 3 generates CRC checksum in different ranges, so # in order to generate platform-independent value we apply # `& 0xffffffff` expression. return zlib.crc32(', '.join(field_values).upper().encode('UTF8')) & 0xffffffff def join_fields(self, fields, separator=", "): """ Join a sequence of fields using the specified separator """ field_values = self.get_field_values(fields) return separator.join(filter(bool, field_values)) def populate_alternative_model(self, address_model): """ For populating an address model using the matching fields from this one. This is used to convert a user address to a shipping address as part of the checkout process. """ destination_field_names = [ field.name for field in address_model._meta.fields] for field_name in [field.name for field in self._meta.fields]: if field_name in destination_field_names and field_name != 'id': setattr(address_model, field_name, getattr(self, field_name)) def active_address_fields(self): """ Returns the non-empty components of the address, but merging the title, first_name and last_name into a single line. It uses fields listed out in `base_fields` property. """ return self.get_address_field_values(self.base_fields) class AbstractCountry(models.Model): """ International Organization for Standardization (ISO) 3166-1 Country list. The field names are a bit awkward, but kept for backwards compatibility. pycountry's syntax of alpha2, alpha3, name and official_name seems sane. """ iso_3166_1_a2 = models.CharField( _('ISO 3166-1 alpha-2'), max_length=2, primary_key=True) iso_3166_1_a3 = models.CharField( _('ISO 3166-1 alpha-3'), max_length=3, blank=True) iso_3166_1_numeric = models.CharField( _('ISO 3166-1 numeric'), blank=True, max_length=3) #: The commonly used name; e.g. 'United Kingdom' printable_name = models.CharField(_('Country name'), max_length=128) #: The full official name of a country #: e.g. 'United Kingdom of Great Britain and Northern Ireland' name = models.CharField(_('Official name'), max_length=128) display_order = models.PositiveSmallIntegerField( _("Display order"), default=0, db_index=True, help_text=_('Higher the number, higher the country in the list.')) is_shipping_country = models.BooleanField( _("Is shipping country"), default=False, db_index=True) class Meta: abstract = True app_label = 'address' verbose_name = _('Country') verbose_name_plural = _('Countries') ordering = ('-display_order', 'printable_name',) def __str__(self): return self.printable_name or self.name @property def code(self): """ Shorthand for the ISO 3166 Alpha-2 code """ return self.iso_3166_1_a2 @property def numeric_code(self): """ Shorthand for the ISO 3166 numeric code. iso_3166_1_numeric used to wrongly be a integer field, but has to be padded with leading zeroes. It's since been converted to a char field, but the database might still contain non-padded strings. That's why the padding is kept. """ return "%.03d" % int(self.iso_3166_1_numeric) class AbstractShippingAddress(AbstractAddress): """ A shipping address. A shipping address should not be edited once the order has been placed - it should be read-only after that. NOTE: ShippingAddress is a model of the order app. But moving it there is tricky due to circular import issues that are amplified by get_model/get_class calls pre-Django 1.7 to register receivers. So... TODO: Once Django 1.6 support is dropped, move AbstractBillingAddress and AbstractShippingAddress to the order app, and move PartnerAddress to the partner app. """ phone_number = PhoneNumberField( _("Phone number"), blank=True, help_text=_("In case we need to call you about your order")) notes = models.TextField( blank=True, verbose_name=_('Instructions'), help_text=_("Tell us anything we should know when delivering " "your order.")) class Meta: abstract = True # ShippingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Shipping address") verbose_name_plural = _("Shipping addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractUserAddress(AbstractShippingAddress): """ A user's address. A user can have many of these and together they form an 'address book' of sorts for the user. We use a separate model for shipping and billing (even though there will be some data duplication) because we don't want shipping/billing addresses changed or deleted once an order has been placed. By having a separate model, we allow users the ability to add/edit/delete from their address book without affecting orders already placed. """ user = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='addresses', verbose_name=_("User")) #: Whether this address is the default for shipping is_default_for_shipping = models.BooleanField( _("Default shipping address?"), default=False) #: Whether this address should be the default for billing. is_default_for_billing = models.BooleanField( _("Default billing address?"), default=False) #: We keep track of the number of times an address has been used #: as a shipping address so we can show the most popular ones #: first at the checkout. num_orders_as_shipping_address = models.PositiveIntegerField( _("Number of Orders as Shipping Address"), default=0) #: Same as previous, but for billing address. num_orders_as_billing_address = models.PositiveIntegerField( _("Number of Orders as Billing Address"), default=0) #: A hash is kept to try and avoid duplicate addresses being added #: to the address book. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True, editable=False) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) def save(self, *args, **kwargs): """ Save a hash of the address fields """ # Save a hash of the address fields so we can check whether two # addresses are the same to avoid saving duplicates self.hash = self.generate_hash() # Ensure that each user only has one default shipping address # and billing address self._ensure_defaults_integrity() super().save(*args, **kwargs) def _ensure_defaults_integrity(self): if self.is_default_for_shipping: self.__class__._default_manager\ .filter(user=self.user, is_default_for_shipping=True)\ .update(is_default_for_shipping=False) if self.is_default_for_billing: self.__class__._default_manager\ .filter(user=self.user, is_default_for_billing=True)\ .update(is_default_for_billing=False) class Meta: abstract = True app_label = 'address' verbose_name = _("User address") verbose_name_plural = _("User addresses") ordering = ['-num_orders_as_shipping_address'] unique_together = ('user', 'hash') def validate_unique(self, exclude=None): super().validate_unique(exclude) qs = self.__class__.objects.filter( user=self.user, hash=self.generate_hash()) if self.id: qs = qs.exclude(id=self.id) if qs.exists(): raise exceptions.ValidationError({ '__all__': [_("This address is already in your address" " book")]}) class AbstractBillingAddress(AbstractAddress): class Meta: abstract = True # BillingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Billing address") verbose_name_plural = _("Billing addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractPartnerAddress(AbstractAddress): """ A partner can have one or more addresses. This can be useful e.g. when determining US tax which depends on the origin of the shipment. """ partner = models.ForeignKey( 'partner.Partner', on_delete=models.CASCADE, related_name='addresses', verbose_name=_('Partner')) class Meta: abstract = True app_label = 'partner' verbose_name = _("Partner address") verbose_name_plural = _("Partner addresses")
# -*- coding: utf-8 -*- import pytest from django.test import TestCase from django.core import exceptions from oscar.apps.order.models import ShippingAddress from oscar.core.compat import get_user_model from oscar.apps.address import models from oscar.test import factories from tests._site.model_tests_app.models import ( UserAddressModelWithCustomBaseFields, UserAddressModelWithCustomHashFields ) User = get_user_model() class UserAddressModelWithCustomBaseFieldsFactory(factories.UserAddressFactory): class Meta: model = UserAddressModelWithCustomBaseFields class UserAddressModelWithCustomHashFieldsFactory(factories.UserAddressFactory): class Meta: model = UserAddressModelWithCustomHashFields class TestUserAddress(TestCase): def setUp(self): self.country = factories.CountryFactory.build() self.user = factories.UserFactory() def test_uses_title_firstname_and_lastname_in_salutation(self): a = factories.UserAddressFactory.build( country=self.country, title='Dr', first_name='Barry', last_name='Barrington', user=self.user) self.assertEqual("Dr Barry Barrington", a.salutation) def test_strips_whitespace_from_salutation(self): a = factories.UserAddressFactory.build( title='', first_name='', last_name='Barrington', country=self.country, user=self.user) self.assertEqual("Barrington", a.salutation) def test_has_name_property(self): a = factories.UserAddressFactory.build( country=self.country, first_name='Barry', last_name='Barrington', user=self.user) self.assertEqual("Barry Barrington", a.name) def test_has_summary_property(self): c = factories.CountryFactory(name='') a = factories.UserAddressFactory( country=c, title='Dr', first_name='Barry', last_name='Barrington', line1='1 King Road', line4='London', postcode='SW1 9RE') self.assertEqual( "Dr Barry Barrington, 1 King Road, London, SW1 9RE, UNITED KINGDOM", a.summary) def test_summary_includes_country(self): c = factories.CountryFactory.build(name='UNITED KINGDOM') a = factories.UserAddressFactory.build( country=c, title='Dr', first_name='Barry', last_name='Barrington', line1='1 King Road', line4='London', postcode='SW1 9RE', user=self.user) self.assertEqual( "Dr Barry Barrington, 1 King Road, London, SW1 9RE, UNITED KINGDOM", a.summary) def test_hash_value(self): a = factories.UserAddressFactory.build( country=self.country, user=self.user) self.assertEqual(a.generate_hash(), 2668616117) def test_hash_and_summary_values_on_model_with_custom_base_fields(self): a = UserAddressModelWithCustomBaseFieldsFactory.build(country=self.country, user=self.user) self.assertEqual(a.summary, '1 King Road, London') self.assertEqual(a.generate_hash(), 2668616117) def test_hash_and_summary_values_on_model_with_custom_hash_fields(self): a = UserAddressModelWithCustomHashFieldsFactory.build(country=self.country, user=self.user) self.assertEqual(a.summary, 'Dr Barry Barrington, 1 King Road, London, SW1 9RE, UNITED KINGDOM') self.assertEqual(a.generate_hash(), 2153195893) def test_can_be_hashed_including_non_ascii(self): a = factories.UserAddressFactory.build( first_name="\u0141ukasz Smith", last_name='Smith', line1="75 Smith Road", postcode="n4 8ty", country=self.country, user=self.user) hash = a.generate_hash() self.assertTrue(hash is not None) def test_strips_whitespace_in_name_property(self): a = factories.UserAddressFactory.build( first_name='', last_name='Barrington', country=self.country, user=self.user) self.assertEqual("Barrington", a.name) def test_uses_city_as_an_alias_of_line4(self): a = factories.UserAddressFactory.build( line4='London', country=self.country, user=self.user) self.assertEqual('London', a.city) def test_converts_postcode_to_uppercase_when_cleaning(self): address = factories.UserAddressFactory.build( postcode="n4 8ty", country=self.country, user=self.user) address.clean() self.assertEqual("N4 8TY", address.postcode) def test_strips_whitespace_when_cleaning(self): a = factories.UserAddressFactory.build( line1=" 75 Smith Road ", postcode=" n4 8ty", country=self.country, user=self.user) a.clean() self.assertEqual("N4 8TY", a.postcode) self.assertEqual("75 Smith Road", a.line1) def test_active_address_fields_skips_whitespace_only_fields(self): a = factories.UserAddressFactory.build( first_name=' ', last_name='Barrington', line1=' 75 Smith Road ', postcode=' n4 8ty', title='', country=self.country, user=self.user) active_fields = a.active_address_fields() self.assertEqual("Barrington", active_fields[0]) def test_ignores_whitespace_when_hashing(self): a1 = factories.UserAddressFactory.build( first_name='Terry', last_name='Barrington', country=self.country, user=self.user) a1.clean() a2 = factories.UserAddressFactory.build( first_name=' Terry ', last_name=' Barrington', country=self.country, user=self.user) a2.clean() self.assertEqual(a1.generate_hash(), a2.generate_hash()) def test_populate_shipping_address_doesnt_set_id(self): a = factories.UserAddressFactory.build( country=self.country, user=self.user) a.clean() sa = ShippingAddress() a.populate_alternative_model(sa) self.assertIsNone(sa.id) def test_populated_shipping_address_has_same_summary_user_address(self): a = factories.UserAddressFactory.build( country=self.country, user=self.user) a.clean() sa = ShippingAddress() a.populate_alternative_model(sa) self.assertEqual(sa.summary, a.summary) def test_summary_value(self): a = factories.UserAddressFactory.build( country=self.country, user=self.user) self.assertEqual(a.summary, 'Dr Barry Barrington, 1 King Road, London, SW1 9RE, UNITED KINGDOM') def test_summary_is_property(self): a = factories.UserAddressFactory.build( title='', line4='', first_name=" Terry ", last_name='Barrington', line1=" 75 Smith Road ", postcode=" n4 8ty", country=self.country, user=self.user) a.clean() self.assertEqual( "Terry Barrington, 75 Smith Road, N4 8TY, UNITED KINGDOM", a.summary) VALID_POSTCODES = [ ('GB', 'N1 9RT'), ('SK', '991 41'), ('CZ', '612 00'), ('CC', '6799'), ('CY', '8240'), ('MC', '98000'), ('SH', 'STHL 1ZZ'), ('JP', '150-2345'), ('PG', '314'), ('HN', '41202'), ('BN', 'BC3615'), ('TW', '104'), ('TW', '10444'), # It works for small cases as well ('GB', 'sw2 1rw'), ] INVALID_POSTCODES = [ ('GB', 'not-a-postcode'), ('DE', '123b4'), ] @pytest.mark.parametrize('country_value, postcode_value', VALID_POSTCODES) def test_assert_valid_postcode(country_value, postcode_value): country = models.Country(iso_3166_1_a2=country_value) address = models.UserAddress(country=country, postcode=postcode_value) address.clean() @pytest.mark.parametrize('country_value, postcode_value', INVALID_POSTCODES) def test_assert_invalid_postcode(country_value, postcode_value): country = models.Country(iso_3166_1_a2=country_value) address = models.UserAddress(country=country, postcode=postcode_value) with pytest.raises(exceptions.ValidationError): address.clean()
I need integration test for this code import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from phonenumber_field.modelfields import PhoneNumberField from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import UppercaseCharField class AbstractAddress(models.Model): """ Superclass address object This is subclassed and extended to provide models for user, shipping and billing addresses. """ MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) POSTCODE_REQUIRED = 'postcode' in settings.OSCAR_REQUIRED_ADDRESS_FIELDS # Regex for each country. Not listed countries don't use postcodes # Based on http://en.wikipedia.org/wiki/List_of_postal_codes POSTCODES_REGEX = { 'AC': r'^[A-Z]{4}[0-9][A-Z]$', 'AD': r'^AD[0-9]{3}$', 'AF': r'^[0-9]{4}$', 'AI': r'^AI-2640$', 'AL': r'^[0-9]{4}$', 'AM': r'^[0-9]{4}$', 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3})$', 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'AT': r'^[0-9]{4}$', 'AU': r'^[0-9]{4}$', 'AX': r'^[0-9]{5}$', 'AZ': r'^AZ[0-9]{4}$', 'BA': r'^[0-9]{5}$', 'BB': r'^BB[0-9]{5}$', 'BD': r'^[0-9]{4}$', 'BE': r'^[0-9]{4}$', 'BG': r'^[0-9]{4}$', 'BH': r'^[0-9]{3,4}$', 'BL': r'^[0-9]{5}$', 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})', 'BN': r'^[A-Z]{2}[0-9]{4}$', 'BO': r'^[0-9]{4}$', 'BR': r'^[0-9]{5}(-[0-9]{3})?$', 'BT': r'^[0-9]{3}$', 'BY': r'^[0-9]{6}$', 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$', 'CC': r'^[0-9]{4}$', 'CH': r'^[0-9]{4}$', 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$', 'CN': r'^[0-9]{6}$', 'CO': r'^[0-9]{6}$', 'CR': r'^[0-9]{4,5}$', 'CU': r'^[0-9]{5}$', 'CV': r'^[0-9]{4}$', 'CX': r'^[0-9]{4}$', 'CY': r'^[0-9]{4}$', 'CZ': r'^[0-9]{5}$', 'DE': r'^[0-9]{5}$', 'DK': r'^[0-9]{4}$', 'DO': r'^[0-9]{5}$', 'DZ': r'^[0-9]{5}$', 'EC': r'^EC[0-9]{6}$', 'EE': r'^[0-9]{5}$', 'EG': r'^[0-9]{5}$', 'ES': r'^[0-9]{5}$', 'ET': r'^[0-9]{4}$', 'FI': r'^[0-9]{5}$', 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'FM': r'^[0-9]{5}(-[0-9]{4})?$', 'FO': r'^[0-9]{3}$', 'FR': r'^[0-9]{5}$', 'GA': r'^[0-9]{2}.*[0-9]{2}$', 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$', 'GE': r'^[0-9]{4}$', 'GF': r'^[0-9]{5}$', 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2})$', 'GI': r'^GX111AA$', 'GL': r'^[0-9]{4}$', 'GP': r'^[0-9]{5}$', 'GR': r'^[0-9]{5}$', 'GS': r'^SIQQ1ZZ$', 'GT': r'^[0-9]{5}$', 'GU': r'^[0-9]{5}$', 'GW': r'^[0-9]{4}$', 'HM': r'^[0-9]{4}$', 'HN': r'^[0-9]{5}$', 'HR': r'^[0-9]{5}$', 'HT': r'^[0-9]{4}$', 'HU': r'^[0-9]{4}$', 'ID': r'^[0-9]{5}$', 'IL': r'^[0-9]{7}$', 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$', 'IN': r'^[0-9]{6}$', 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'IQ': r'^[0-9]{5}$', 'IR': r'^[0-9]{5}-[0-9]{5}$', 'IS': r'^[0-9]{3}$', 'IT': r'^[0-9]{5}$', 'JE': r'^JE[0-9]{2}[A-Z]{2}$', 'JM': r'^JM[A-Z]{3}[0-9]{2}$', 'JO': r'^[0-9]{5}$', 'JP': r'^[0-9]{3}-?[0-9]{4}$', 'KE': r'^[0-9]{5}$', 'KG': r'^[0-9]{6}$', 'KH': r'^[0-9]{5}$', 'KR': r'^[0-9]{5}$', 'KY': r'^KY[0-9]-[0-9]{4}$', 'KZ': r'^[0-9]{6}$', 'LA': r'^[0-9]{5}$', 'LB': r'^[0-9]{8}$', 'LI': r'^[0-9]{4}$', 'LK': r'^[0-9]{5}$', 'LR': r'^[0-9]{4}$', 'LS': r'^[0-9]{3}$', 'LT': r'^(LT-)?[0-9]{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', 'MZ': r'^[0-9]{4}$', 'NA': r'^[0-9]{5}$', 'NC': r'^[0-9]{5}$', 'NE': r'^[0-9]{4}$', 'NF': r'^[0-9]{4}$', 'NG': r'^[0-9]{6}$', 'NI': r'^[0-9]{5}$', 'NL': r'^[0-9]{4}[A-Z]{2}$', 'NO': r'^[0-9]{4}$', 'NP': r'^[0-9]{5}$', 'NZ': r'^[0-9]{4}$', 'OM': r'^[0-9]{3}$', 'PA': r'^[0-9]{6}$', 'PE': r'^[0-9]{5}$', 'PF': r'^[0-9]{5}$', 'PG': r'^[0-9]{3}$', 'PH': r'^[0-9]{4}$', 'PK': r'^[0-9]{5}$', 'PL': r'^[0-9]{2}-?[0-9]{3}$', 'PM': r'^[0-9]{5}$', 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'PR': r'^[0-9]{5}$', 'PT': r'^[0-9]{4}(-?[0-9]{3})?$', 'PW': r'^[0-9]{5}$', 'PY': r'^[0-9]{4}$', 'RE': r'^[0-9]{5}$', 'RO': r'^[0-9]{6}$', 'RS': r'^[0-9]{5}$', 'RU': r'^[0-9]{6}$', 'SA': r'^[0-9]{5}$', 'SD': r'^[0-9]{5}$', 'SE': r'^[0-9]{5}$', 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$', 'SH': r'^(STHL1ZZ|TDCU1ZZ)$', 'SI': r'^(SI-)?[0-9]{4}$', 'SK': r'^[0-9]{5}$', 'SM': r'^[0-9]{5}$', 'SN': r'^[0-9]{5}$', 'SV': r'^01101$', 'SZ': r'^[A-Z][0-9]{3}$', 'TC': r'^TKCA1ZZ$', 'TD': r'^[0-9]{5}$', 'TH': r'^[0-9]{5}$', 'TJ': r'^[0-9]{6}$', 'TM': r'^[0-9]{6}$', 'TN': r'^[0-9]{4}$', 'TR': r'^[0-9]{5}$', 'TT': r'^[0-9]{6}$', 'TW': r'^([0-9]{3}|[0-9]{5})$', 'UA': r'^[0-9]{5}$', 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'UY': r'^[0-9]{5}$', 'UZ': r'^[0-9]{6}$', 'VA': r'^00120$', 'VC': r'^VC[0-9]{4}', 'VE': r'^[0-9]{4}[A-Z]?$', 'VG': r'^VG[0-9]{4}$', 'VI': r'^[0-9]{5}$', 'VN': r'^[0-9]{6}$', 'WF': r'^[0-9]{5}$', 'XK': r'^[0-9]{5}$', 'YT': r'^[0-9]{5}$', 'ZA': r'^[0-9]{4}$', 'ZM': r'^[0-9]{5}$', } title = models.CharField( pgettext_lazy("Treatment Pronouns for the customer", "Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, blank=True) # We use quite a few lines of an address as they are often quite long and # it's easier to just hide the unnecessary ones than add extra ones. line1 = models.CharField(_("First line of address"), max_length=255) line2 = models.CharField( _("Second line of address"), max_length=255, blank=True) line3 = models.CharField( _("Third line of address"), max_length=255, blank=True) line4 = models.CharField(_("City"), max_length=255, blank=True) state = models.CharField(_("State/County"), max_length=255, blank=True) postcode = UppercaseCharField( _("Post/Zip-code"), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', on_delete=models.CASCADE, verbose_name=_("Country")) #: A field only used for searching addresses - this contains all the #: relevant fields. This is effectively a poor man's Solr text field. search_text = models.TextField( _("Search text - used only for searching addresses"), editable=False) # Fields, used for `summary` property definition and hash generation. base_fields = hash_fields = ['salutation', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode', 'country'] def __str__(self): return self.summary class Meta: abstract = True verbose_name = _('Address') verbose_name_plural = _('Addresses') # Saving def save(self, *args, **kwargs): self._update_search_text() super().save(*args, **kwargs) def clean(self): # Strip all whitespace for field in ['first_name', 'last_name', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode']: if self.__dict__[field]: self.__dict__[field] = self.__dict__[field].strip() # Ensure postcodes are valid for country self.ensure_postcode_is_valid_for_country() def ensure_postcode_is_valid_for_country(self): """ Validate postcode given the country """ if not self.postcode and self.POSTCODE_REQUIRED and self.country_id: country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) if regex: msg = _("Addresses in %(country)s require a valid postcode") \ % {'country': self.country} raise exceptions.ValidationError(msg) if self.postcode and self.country_id: # Ensure postcodes are always uppercase postcode = self.postcode.upper().replace(' ', '') country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) # Validate postcode against regex for the country if available if regex and not re.match(regex, postcode): msg = _("The postcode '%(postcode)s' is not valid " "for %(country)s") \ % {'postcode': self.postcode, 'country': self.country} raise exceptions.ValidationError( {'postcode': [msg]}) def _update_search_text(self): search_fields = filter( bool, [self.first_name, self.last_name, self.line1, self.line2, self.line3, self.line4, self.state, self.postcode, self.country.name]) self.search_text = ' '.join(search_fields) # Properties @property def city(self): # Common alias return self.line4 @property def summary(self): """ Returns a single string summary of the address, separating fields using commas. """ return ", ".join(self.active_address_fields()) @property def salutation(self): """ Name (including title) """ return self.join_fields( ('title', 'first_name', 'last_name'), separator=" ") @property def name(self): return self.join_fields(('first_name', 'last_name'), separator=" ") # Helpers def get_field_values(self, fields): field_values = [] for field in fields: # Title is special case if field == 'title': value = self.get_title_display() elif field == 'country': try: value = self.country.printable_name except exceptions.ObjectDoesNotExist: value = '' elif field == 'salutation': value = self.salutation else: value = getattr(self, field) field_values.append(value) return field_values def get_address_field_values(self, fields): """ Returns set of field values within the salutation and country. """ field_values = [f.strip() for f in self.get_field_values(fields) if f] return field_values def generate_hash(self): """ Returns a hash of the address, based on standard set of fields, listed out in `hash_fields` property. """ field_values = self.get_address_field_values(self.hash_fields) # Python 2 and 3 generates CRC checksum in different ranges, so # in order to generate platform-independent value we apply # `& 0xffffffff` expression. return zlib.crc32(', '.join(field_values).upper().encode('UTF8')) & 0xffffffff def join_fields(self, fields, separator=", "): """ Join a sequence of fields using the specified separator """ field_values = self.get_field_values(fields) return separator.join(filter(bool, field_values)) def populate_alternative_model(self, address_model): """ For populating an address model using the matching fields from this one. This is used to convert a user address to a shipping address as part of the checkout process. """ destination_field_names = [ field.name for field in address_model._meta.fields] for field_name in [field.name for field in self._meta.fields]: if field_name in destination_field_names and field_name != 'id': setattr(address_model, field_name, getattr(self, field_name)) def active_address_fields(self): """ Returns the non-empty components of the address, but merging the title, first_name and last_name into a single line. It uses fields listed out in `base_fields` property. """ return self.get_address_field_values(self.base_fields) class AbstractCountry(models.Model): """ International Organization for Standardization (ISO) 3166-1 Country list. The field names are a bit awkward, but kept for backwards compatibility. pycountry's syntax of alpha2, alpha3, name and official_name seems sane. """ iso_3166_1_a2 = models.CharField( _('ISO 3166-1 alpha-2'), max_length=2, primary_key=True) iso_3166_1_a3 = models.CharField( _('ISO 3166-1 alpha-3'), max_length=3, blank=True) iso_3166_1_numeric = models.CharField( _('ISO 3166-1 numeric'), blank=True, max_length=3) #: The commonly used name; e.g. 'United Kingdom' printable_name = models.CharField(_('Country name'), max_length=128) #: The full official name of a country #: e.g. 'United Kingdom of Great Britain and Northern Ireland' name = models.CharField(_('Official name'), max_length=128) display_order = models.PositiveSmallIntegerField( _("Display order"), default=0, db_index=True, help_text=_('Higher the number, higher the country in the list.')) is_shipping_country = models.BooleanField( _("Is shipping country"), default=False, db_index=True) class Meta: abstract = True app_label = 'address' verbose_name = _('Country') verbose_name_plural = _('Countries') ordering = ('-display_order', 'printable_name',) def __str__(self): return self.printable_name or self.name @property def code(self): """ Shorthand for the ISO 3166 Alpha-2 code """ return self.iso_3166_1_a2 @property def numeric_code(self): """ Shorthand for the ISO 3166 numeric code. iso_3166_1_numeric used to wrongly be a integer field, but has to be padded with leading zeroes. It's since been converted to a char field, but the database might still contain non-padded strings. That's why the padding is kept. """ return "%.03d" % int(self.iso_3166_1_numeric) class AbstractShippingAddress(AbstractAddress): """ A shipping address. A shipping address should not be edited once the order has been placed - it should be read-only after that. NOTE: ShippingAddress is a model of the order app. But moving it there is tricky due to circular import issues that are amplified by get_model/get_class calls pre-Django 1.7 to register receivers. So... TODO: Once Django 1.6 support is dropped, move AbstractBillingAddress and AbstractShippingAddress to the order app, and move PartnerAddress to the partner app. """ phone_number = PhoneNumberField( _("Phone number"), blank=True, help_text=_("In case we need to call you about your order")) notes = models.TextField( blank=True, verbose_name=_('Instructions'), help_text=_("Tell us anything we should know when delivering " "your order.")) class Meta: abstract = True # ShippingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Shipping address") verbose_name_plural = _("Shipping addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractUserAddress(AbstractShippingAddress): """ A user's address. A user can have many of these and together they form an 'address book' of sorts for the user. We use a separate model for shipping and billing (even though there will be some data duplication) because we don't want shipping/billing addresses changed or deleted once an order has been placed. By having a separate model, we allow users the ability to add/edit/delete from their address book without affecting orders already placed. """ user = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='addresses', verbose_name=_("User")) #: Whether this address is the default for shipping is_default_for_shipping = models.BooleanField( _("Default shipping address?"), default=False) #: Whether this address should be the default for billing. is_default_for_billing = models.BooleanField( _("Default billing address?"), default=False) #: We keep track of the number of times an address has been used #: as a shipping address so we can show the most popular ones #: first at the checkout. num_orders_as_shipping_address = models.PositiveIntegerField( _("Number of Orders as Shipping Address"), default=0) #: Same as previous, but for billing address. num_orders_as_billing_address = models.PositiveIntegerField( _("Number of Orders as Billing Address"), default=0) #: A hash is kept to try and avoid duplicate addresses being added #: to the address book. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True, editable=False) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) def save(self, *args, **kwargs): """ Save a hash of the address fields """ # Save a hash of the address fields so we can check whether two # addresses are the same to avoid saving duplicates self.hash = self.generate_hash() # Ensure that each user only has one default shipping address # and billing address self._ensure_defaults_integrity() super().save(*args, **kwargs) def _ensure_defaults_integrity(self): if self.is_default_for_shipping: self.__class__._default_manager\ .filter(user=self.user, is_default_for_shipping=True)\ .update(is_default_for_shipping=False) if self.is_default_for_billing: self.__class__._default_manager\ .filter(user=self.user, is_default_for_billing=True)\ .update(is_default_for_billing=False) class Meta: abstract = True app_label = 'address' verbose_name = _("User address") verbose_name_plural = _("User addresses") ordering = ['-num_orders_as_shipping_address'] unique_together = ('user', 'hash') def validate_unique(self, exclude=None): super().validate_unique(exclude) qs = self.__class__.objects.filter( user=self.user, hash=self.generate_hash()) if self.id: qs = qs.exclude(id=self.id) if qs.exists(): raise exceptions.ValidationError({ '__all__': [_("This address is already in your address" " book")]}) class AbstractBillingAddress(AbstractAddress): class Meta: abstract = True # BillingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Billing address") verbose_name_plural = _("Billing addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractPartnerAddress(AbstractAddress): """ A partner can have one or more addresses. This can be useful e.g. when determining US tax which depends on the origin of the shipment. """ partner = models.ForeignKey( 'partner.Partner', on_delete=models.CASCADE, related_name='addresses', verbose_name=_('Partner')) class Meta: abstract = True app_label = 'partner' verbose_name = _("Partner address") verbose_name_plural = _("Partner addresses")
I need integration test for this code import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from phonenumber_field.modelfields import PhoneNumberField from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import UppercaseCharField class AbstractAddress(models.Model): """ Superclass address object This is subclassed and extended to provide models for user, shipping and billing addresses. """ MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) POSTCODE_REQUIRED = 'postcode' in settings.OSCAR_REQUIRED_ADDRESS_FIELDS # Regex for each country. Not listed countries don't use postcodes # Based on http://en.wikipedia.org/wiki/List_of_postal_codes POSTCODES_REGEX = { 'AC': r'^[A-Z]{4}[0-9][A-Z]$', 'AD': r'^AD[0-9]{3}$', 'AF': r'^[0-9]{4}$', 'AI': r'^AI-2640$', 'AL': r'^[0-9]{4}$', 'AM': r'^[0-9]{4}$', 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3})$', 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'AT': r'^[0-9]{4}$', 'AU': r'^[0-9]{4}$', 'AX': r'^[0-9]{5}$', 'AZ': r'^AZ[0-9]{4}$', 'BA': r'^[0-9]{5}$', 'BB': r'^BB[0-9]{5}$', 'BD': r'^[0-9]{4}$', 'BE': r'^[0-9]{4}$', 'BG': r'^[0-9]{4}$', 'BH': r'^[0-9]{3,4}$', 'BL': r'^[0-9]{5}$', 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})', 'BN': r'^[A-Z]{2}[0-9]{4}$', 'BO': r'^[0-9]{4}$', 'BR': r'^[0-9]{5}(-[0-9]{3})?$', 'BT': r'^[0-9]{3}$', 'BY': r'^[0-9]{6}$', 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$', 'CC': r'^[0-9]{4}$', 'CH': r'^[0-9]{4}$', 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$', 'CN': r'^[0-9]{6}$', 'CO': r'^[0-9]{6}$', 'CR': r'^[0-9]{4,5}$', 'CU': r'^[0-9]{5}$', 'CV': r'^[0-9]{4}$', 'CX': r'^[0-9]{4}$', 'CY': r'^[0-9]{4}$', 'CZ': r'^[0-9]{5}$', 'DE': r'^[0-9]{5}$', 'DK': r'^[0-9]{4}$', 'DO': r'^[0-9]{5}$', 'DZ': r'^[0-9]{5}$', 'EC': r'^EC[0-9]{6}$', 'EE': r'^[0-9]{5}$', 'EG': r'^[0-9]{5}$', 'ES': r'^[0-9]{5}$', 'ET': r'^[0-9]{4}$', 'FI': r'^[0-9]{5}$', 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'FM': r'^[0-9]{5}(-[0-9]{4})?$', 'FO': r'^[0-9]{3}$', 'FR': r'^[0-9]{5}$', 'GA': r'^[0-9]{2}.*[0-9]{2}$', 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$', 'GE': r'^[0-9]{4}$', 'GF': r'^[0-9]{5}$', 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2})$', 'GI': r'^GX111AA$', 'GL': r'^[0-9]{4}$', 'GP': r'^[0-9]{5}$', 'GR': r'^[0-9]{5}$', 'GS': r'^SIQQ1ZZ$', 'GT': r'^[0-9]{5}$', 'GU': r'^[0-9]{5}$', 'GW': r'^[0-9]{4}$', 'HM': r'^[0-9]{4}$', 'HN': r'^[0-9]{5}$', 'HR': r'^[0-9]{5}$', 'HT': r'^[0-9]{4}$', 'HU': r'^[0-9]{4}$', 'ID': r'^[0-9]{5}$', 'IL': r'^[0-9]{7}$', 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$', 'IN': r'^[0-9]{6}$', 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'IQ': r'^[0-9]{5}$', 'IR': r'^[0-9]{5}-[0-9]{5}$', 'IS': r'^[0-9]{3}$', 'IT': r'^[0-9]{5}$', 'JE': r'^JE[0-9]{2}[A-Z]{2}$', 'JM': r'^JM[A-Z]{3}[0-9]{2}$', 'JO': r'^[0-9]{5}$', 'JP': r'^[0-9]{3}-?[0-9]{4}$', 'KE': r'^[0-9]{5}$', 'KG': r'^[0-9]{6}$', 'KH': r'^[0-9]{5}$', 'KR': r'^[0-9]{5}$', 'KY': r'^KY[0-9]-[0-9]{4}$', 'KZ': r'^[0-9]{6}$', 'LA': r'^[0-9]{5}$', 'LB': r'^[0-9]{8}$', 'LI': r'^[0-9]{4}$', 'LK': r'^[0-9]{5}$', 'LR': r'^[0-9]{4}$', 'LS': r'^[0-9]{3}$', 'LT': r'^(LT-)?[0-9]{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', 'MZ': r'^[0-9]{4}$', 'NA': r'^[0-9]{5}$', 'NC': r'^[0-9]{5}$', 'NE': r'^[0-9]{4}$', 'NF': r'^[0-9]{4}$', 'NG': r'^[0-9]{6}$', 'NI': r'^[0-9]{5}$', 'NL': r'^[0-9]{4}[A-Z]{2}$', 'NO': r'^[0-9]{4}$', 'NP': r'^[0-9]{5}$', 'NZ': r'^[0-9]{4}$', 'OM': r'^[0-9]{3}$', 'PA': r'^[0-9]{6}$', 'PE': r'^[0-9]{5}$', 'PF': r'^[0-9]{5}$', 'PG': r'^[0-9]{3}$', 'PH': r'^[0-9]{4}$', 'PK': r'^[0-9]{5}$', 'PL': r'^[0-9]{2}-?[0-9]{3}$', 'PM': r'^[0-9]{5}$', 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'PR': r'^[0-9]{5}$', 'PT': r'^[0-9]{4}(-?[0-9]{3})?$', 'PW': r'^[0-9]{5}$', 'PY': r'^[0-9]{4}$', 'RE': r'^[0-9]{5}$', 'RO': r'^[0-9]{6}$', 'RS': r'^[0-9]{5}$', 'RU': r'^[0-9]{6}$', 'SA': r'^[0-9]{5}$', 'SD': r'^[0-9]{5}$', 'SE': r'^[0-9]{5}$', 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$', 'SH': r'^(STHL1ZZ|TDCU1ZZ)$', 'SI': r'^(SI-)?[0-9]{4}$', 'SK': r'^[0-9]{5}$', 'SM': r'^[0-9]{5}$', 'SN': r'^[0-9]{5}$', 'SV': r'^01101$', 'SZ': r'^[A-Z][0-9]{3}$', 'TC': r'^TKCA1ZZ$', 'TD': r'^[0-9]{5}$', 'TH': r'^[0-9]{5}$', 'TJ': r'^[0-9]{6}$', 'TM': r'^[0-9]{6}$', 'TN': r'^[0-9]{4}$', 'TR': r'^[0-9]{5}$', 'TT': r'^[0-9]{6}$', 'TW': r'^([0-9]{3}|[0-9]{5})$', 'UA': r'^[0-9]{5}$', 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'UY': r'^[0-9]{5}$', 'UZ': r'^[0-9]{6}$', 'VA': r'^00120$', 'VC': r'^VC[0-9]{4}', 'VE': r'^[0-9]{4}[A-Z]?$', 'VG': r'^VG[0-9]{4}$', 'VI': r'^[0-9]{5}$', 'VN': r'^[0-9]{6}$', 'WF': r'^[0-9]{5}$', 'XK': r'^[0-9]{5}$', 'YT': r'^[0-9]{5}$', 'ZA': r'^[0-9]{4}$', 'ZM': r'^[0-9]{5}$', } title = models.CharField( pgettext_lazy("Treatment Pronouns for the customer", "Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, blank=True) # We use quite a few lines of an address as they are often quite long and # it's easier to just hide the unnecessary ones than add extra ones. line1 = models.CharField(_("First line of address"), max_length=255) line2 = models.CharField( _("Second line of address"), max_length=255, blank=True) line3 = models.CharField( _("Third line of address"), max_length=255, blank=True) line4 = models.CharField(_("City"), max_length=255, blank=True) state = models.CharField(_("State/County"), max_length=255, blank=True) postcode = UppercaseCharField( _("Post/Zip-code"), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', on_delete=models.CASCADE, verbose_name=_("Country")) #: A field only used for searching addresses - this contains all the #: relevant fields. This is effectively a poor man's Solr text field. search_text = models.TextField( _("Search text - used only for searching addresses"), editable=False) # Fields, used for `summary` property definition and hash generation. base_fields = hash_fields = ['salutation', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode', 'country'] def __str__(self): return self.summary class Meta: abstract = True verbose_name = _('Address') verbose_name_plural = _('Addresses') # Saving def save(self, *args, **kwargs): self._update_search_text() super().save(*args, **kwargs) def clean(self): # Strip all whitespace for field in ['first_name', 'last_name', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode']: if self.__dict__[field]: self.__dict__[field] = self.__dict__[field].strip() # Ensure postcodes are valid for country self.ensure_postcode_is_valid_for_country() def ensure_postcode_is_valid_for_country(self): """ Validate postcode given the country """ if not self.postcode and self.POSTCODE_REQUIRED and self.country_id: country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) if regex: msg = _("Addresses in %(country)s require a valid postcode") \ % {'country': self.country} raise exceptions.ValidationError(msg) if self.postcode and self.country_id: # Ensure postcodes are always uppercase postcode = self.postcode.upper().replace(' ', '') country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) # Validate postcode against regex for the country if available if regex and not re.match(regex, postcode): msg = _("The postcode '%(postcode)s' is not valid " "for %(country)s") \ % {'postcode': self.postcode, 'country': self.country} raise exceptions.ValidationError( {'postcode': [msg]}) def _update_search_text(self): search_fields = filter( bool, [self.first_name, self.last_name, self.line1, self.line2, self.line3, self.line4, self.state, self.postcode, self.country.name]) self.search_text = ' '.join(search_fields) # Properties @property def city(self): # Common alias return self.line4 @property def summary(self): """ Returns a single string summary of the address, separating fields using commas. """ return ", ".join(self.active_address_fields()) @property def salutation(self): """ Name (including title) """ return self.join_fields( ('title', 'first_name', 'last_name'), separator=" ") @property def name(self): return self.join_fields(('first_name', 'last_name'), separator=" ") # Helpers def get_field_values(self, fields): field_values = [] for field in fields: # Title is special case if field == 'title': value = self.get_title_display() elif field == 'country': try: value = self.country.printable_name except exceptions.ObjectDoesNotExist: value = '' elif field == 'salutation': value = self.salutation else: value = getattr(self, field) field_values.append(value) return field_values def get_address_field_values(self, fields): """ Returns set of field values within the salutation and country. """ field_values = [f.strip() for f in self.get_field_values(fields) if f] return field_values def generate_hash(self): """ Returns a hash of the address, based on standard set of fields, listed out in `hash_fields` property. """ field_values = self.get_address_field_values(self.hash_fields) # Python 2 and 3 generates CRC checksum in different ranges, so # in order to generate platform-independent value we apply # `& 0xffffffff` expression. return zlib.crc32(', '.join(field_values).upper().encode('UTF8')) & 0xffffffff def join_fields(self, fields, separator=", "): """ Join a sequence of fields using the specified separator """ field_values = self.get_field_values(fields) return separator.join(filter(bool, field_values)) def populate_alternative_model(self, address_model): """ For populating an address model using the matching fields from this one. This is used to convert a user address to a shipping address as part of the checkout process. """ destination_field_names = [ field.name for field in address_model._meta.fields] for field_name in [field.name for field in self._meta.fields]: if field_name in destination_field_names and field_name != 'id': setattr(address_model, field_name, getattr(self, field_name)) def active_address_fields(self): """ Returns the non-empty components of the address, but merging the title, first_name and last_name into a single line. It uses fields listed out in `base_fields` property. """ return self.get_address_field_values(self.base_fields) class AbstractCountry(models.Model): """ International Organization for Standardization (ISO) 3166-1 Country list. The field names are a bit awkward, but kept for backwards compatibility. pycountry's syntax of alpha2, alpha3, name and official_name seems sane. """ iso_3166_1_a2 = models.CharField( _('ISO 3166-1 alpha-2'), max_length=2, primary_key=True) iso_3166_1_a3 = models.CharField( _('ISO 3166-1 alpha-3'), max_length=3, blank=True) iso_3166_1_numeric = models.CharField( _('ISO 3166-1 numeric'), blank=True, max_length=3) #: The commonly used name; e.g. 'United Kingdom' printable_name = models.CharField(_('Country name'), max_length=128) #: The full official name of a country #: e.g. 'United Kingdom of Great Britain and Northern Ireland' name = models.CharField(_('Official name'), max_length=128) display_order = models.PositiveSmallIntegerField( _("Display order"), default=0, db_index=True, help_text=_('Higher the number, higher the country in the list.')) is_shipping_country = models.BooleanField( _("Is shipping country"), default=False, db_index=True) class Meta: abstract = True app_label = 'address' verbose_name = _('Country') verbose_name_plural = _('Countries') ordering = ('-display_order', 'printable_name',) def __str__(self): return self.printable_name or self.name @property def code(self): """ Shorthand for the ISO 3166 Alpha-2 code """ return self.iso_3166_1_a2 @property def numeric_code(self): """ Shorthand for the ISO 3166 numeric code. iso_3166_1_numeric used to wrongly be a integer field, but has to be padded with leading zeroes. It's since been converted to a char field, but the database might still contain non-padded strings. That's why the padding is kept. """ return "%.03d" % int(self.iso_3166_1_numeric) class AbstractShippingAddress(AbstractAddress): """ A shipping address. A shipping address should not be edited once the order has been placed - it should be read-only after that. NOTE: ShippingAddress is a model of the order app. But moving it there is tricky due to circular import issues that are amplified by get_model/get_class calls pre-Django 1.7 to register receivers. So... TODO: Once Django 1.6 support is dropped, move AbstractBillingAddress and AbstractShippingAddress to the order app, and move PartnerAddress to the partner app. """ phone_number = PhoneNumberField( _("Phone number"), blank=True, help_text=_("In case we need to call you about your order")) notes = models.TextField( blank=True, verbose_name=_('Instructions'), help_text=_("Tell us anything we should know when delivering " "your order.")) class Meta: abstract = True # ShippingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Shipping address") verbose_name_plural = _("Shipping addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractUserAddress(AbstractShippingAddress): """ A user's address. A user can have many of these and together they form an 'address book' of sorts for the user. We use a separate model for shipping and billing (even though there will be some data duplication) because we don't want shipping/billing addresses changed or deleted once an order has been placed. By having a separate model, we allow users the ability to add/edit/delete from their address book without affecting orders already placed. """ user = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='addresses', verbose_name=_("User")) #: Whether this address is the default for shipping is_default_for_shipping = models.BooleanField( _("Default shipping address?"), default=False) #: Whether this address should be the default for billing. is_default_for_billing = models.BooleanField( _("Default billing address?"), default=False) #: We keep track of the number of times an address has been used #: as a shipping address so we can show the most popular ones #: first at the checkout. num_orders_as_shipping_address = models.PositiveIntegerField( _("Number of Orders as Shipping Address"), default=0) #: Same as previous, but for billing address. num_orders_as_billing_address = models.PositiveIntegerField( _("Number of Orders as Billing Address"), default=0) #: A hash is kept to try and avoid duplicate addresses being added #: to the address book. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True, editable=False) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) def save(self, *args, **kwargs): """ Save a hash of the address fields """ # Save a hash of the address fields so we can check whether two # addresses are the same to avoid saving duplicates self.hash = self.generate_hash() # Ensure that each user only has one default shipping address # and billing address self._ensure_defaults_integrity() super().save(*args, **kwargs) def _ensure_defaults_integrity(self): if self.is_default_for_shipping: self.__class__._default_manager\ .filter(user=self.user, is_default_for_shipping=True)\ .update(is_default_for_shipping=False) if self.is_default_for_billing: self.__class__._default_manager\ .filter(user=self.user, is_default_for_billing=True)\ .update(is_default_for_billing=False) class Meta: abstract = True app_label = 'address' verbose_name = _("User address") verbose_name_plural = _("User addresses") ordering = ['-num_orders_as_shipping_address'] unique_together = ('user', 'hash') def validate_unique(self, exclude=None): super().validate_unique(exclude) qs = self.__class__.objects.filter( user=self.user, hash=self.generate_hash()) if self.id: qs = qs.exclude(id=self.id) if qs.exists(): raise exceptions.ValidationError({ '__all__': [_("This address is already in your address" " book")]}) class AbstractBillingAddress(AbstractAddress): class Meta: abstract = True # BillingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Billing address") verbose_name_plural = _("Billing addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractPartnerAddress(AbstractAddress): """ A partner can have one or more addresses. This can be useful e.g. when determining US tax which depends on the origin of the shipment. """ partner = models.ForeignKey( 'partner.Partner', on_delete=models.CASCADE, related_name='addresses', verbose_name=_('Partner')) class Meta: abstract = True app_label = 'partner' verbose_name = _("Partner address") verbose_name_plural = _("Partner addresses")
from datetime import datetime, date from django.test import TestCase from django.core.exceptions import ValidationError from django.core.files.uploadedfile import SimpleUploadedFile from oscar.test import factories class TestBooleanAttributes(TestCase): def setUp(self): self.attr = factories.ProductAttributeFactory(type="boolean") def test_validate_boolean_values(self): self.assertIsNone(self.attr.validate_value(True)) def test_validate_invalid_boolean_values(self): with self.assertRaises(ValidationError): self.attr.validate_value(1) class TestMultiOptionAttributes(TestCase): def setUp(self): self.option_group = factories.AttributeOptionGroupFactory() self.attr = factories.ProductAttributeFactory( type='multi_option', name='Sizes', code='sizes', option_group=self.option_group, ) # Add some options to the group self.options = factories.AttributeOptionFactory.create_batch( 3, group=self.option_group) def test_validate_multi_option_values(self): self.assertIsNone(self.attr.validate_value([ self.options[0], self.options[1]])) def test_validate_invalid_multi_option_values(self): with self.assertRaises(ValidationError): # value must be an iterable self.attr.validate_value('foobar') with self.assertRaises(ValidationError): # Items must all be AttributeOption objects self.attr.validate_value([self.options[0], 'notanOption']) def test_save_multi_option_value(self): product = factories.ProductFactory() # We'll save two out of the three available options self.attr.save_value(product, [self.options[0], self.options[2]]) product.refresh_from_db() self.assertEqual(list(product.attr.sizes), [self.options[0], self.options[2]]) def test_delete_multi_option_value(self): product = factories.ProductFactory() self.attr.save_value(product, [self.options[0], self.options[1]]) # Now delete these values self.attr.save_value(product, None) product.refresh_from_db() self.assertFalse(hasattr(product.attr, 'sizes')) def test_multi_option_value_as_text(self): product = factories.ProductFactory() self.attr.save_value(product, self.options) attr_val = product.attribute_values.get(attribute=self.attr) self.assertEqual(attr_val.value_as_text, ", ".join(o.option for o in self.options)) class TestDatetimeAttributes(TestCase): def setUp(self): self.attr = factories.ProductAttributeFactory(type="datetime") def test_validate_datetime_values(self): self.assertIsNone(self.attr.validate_value(datetime.now())) def test_validate_invalid_datetime_values(self): with self.assertRaises(ValidationError): self.attr.validate_value(1) class TestDateAttributes(TestCase): def setUp(self): self.attr = factories.ProductAttributeFactory(type="date") def test_validate_datetime_values(self): self.assertIsNone(self.attr.validate_value(datetime.now())) def test_validate_date_values(self): self.assertIsNone(self.attr.validate_value(date.today())) def test_validate_invalid_date_values(self): with self.assertRaises(ValidationError): self.attr.validate_value(1) class TestIntegerAttributes(TestCase): def setUp(self): self.attr = factories.ProductAttributeFactory(type="integer") def test_validate_integer_values(self): self.assertIsNone(self.attr.validate_value(1)) def test_validate_str_integer_values(self): self.assertIsNone(self.attr.validate_value('1')) def test_validate_invalid_integer_values(self): with self.assertRaises(ValidationError): self.attr.validate_value('notanInteger') class TestFloatAttributes(TestCase): def setUp(self): self.attr = factories.ProductAttributeFactory(type="float") def test_validate_integer_values(self): self.assertIsNone(self.attr.validate_value(1)) def test_validate_float_values(self): self.assertIsNone(self.attr.validate_value(1.2)) def test_validate_str_float_values(self): self.assertIsNone(self.attr.validate_value('1.2')) def test_validate_invalid_float_values(self): with self.assertRaises(ValidationError): self.attr.validate_value('notaFloat') class TestTextAttributes(TestCase): def setUp(self): self.attr = factories.ProductAttributeFactory(type="text") def test_validate_string_and_unicode_values(self): self.assertIsNone(self.attr.validate_value('String')) def test_validate_invalid_float_values(self): with self.assertRaises(ValidationError): self.attr.validate_value(1) class TestFileAttributes(TestCase): def setUp(self): self.attr = factories.ProductAttributeFactory(type="file") def test_validate_file_values(self): file_field = SimpleUploadedFile('test_file.txt', b'Test') self.assertIsNone(self.attr.validate_value(file_field))
I need integration test for this code import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from phonenumber_field.modelfields import PhoneNumberField from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import UppercaseCharField class AbstractAddress(models.Model): """ Superclass address object This is subclassed and extended to provide models for user, shipping and billing addresses. """ MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) POSTCODE_REQUIRED = 'postcode' in settings.OSCAR_REQUIRED_ADDRESS_FIELDS # Regex for each country. Not listed countries don't use postcodes # Based on http://en.wikipedia.org/wiki/List_of_postal_codes POSTCODES_REGEX = { 'AC': r'^[A-Z]{4}[0-9][A-Z]$', 'AD': r'^AD[0-9]{3}$', 'AF': r'^[0-9]{4}$', 'AI': r'^AI-2640$', 'AL': r'^[0-9]{4}$', 'AM': r'^[0-9]{4}$', 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3})$', 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'AT': r'^[0-9]{4}$', 'AU': r'^[0-9]{4}$', 'AX': r'^[0-9]{5}$', 'AZ': r'^AZ[0-9]{4}$', 'BA': r'^[0-9]{5}$', 'BB': r'^BB[0-9]{5}$', 'BD': r'^[0-9]{4}$', 'BE': r'^[0-9]{4}$', 'BG': r'^[0-9]{4}$', 'BH': r'^[0-9]{3,4}$', 'BL': r'^[0-9]{5}$', 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})', 'BN': r'^[A-Z]{2}[0-9]{4}$', 'BO': r'^[0-9]{4}$', 'BR': r'^[0-9]{5}(-[0-9]{3})?$', 'BT': r'^[0-9]{3}$', 'BY': r'^[0-9]{6}$', 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$', 'CC': r'^[0-9]{4}$', 'CH': r'^[0-9]{4}$', 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$', 'CN': r'^[0-9]{6}$', 'CO': r'^[0-9]{6}$', 'CR': r'^[0-9]{4,5}$', 'CU': r'^[0-9]{5}$', 'CV': r'^[0-9]{4}$', 'CX': r'^[0-9]{4}$', 'CY': r'^[0-9]{4}$', 'CZ': r'^[0-9]{5}$', 'DE': r'^[0-9]{5}$', 'DK': r'^[0-9]{4}$', 'DO': r'^[0-9]{5}$', 'DZ': r'^[0-9]{5}$', 'EC': r'^EC[0-9]{6}$', 'EE': r'^[0-9]{5}$', 'EG': r'^[0-9]{5}$', 'ES': r'^[0-9]{5}$', 'ET': r'^[0-9]{4}$', 'FI': r'^[0-9]{5}$', 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'FM': r'^[0-9]{5}(-[0-9]{4})?$', 'FO': r'^[0-9]{3}$', 'FR': r'^[0-9]{5}$', 'GA': r'^[0-9]{2}.*[0-9]{2}$', 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$', 'GE': r'^[0-9]{4}$', 'GF': r'^[0-9]{5}$', 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2})$', 'GI': r'^GX111AA$', 'GL': r'^[0-9]{4}$', 'GP': r'^[0-9]{5}$', 'GR': r'^[0-9]{5}$', 'GS': r'^SIQQ1ZZ$', 'GT': r'^[0-9]{5}$', 'GU': r'^[0-9]{5}$', 'GW': r'^[0-9]{4}$', 'HM': r'^[0-9]{4}$', 'HN': r'^[0-9]{5}$', 'HR': r'^[0-9]{5}$', 'HT': r'^[0-9]{4}$', 'HU': r'^[0-9]{4}$', 'ID': r'^[0-9]{5}$', 'IL': r'^[0-9]{7}$', 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$', 'IN': r'^[0-9]{6}$', 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'IQ': r'^[0-9]{5}$', 'IR': r'^[0-9]{5}-[0-9]{5}$', 'IS': r'^[0-9]{3}$', 'IT': r'^[0-9]{5}$', 'JE': r'^JE[0-9]{2}[A-Z]{2}$', 'JM': r'^JM[A-Z]{3}[0-9]{2}$', 'JO': r'^[0-9]{5}$', 'JP': r'^[0-9]{3}-?[0-9]{4}$', 'KE': r'^[0-9]{5}$', 'KG': r'^[0-9]{6}$', 'KH': r'^[0-9]{5}$', 'KR': r'^[0-9]{5}$', 'KY': r'^KY[0-9]-[0-9]{4}$', 'KZ': r'^[0-9]{6}$', 'LA': r'^[0-9]{5}$', 'LB': r'^[0-9]{8}$', 'LI': r'^[0-9]{4}$', 'LK': r'^[0-9]{5}$', 'LR': r'^[0-9]{4}$', 'LS': r'^[0-9]{3}$', 'LT': r'^(LT-)?[0-9]{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', 'MZ': r'^[0-9]{4}$', 'NA': r'^[0-9]{5}$', 'NC': r'^[0-9]{5}$', 'NE': r'^[0-9]{4}$', 'NF': r'^[0-9]{4}$', 'NG': r'^[0-9]{6}$', 'NI': r'^[0-9]{5}$', 'NL': r'^[0-9]{4}[A-Z]{2}$', 'NO': r'^[0-9]{4}$', 'NP': r'^[0-9]{5}$', 'NZ': r'^[0-9]{4}$', 'OM': r'^[0-9]{3}$', 'PA': r'^[0-9]{6}$', 'PE': r'^[0-9]{5}$', 'PF': r'^[0-9]{5}$', 'PG': r'^[0-9]{3}$', 'PH': r'^[0-9]{4}$', 'PK': r'^[0-9]{5}$', 'PL': r'^[0-9]{2}-?[0-9]{3}$', 'PM': r'^[0-9]{5}$', 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'PR': r'^[0-9]{5}$', 'PT': r'^[0-9]{4}(-?[0-9]{3})?$', 'PW': r'^[0-9]{5}$', 'PY': r'^[0-9]{4}$', 'RE': r'^[0-9]{5}$', 'RO': r'^[0-9]{6}$', 'RS': r'^[0-9]{5}$', 'RU': r'^[0-9]{6}$', 'SA': r'^[0-9]{5}$', 'SD': r'^[0-9]{5}$', 'SE': r'^[0-9]{5}$', 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$', 'SH': r'^(STHL1ZZ|TDCU1ZZ)$', 'SI': r'^(SI-)?[0-9]{4}$', 'SK': r'^[0-9]{5}$', 'SM': r'^[0-9]{5}$', 'SN': r'^[0-9]{5}$', 'SV': r'^01101$', 'SZ': r'^[A-Z][0-9]{3}$', 'TC': r'^TKCA1ZZ$', 'TD': r'^[0-9]{5}$', 'TH': r'^[0-9]{5}$', 'TJ': r'^[0-9]{6}$', 'TM': r'^[0-9]{6}$', 'TN': r'^[0-9]{4}$', 'TR': r'^[0-9]{5}$', 'TT': r'^[0-9]{6}$', 'TW': r'^([0-9]{3}|[0-9]{5})$', 'UA': r'^[0-9]{5}$', 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'UY': r'^[0-9]{5}$', 'UZ': r'^[0-9]{6}$', 'VA': r'^00120$', 'VC': r'^VC[0-9]{4}', 'VE': r'^[0-9]{4}[A-Z]?$', 'VG': r'^VG[0-9]{4}$', 'VI': r'^[0-9]{5}$', 'VN': r'^[0-9]{6}$', 'WF': r'^[0-9]{5}$', 'XK': r'^[0-9]{5}$', 'YT': r'^[0-9]{5}$', 'ZA': r'^[0-9]{4}$', 'ZM': r'^[0-9]{5}$', } title = models.CharField( pgettext_lazy("Treatment Pronouns for the customer", "Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, blank=True) # We use quite a few lines of an address as they are often quite long and # it's easier to just hide the unnecessary ones than add extra ones. line1 = models.CharField(_("First line of address"), max_length=255) line2 = models.CharField( _("Second line of address"), max_length=255, blank=True) line3 = models.CharField( _("Third line of address"), max_length=255, blank=True) line4 = models.CharField(_("City"), max_length=255, blank=True) state = models.CharField(_("State/County"), max_length=255, blank=True) postcode = UppercaseCharField( _("Post/Zip-code"), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', on_delete=models.CASCADE, verbose_name=_("Country")) #: A field only used for searching addresses - this contains all the #: relevant fields. This is effectively a poor man's Solr text field. search_text = models.TextField( _("Search text - used only for searching addresses"), editable=False) # Fields, used for `summary` property definition and hash generation. base_fields = hash_fields = ['salutation', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode', 'country'] def __str__(self): return self.summary class Meta: abstract = True verbose_name = _('Address') verbose_name_plural = _('Addresses') # Saving def save(self, *args, **kwargs): self._update_search_text() super().save(*args, **kwargs) def clean(self): # Strip all whitespace for field in ['first_name', 'last_name', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode']: if self.__dict__[field]: self.__dict__[field] = self.__dict__[field].strip() # Ensure postcodes are valid for country self.ensure_postcode_is_valid_for_country() def ensure_postcode_is_valid_for_country(self): """ Validate postcode given the country """ if not self.postcode and self.POSTCODE_REQUIRED and self.country_id: country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) if regex: msg = _("Addresses in %(country)s require a valid postcode") \ % {'country': self.country} raise exceptions.ValidationError(msg) if self.postcode and self.country_id: # Ensure postcodes are always uppercase postcode = self.postcode.upper().replace(' ', '') country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) # Validate postcode against regex for the country if available if regex and not re.match(regex, postcode): msg = _("The postcode '%(postcode)s' is not valid " "for %(country)s") \ % {'postcode': self.postcode, 'country': self.country} raise exceptions.ValidationError( {'postcode': [msg]}) def _update_search_text(self): search_fields = filter( bool, [self.first_name, self.last_name, self.line1, self.line2, self.line3, self.line4, self.state, self.postcode, self.country.name]) self.search_text = ' '.join(search_fields) # Properties @property def city(self): # Common alias return self.line4 @property def summary(self): """ Returns a single string summary of the address, separating fields using commas. """ return ", ".join(self.active_address_fields()) @property def salutation(self): """ Name (including title) """ return self.join_fields( ('title', 'first_name', 'last_name'), separator=" ") @property def name(self): return self.join_fields(('first_name', 'last_name'), separator=" ") # Helpers def get_field_values(self, fields): field_values = [] for field in fields: # Title is special case if field == 'title': value = self.get_title_display() elif field == 'country': try: value = self.country.printable_name except exceptions.ObjectDoesNotExist: value = '' elif field == 'salutation': value = self.salutation else: value = getattr(self, field) field_values.append(value) return field_values def get_address_field_values(self, fields): """ Returns set of field values within the salutation and country. """ field_values = [f.strip() for f in self.get_field_values(fields) if f] return field_values def generate_hash(self): """ Returns a hash of the address, based on standard set of fields, listed out in `hash_fields` property. """ field_values = self.get_address_field_values(self.hash_fields) # Python 2 and 3 generates CRC checksum in different ranges, so # in order to generate platform-independent value we apply # `& 0xffffffff` expression. return zlib.crc32(', '.join(field_values).upper().encode('UTF8')) & 0xffffffff def join_fields(self, fields, separator=", "): """ Join a sequence of fields using the specified separator """ field_values = self.get_field_values(fields) return separator.join(filter(bool, field_values)) def populate_alternative_model(self, address_model): """ For populating an address model using the matching fields from this one. This is used to convert a user address to a shipping address as part of the checkout process. """ destination_field_names = [ field.name for field in address_model._meta.fields] for field_name in [field.name for field in self._meta.fields]: if field_name in destination_field_names and field_name != 'id': setattr(address_model, field_name, getattr(self, field_name)) def active_address_fields(self): """ Returns the non-empty components of the address, but merging the title, first_name and last_name into a single line. It uses fields listed out in `base_fields` property. """ return self.get_address_field_values(self.base_fields) class AbstractCountry(models.Model): """ International Organization for Standardization (ISO) 3166-1 Country list. The field names are a bit awkward, but kept for backwards compatibility. pycountry's syntax of alpha2, alpha3, name and official_name seems sane. """ iso_3166_1_a2 = models.CharField( _('ISO 3166-1 alpha-2'), max_length=2, primary_key=True) iso_3166_1_a3 = models.CharField( _('ISO 3166-1 alpha-3'), max_length=3, blank=True) iso_3166_1_numeric = models.CharField( _('ISO 3166-1 numeric'), blank=True, max_length=3) #: The commonly used name; e.g. 'United Kingdom' printable_name = models.CharField(_('Country name'), max_length=128) #: The full official name of a country #: e.g. 'United Kingdom of Great Britain and Northern Ireland' name = models.CharField(_('Official name'), max_length=128) display_order = models.PositiveSmallIntegerField( _("Display order"), default=0, db_index=True, help_text=_('Higher the number, higher the country in the list.')) is_shipping_country = models.BooleanField( _("Is shipping country"), default=False, db_index=True) class Meta: abstract = True app_label = 'address' verbose_name = _('Country') verbose_name_plural = _('Countries') ordering = ('-display_order', 'printable_name',) def __str__(self): return self.printable_name or self.name @property def code(self): """ Shorthand for the ISO 3166 Alpha-2 code """ return self.iso_3166_1_a2 @property def numeric_code(self): """ Shorthand for the ISO 3166 numeric code. iso_3166_1_numeric used to wrongly be a integer field, but has to be padded with leading zeroes. It's since been converted to a char field, but the database might still contain non-padded strings. That's why the padding is kept. """ return "%.03d" % int(self.iso_3166_1_numeric) class AbstractShippingAddress(AbstractAddress): """ A shipping address. A shipping address should not be edited once the order has been placed - it should be read-only after that. NOTE: ShippingAddress is a model of the order app. But moving it there is tricky due to circular import issues that are amplified by get_model/get_class calls pre-Django 1.7 to register receivers. So... TODO: Once Django 1.6 support is dropped, move AbstractBillingAddress and AbstractShippingAddress to the order app, and move PartnerAddress to the partner app. """ phone_number = PhoneNumberField( _("Phone number"), blank=True, help_text=_("In case we need to call you about your order")) notes = models.TextField( blank=True, verbose_name=_('Instructions'), help_text=_("Tell us anything we should know when delivering " "your order.")) class Meta: abstract = True # ShippingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Shipping address") verbose_name_plural = _("Shipping addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractUserAddress(AbstractShippingAddress): """ A user's address. A user can have many of these and together they form an 'address book' of sorts for the user. We use a separate model for shipping and billing (even though there will be some data duplication) because we don't want shipping/billing addresses changed or deleted once an order has been placed. By having a separate model, we allow users the ability to add/edit/delete from their address book without affecting orders already placed. """ user = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='addresses', verbose_name=_("User")) #: Whether this address is the default for shipping is_default_for_shipping = models.BooleanField( _("Default shipping address?"), default=False) #: Whether this address should be the default for billing. is_default_for_billing = models.BooleanField( _("Default billing address?"), default=False) #: We keep track of the number of times an address has been used #: as a shipping address so we can show the most popular ones #: first at the checkout. num_orders_as_shipping_address = models.PositiveIntegerField( _("Number of Orders as Shipping Address"), default=0) #: Same as previous, but for billing address. num_orders_as_billing_address = models.PositiveIntegerField( _("Number of Orders as Billing Address"), default=0) #: A hash is kept to try and avoid duplicate addresses being added #: to the address book. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True, editable=False) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) def save(self, *args, **kwargs): """ Save a hash of the address fields """ # Save a hash of the address fields so we can check whether two # addresses are the same to avoid saving duplicates self.hash = self.generate_hash() # Ensure that each user only has one default shipping address # and billing address self._ensure_defaults_integrity() super().save(*args, **kwargs) def _ensure_defaults_integrity(self): if self.is_default_for_shipping: self.__class__._default_manager\ .filter(user=self.user, is_default_for_shipping=True)\ .update(is_default_for_shipping=False) if self.is_default_for_billing: self.__class__._default_manager\ .filter(user=self.user, is_default_for_billing=True)\ .update(is_default_for_billing=False) class Meta: abstract = True app_label = 'address' verbose_name = _("User address") verbose_name_plural = _("User addresses") ordering = ['-num_orders_as_shipping_address'] unique_together = ('user', 'hash') def validate_unique(self, exclude=None): super().validate_unique(exclude) qs = self.__class__.objects.filter( user=self.user, hash=self.generate_hash()) if self.id: qs = qs.exclude(id=self.id) if qs.exists(): raise exceptions.ValidationError({ '__all__': [_("This address is already in your address" " book")]}) class AbstractBillingAddress(AbstractAddress): class Meta: abstract = True # BillingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Billing address") verbose_name_plural = _("Billing addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractPartnerAddress(AbstractAddress): """ A partner can have one or more addresses. This can be useful e.g. when determining US tax which depends on the origin of the shipment. """ partner = models.ForeignKey( 'partner.Partner', on_delete=models.CASCADE, related_name='addresses', verbose_name=_('Partner')) class Meta: abstract = True app_label = 'partner' verbose_name = _("Partner address") verbose_name_plural = _("Partner addresses")
# -*- coding: utf-8 -*- from django.core.cache import cache from django.test import TestCase from django.test.utils import override_settings from oscar.apps.catalogue.models import Category from oscar.apps.catalogue.categories import create_from_breadcrumbs from oscar.templatetags.category_tags import get_annotated_list class TestCategory(TestCase): def setUp(self): self.products = Category.add_root(name="Pröducts") self.books = self.products.add_child(name="Bücher") def tearDown(self): cache.clear() def test_includes_parents_name_in_full_name(self): self.assertTrue(self.products.name in self.books.full_name) def test_has_children_method(self): self.assertTrue(self.products.has_children()) def test_slugs_were_autogenerated(self): self.assertTrue(self.products.slug) self.assertTrue(self.books.slug) def test_supplied_slug_is_not_altered(self): more_books = self.products.add_child( name=self.books.name, slug=self.books.slug) self.assertEqual(more_books.slug, self.books.slug) @override_settings(OSCAR_SLUG_ALLOW_UNICODE=True) def test_unicode_slug(self): root_category = Category.add_root(name="Vins français") child_category = root_category.add_child(name="Château d'Yquem") self.assertEqual(root_category.slug, 'vins-français') self.assertEqual( root_category.get_absolute_url(), '/catalogue/category/vins-fran%C3%A7ais_{}/'.format(root_category.pk) ) self.assertEqual(child_category.slug, 'château-dyquem') self.assertEqual( child_category.get_absolute_url(), '/catalogue/category/vins-fran%C3%A7ais/ch%C3%A2teau-dyquem_{}/'.format(child_category.pk) ) @override_settings(OSCAR_SLUG_ALLOW_UNICODE=True) def test_url_caching(self): category = self.products.add_child(name="Fromages français") absolute_url = category.get_absolute_url() url = cache.get(category.get_url_cache_key()) self.assertEqual(url, '/catalogue/category/products/fromages-fran%C3%A7ais_{}/'.format(category.pk)) self.assertEqual(absolute_url, '/catalogue/category/products/fromages-fran%C3%A7ais_{}/'.format(category.pk)) class TestMovingACategory(TestCase): def setUp(self): breadcrumbs = ( 'Books > Fiction > Horror > Teen', 'Books > Fiction > Horror > Gothic', 'Books > Fiction > Comedy', 'Books > Non-fiction > Biography', 'Books > Non-fiction > Programming', 'Books > Children', ) for trail in breadcrumbs: create_from_breadcrumbs(trail) horror = Category.objects.get(name="Horror") programming = Category.objects.get(name="Programming") horror.move(programming) # Reload horror instance to pick up changes self.horror = Category.objects.get(name="Horror") def test_updates_instance_name(self): self.assertEqual('Books > Non-fiction > Horror', self.horror.full_name) def test_updates_subtree_names(self): teen = Category.objects.get(name="Teen") self.assertEqual('Books > Non-fiction > Horror > Teen', teen.full_name) gothic = Category.objects.get(name="Gothic") self.assertEqual('Books > Non-fiction > Horror > Gothic', gothic.full_name) class TestCategoryFactory(TestCase): def test_can_create_single_level_category(self): trail = 'Books' category = create_from_breadcrumbs(trail) self.assertIsNotNone(category) self.assertEqual(category.name, 'Books') self.assertEqual(category.slug, 'books') def test_can_create_parent_and_child_categories(self): trail = 'Books > Science-Fiction' category = create_from_breadcrumbs(trail) self.assertIsNotNone(category) self.assertEqual(category.name, 'Science-Fiction') self.assertEqual(category.get_depth(), 2) self.assertEqual(category.get_parent().name, 'Books') self.assertEqual(2, Category.objects.count()) self.assertEqual(category.full_slug, 'books/science-fiction') def test_can_create_multiple_categories(self): trail = 'Books > Science-Fiction > Star Trek' create_from_breadcrumbs(trail) trail = 'Books > Factual > Popular Science' category = create_from_breadcrumbs(trail) self.assertIsNotNone(category) self.assertEqual(category.name, 'Popular Science') self.assertEqual(category.get_depth(), 3) self.assertEqual(category.get_parent().name, 'Factual') self.assertEqual(5, Category.objects.count()) self.assertEqual(category.full_slug, 'books/factual/popular-science', ) def test_can_use_alternative_separator(self): trail = 'Food|Cheese|Blue' create_from_breadcrumbs(trail, separator='|') self.assertEqual(3, len(Category.objects.all())) def test_updating_subtree_slugs_when_moving_category_to_new_parent(self): trail = 'A > B > C' create_from_breadcrumbs(trail) trail = 'A > B > D' create_from_breadcrumbs(trail) trail = 'A > E > F' create_from_breadcrumbs(trail) trail = 'A > E > G' create_from_breadcrumbs(trail) trail = 'T' target = create_from_breadcrumbs(trail) category = Category.objects.get(name='A') category.move(target, pos='first-child') c1 = Category.objects.get(name='A') self.assertEqual(c1.full_slug, 't/a') self.assertEqual(c1.full_name, 'T > A') child = Category.objects.get(name='F') self.assertEqual(child.full_slug, 't/a/e/f') self.assertEqual(child.full_name, 'T > A > E > F') child = Category.objects.get(name='D') self.assertEqual(child.full_slug, 't/a/b/d') self.assertEqual(child.full_name, 'T > A > B > D') def test_updating_subtree_when_moving_category_to_new_sibling(self): trail = 'A > B > C' create_from_breadcrumbs(trail) trail = 'A > B > D' create_from_breadcrumbs(trail) trail = 'A > E > F' create_from_breadcrumbs(trail) trail = 'A > E > G' create_from_breadcrumbs(trail) category = Category.objects.get(name='E') target = Category.objects.get(name='A') category.move(target, pos='right') child = Category.objects.get(name='E') self.assertEqual(child.full_slug, 'e') self.assertEqual(child.full_name, 'E') child = Category.objects.get(name='F') self.assertEqual(child.full_slug, 'e/f') self.assertEqual(child.full_name, 'E > F') class TestCategoryTemplateTags(TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.template = """ {% if tree_categories %} <ul> {% for tree_category, info in tree_categories %} <li> {% if tree_category.pk == category.pk %} <strong>{{ tree_category.name }}</strong> {% else %} <a href="{{ tree_category.get_absolute_url }}"> {{ tree_category.name }}</a> {% endif %} {% if info.has_children %}<ul>{% else %}</li>{% endif %} {% for n in info.num_to_close %} </ul></li> {% endfor %} {% endfor %} </ul> {% endif %} """ def setUp(self): breadcrumbs = ( 'Books > Fiction > Horror > Teen', 'Books > Fiction > Horror > Gothic', 'Books > Fiction > Comedy', 'Books > Non-fiction > Biography', 'Books > Non-fiction > Programming', 'Books > Children', ) for trail in breadcrumbs: create_from_breadcrumbs(trail) def get_category_names(self, depth=None, parent=None): """ For the tests, we are only interested in the category names returned from the template tag. This helper calls the template tag and returns a list of the included categories. """ annotated_list = get_annotated_list(depth, parent) names = [category.name for category, __ in annotated_list] names_set = set(names) # We return a set to ease testing, but need to be sure we're not # losing any duplicates through that conversion. self.assertEqual(len(names_set), len(names)) return names_set def test_all_categories(self): expected_categories = { 'Books', 'Fiction', 'Horror', 'Teen', 'Gothic', 'Comedy', 'Non-fiction', 'Biography', 'Programming', 'Children'} actual_categories = self.get_category_names() self.assertEqual(expected_categories, actual_categories) def test_categories_depth(self): expected_categories = {'Books'} actual_categories = self.get_category_names(depth=1) self.assertEqual(expected_categories, actual_categories) def test_categories_parent(self): parent = Category.objects.get(name="Fiction") actual_categories = self.get_category_names(parent=parent) expected_categories = {'Horror', 'Teen', 'Gothic', 'Comedy'} self.assertEqual(expected_categories, actual_categories) def test_categories_depth_parent(self): parent = Category.objects.get(name="Fiction") actual_categories = self.get_category_names(depth=1, parent=parent) expected_categories = {'Horror', 'Comedy'} self.assertEqual(expected_categories, actual_categories)
I need integration test for this code import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from phonenumber_field.modelfields import PhoneNumberField from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import UppercaseCharField class AbstractAddress(models.Model): """ Superclass address object This is subclassed and extended to provide models for user, shipping and billing addresses. """ MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) POSTCODE_REQUIRED = 'postcode' in settings.OSCAR_REQUIRED_ADDRESS_FIELDS # Regex for each country. Not listed countries don't use postcodes # Based on http://en.wikipedia.org/wiki/List_of_postal_codes POSTCODES_REGEX = { 'AC': r'^[A-Z]{4}[0-9][A-Z]$', 'AD': r'^AD[0-9]{3}$', 'AF': r'^[0-9]{4}$', 'AI': r'^AI-2640$', 'AL': r'^[0-9]{4}$', 'AM': r'^[0-9]{4}$', 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3})$', 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'AT': r'^[0-9]{4}$', 'AU': r'^[0-9]{4}$', 'AX': r'^[0-9]{5}$', 'AZ': r'^AZ[0-9]{4}$', 'BA': r'^[0-9]{5}$', 'BB': r'^BB[0-9]{5}$', 'BD': r'^[0-9]{4}$', 'BE': r'^[0-9]{4}$', 'BG': r'^[0-9]{4}$', 'BH': r'^[0-9]{3,4}$', 'BL': r'^[0-9]{5}$', 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})', 'BN': r'^[A-Z]{2}[0-9]{4}$', 'BO': r'^[0-9]{4}$', 'BR': r'^[0-9]{5}(-[0-9]{3})?$', 'BT': r'^[0-9]{3}$', 'BY': r'^[0-9]{6}$', 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$', 'CC': r'^[0-9]{4}$', 'CH': r'^[0-9]{4}$', 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$', 'CN': r'^[0-9]{6}$', 'CO': r'^[0-9]{6}$', 'CR': r'^[0-9]{4,5}$', 'CU': r'^[0-9]{5}$', 'CV': r'^[0-9]{4}$', 'CX': r'^[0-9]{4}$', 'CY': r'^[0-9]{4}$', 'CZ': r'^[0-9]{5}$', 'DE': r'^[0-9]{5}$', 'DK': r'^[0-9]{4}$', 'DO': r'^[0-9]{5}$', 'DZ': r'^[0-9]{5}$', 'EC': r'^EC[0-9]{6}$', 'EE': r'^[0-9]{5}$', 'EG': r'^[0-9]{5}$', 'ES': r'^[0-9]{5}$', 'ET': r'^[0-9]{4}$', 'FI': r'^[0-9]{5}$', 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'FM': r'^[0-9]{5}(-[0-9]{4})?$', 'FO': r'^[0-9]{3}$', 'FR': r'^[0-9]{5}$', 'GA': r'^[0-9]{2}.*[0-9]{2}$', 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$', 'GE': r'^[0-9]{4}$', 'GF': r'^[0-9]{5}$', 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2})$', 'GI': r'^GX111AA$', 'GL': r'^[0-9]{4}$', 'GP': r'^[0-9]{5}$', 'GR': r'^[0-9]{5}$', 'GS': r'^SIQQ1ZZ$', 'GT': r'^[0-9]{5}$', 'GU': r'^[0-9]{5}$', 'GW': r'^[0-9]{4}$', 'HM': r'^[0-9]{4}$', 'HN': r'^[0-9]{5}$', 'HR': r'^[0-9]{5}$', 'HT': r'^[0-9]{4}$', 'HU': r'^[0-9]{4}$', 'ID': r'^[0-9]{5}$', 'IL': r'^[0-9]{7}$', 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$', 'IN': r'^[0-9]{6}$', 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'IQ': r'^[0-9]{5}$', 'IR': r'^[0-9]{5}-[0-9]{5}$', 'IS': r'^[0-9]{3}$', 'IT': r'^[0-9]{5}$', 'JE': r'^JE[0-9]{2}[A-Z]{2}$', 'JM': r'^JM[A-Z]{3}[0-9]{2}$', 'JO': r'^[0-9]{5}$', 'JP': r'^[0-9]{3}-?[0-9]{4}$', 'KE': r'^[0-9]{5}$', 'KG': r'^[0-9]{6}$', 'KH': r'^[0-9]{5}$', 'KR': r'^[0-9]{5}$', 'KY': r'^KY[0-9]-[0-9]{4}$', 'KZ': r'^[0-9]{6}$', 'LA': r'^[0-9]{5}$', 'LB': r'^[0-9]{8}$', 'LI': r'^[0-9]{4}$', 'LK': r'^[0-9]{5}$', 'LR': r'^[0-9]{4}$', 'LS': r'^[0-9]{3}$', 'LT': r'^(LT-)?[0-9]{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', 'MZ': r'^[0-9]{4}$', 'NA': r'^[0-9]{5}$', 'NC': r'^[0-9]{5}$', 'NE': r'^[0-9]{4}$', 'NF': r'^[0-9]{4}$', 'NG': r'^[0-9]{6}$', 'NI': r'^[0-9]{5}$', 'NL': r'^[0-9]{4}[A-Z]{2}$', 'NO': r'^[0-9]{4}$', 'NP': r'^[0-9]{5}$', 'NZ': r'^[0-9]{4}$', 'OM': r'^[0-9]{3}$', 'PA': r'^[0-9]{6}$', 'PE': r'^[0-9]{5}$', 'PF': r'^[0-9]{5}$', 'PG': r'^[0-9]{3}$', 'PH': r'^[0-9]{4}$', 'PK': r'^[0-9]{5}$', 'PL': r'^[0-9]{2}-?[0-9]{3}$', 'PM': r'^[0-9]{5}$', 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'PR': r'^[0-9]{5}$', 'PT': r'^[0-9]{4}(-?[0-9]{3})?$', 'PW': r'^[0-9]{5}$', 'PY': r'^[0-9]{4}$', 'RE': r'^[0-9]{5}$', 'RO': r'^[0-9]{6}$', 'RS': r'^[0-9]{5}$', 'RU': r'^[0-9]{6}$', 'SA': r'^[0-9]{5}$', 'SD': r'^[0-9]{5}$', 'SE': r'^[0-9]{5}$', 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$', 'SH': r'^(STHL1ZZ|TDCU1ZZ)$', 'SI': r'^(SI-)?[0-9]{4}$', 'SK': r'^[0-9]{5}$', 'SM': r'^[0-9]{5}$', 'SN': r'^[0-9]{5}$', 'SV': r'^01101$', 'SZ': r'^[A-Z][0-9]{3}$', 'TC': r'^TKCA1ZZ$', 'TD': r'^[0-9]{5}$', 'TH': r'^[0-9]{5}$', 'TJ': r'^[0-9]{6}$', 'TM': r'^[0-9]{6}$', 'TN': r'^[0-9]{4}$', 'TR': r'^[0-9]{5}$', 'TT': r'^[0-9]{6}$', 'TW': r'^([0-9]{3}|[0-9]{5})$', 'UA': r'^[0-9]{5}$', 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'UY': r'^[0-9]{5}$', 'UZ': r'^[0-9]{6}$', 'VA': r'^00120$', 'VC': r'^VC[0-9]{4}', 'VE': r'^[0-9]{4}[A-Z]?$', 'VG': r'^VG[0-9]{4}$', 'VI': r'^[0-9]{5}$', 'VN': r'^[0-9]{6}$', 'WF': r'^[0-9]{5}$', 'XK': r'^[0-9]{5}$', 'YT': r'^[0-9]{5}$', 'ZA': r'^[0-9]{4}$', 'ZM': r'^[0-9]{5}$', } title = models.CharField( pgettext_lazy("Treatment Pronouns for the customer", "Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, blank=True) # We use quite a few lines of an address as they are often quite long and # it's easier to just hide the unnecessary ones than add extra ones. line1 = models.CharField(_("First line of address"), max_length=255) line2 = models.CharField( _("Second line of address"), max_length=255, blank=True) line3 = models.CharField( _("Third line of address"), max_length=255, blank=True) line4 = models.CharField(_("City"), max_length=255, blank=True) state = models.CharField(_("State/County"), max_length=255, blank=True) postcode = UppercaseCharField( _("Post/Zip-code"), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', on_delete=models.CASCADE, verbose_name=_("Country")) #: A field only used for searching addresses - this contains all the #: relevant fields. This is effectively a poor man's Solr text field. search_text = models.TextField( _("Search text - used only for searching addresses"), editable=False) # Fields, used for `summary` property definition and hash generation. base_fields = hash_fields = ['salutation', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode', 'country'] def __str__(self): return self.summary class Meta: abstract = True verbose_name = _('Address') verbose_name_plural = _('Addresses') # Saving def save(self, *args, **kwargs): self._update_search_text() super().save(*args, **kwargs) def clean(self): # Strip all whitespace for field in ['first_name', 'last_name', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode']: if self.__dict__[field]: self.__dict__[field] = self.__dict__[field].strip() # Ensure postcodes are valid for country self.ensure_postcode_is_valid_for_country() def ensure_postcode_is_valid_for_country(self): """ Validate postcode given the country """ if not self.postcode and self.POSTCODE_REQUIRED and self.country_id: country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) if regex: msg = _("Addresses in %(country)s require a valid postcode") \ % {'country': self.country} raise exceptions.ValidationError(msg) if self.postcode and self.country_id: # Ensure postcodes are always uppercase postcode = self.postcode.upper().replace(' ', '') country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) # Validate postcode against regex for the country if available if regex and not re.match(regex, postcode): msg = _("The postcode '%(postcode)s' is not valid " "for %(country)s") \ % {'postcode': self.postcode, 'country': self.country} raise exceptions.ValidationError( {'postcode': [msg]}) def _update_search_text(self): search_fields = filter( bool, [self.first_name, self.last_name, self.line1, self.line2, self.line3, self.line4, self.state, self.postcode, self.country.name]) self.search_text = ' '.join(search_fields) # Properties @property def city(self): # Common alias return self.line4 @property def summary(self): """ Returns a single string summary of the address, separating fields using commas. """ return ", ".join(self.active_address_fields()) @property def salutation(self): """ Name (including title) """ return self.join_fields( ('title', 'first_name', 'last_name'), separator=" ") @property def name(self): return self.join_fields(('first_name', 'last_name'), separator=" ") # Helpers def get_field_values(self, fields): field_values = [] for field in fields: # Title is special case if field == 'title': value = self.get_title_display() elif field == 'country': try: value = self.country.printable_name except exceptions.ObjectDoesNotExist: value = '' elif field == 'salutation': value = self.salutation else: value = getattr(self, field) field_values.append(value) return field_values def get_address_field_values(self, fields): """ Returns set of field values within the salutation and country. """ field_values = [f.strip() for f in self.get_field_values(fields) if f] return field_values def generate_hash(self): """ Returns a hash of the address, based on standard set of fields, listed out in `hash_fields` property. """ field_values = self.get_address_field_values(self.hash_fields) # Python 2 and 3 generates CRC checksum in different ranges, so # in order to generate platform-independent value we apply # `& 0xffffffff` expression. return zlib.crc32(', '.join(field_values).upper().encode('UTF8')) & 0xffffffff def join_fields(self, fields, separator=", "): """ Join a sequence of fields using the specified separator """ field_values = self.get_field_values(fields) return separator.join(filter(bool, field_values)) def populate_alternative_model(self, address_model): """ For populating an address model using the matching fields from this one. This is used to convert a user address to a shipping address as part of the checkout process. """ destination_field_names = [ field.name for field in address_model._meta.fields] for field_name in [field.name for field in self._meta.fields]: if field_name in destination_field_names and field_name != 'id': setattr(address_model, field_name, getattr(self, field_name)) def active_address_fields(self): """ Returns the non-empty components of the address, but merging the title, first_name and last_name into a single line. It uses fields listed out in `base_fields` property. """ return self.get_address_field_values(self.base_fields) class AbstractCountry(models.Model): """ International Organization for Standardization (ISO) 3166-1 Country list. The field names are a bit awkward, but kept for backwards compatibility. pycountry's syntax of alpha2, alpha3, name and official_name seems sane. """ iso_3166_1_a2 = models.CharField( _('ISO 3166-1 alpha-2'), max_length=2, primary_key=True) iso_3166_1_a3 = models.CharField( _('ISO 3166-1 alpha-3'), max_length=3, blank=True) iso_3166_1_numeric = models.CharField( _('ISO 3166-1 numeric'), blank=True, max_length=3) #: The commonly used name; e.g. 'United Kingdom' printable_name = models.CharField(_('Country name'), max_length=128) #: The full official name of a country #: e.g. 'United Kingdom of Great Britain and Northern Ireland' name = models.CharField(_('Official name'), max_length=128) display_order = models.PositiveSmallIntegerField( _("Display order"), default=0, db_index=True, help_text=_('Higher the number, higher the country in the list.')) is_shipping_country = models.BooleanField( _("Is shipping country"), default=False, db_index=True) class Meta: abstract = True app_label = 'address' verbose_name = _('Country') verbose_name_plural = _('Countries') ordering = ('-display_order', 'printable_name',) def __str__(self): return self.printable_name or self.name @property def code(self): """ Shorthand for the ISO 3166 Alpha-2 code """ return self.iso_3166_1_a2 @property def numeric_code(self): """ Shorthand for the ISO 3166 numeric code. iso_3166_1_numeric used to wrongly be a integer field, but has to be padded with leading zeroes. It's since been converted to a char field, but the database might still contain non-padded strings. That's why the padding is kept. """ return "%.03d" % int(self.iso_3166_1_numeric) class AbstractShippingAddress(AbstractAddress): """ A shipping address. A shipping address should not be edited once the order has been placed - it should be read-only after that. NOTE: ShippingAddress is a model of the order app. But moving it there is tricky due to circular import issues that are amplified by get_model/get_class calls pre-Django 1.7 to register receivers. So... TODO: Once Django 1.6 support is dropped, move AbstractBillingAddress and AbstractShippingAddress to the order app, and move PartnerAddress to the partner app. """ phone_number = PhoneNumberField( _("Phone number"), blank=True, help_text=_("In case we need to call you about your order")) notes = models.TextField( blank=True, verbose_name=_('Instructions'), help_text=_("Tell us anything we should know when delivering " "your order.")) class Meta: abstract = True # ShippingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Shipping address") verbose_name_plural = _("Shipping addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractUserAddress(AbstractShippingAddress): """ A user's address. A user can have many of these and together they form an 'address book' of sorts for the user. We use a separate model for shipping and billing (even though there will be some data duplication) because we don't want shipping/billing addresses changed or deleted once an order has been placed. By having a separate model, we allow users the ability to add/edit/delete from their address book without affecting orders already placed. """ user = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='addresses', verbose_name=_("User")) #: Whether this address is the default for shipping is_default_for_shipping = models.BooleanField( _("Default shipping address?"), default=False) #: Whether this address should be the default for billing. is_default_for_billing = models.BooleanField( _("Default billing address?"), default=False) #: We keep track of the number of times an address has been used #: as a shipping address so we can show the most popular ones #: first at the checkout. num_orders_as_shipping_address = models.PositiveIntegerField( _("Number of Orders as Shipping Address"), default=0) #: Same as previous, but for billing address. num_orders_as_billing_address = models.PositiveIntegerField( _("Number of Orders as Billing Address"), default=0) #: A hash is kept to try and avoid duplicate addresses being added #: to the address book. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True, editable=False) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) def save(self, *args, **kwargs): """ Save a hash of the address fields """ # Save a hash of the address fields so we can check whether two # addresses are the same to avoid saving duplicates self.hash = self.generate_hash() # Ensure that each user only has one default shipping address # and billing address self._ensure_defaults_integrity() super().save(*args, **kwargs) def _ensure_defaults_integrity(self): if self.is_default_for_shipping: self.__class__._default_manager\ .filter(user=self.user, is_default_for_shipping=True)\ .update(is_default_for_shipping=False) if self.is_default_for_billing: self.__class__._default_manager\ .filter(user=self.user, is_default_for_billing=True)\ .update(is_default_for_billing=False) class Meta: abstract = True app_label = 'address' verbose_name = _("User address") verbose_name_plural = _("User addresses") ordering = ['-num_orders_as_shipping_address'] unique_together = ('user', 'hash') def validate_unique(self, exclude=None): super().validate_unique(exclude) qs = self.__class__.objects.filter( user=self.user, hash=self.generate_hash()) if self.id: qs = qs.exclude(id=self.id) if qs.exists(): raise exceptions.ValidationError({ '__all__': [_("This address is already in your address" " book")]}) class AbstractBillingAddress(AbstractAddress): class Meta: abstract = True # BillingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Billing address") verbose_name_plural = _("Billing addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractPartnerAddress(AbstractAddress): """ A partner can have one or more addresses. This can be useful e.g. when determining US tax which depends on the origin of the shipment. """ partner = models.ForeignKey( 'partner.Partner', on_delete=models.CASCADE, related_name='addresses', verbose_name=_('Partner')) class Meta: abstract = True app_label = 'partner' verbose_name = _("Partner address") verbose_name_plural = _("Partner addresses")
import pytest from django.core.exceptions import ValidationError from oscar.apps.catalogue import models def test_product_attributes_can_contain_underscores(): attr = models.ProductAttribute(name="A", code="a_b") attr.full_clean() def test_product_attributes_cant_contain_hyphens(): attr = models.ProductAttribute(name="A", code="a-b") with pytest.raises(ValidationError): attr.full_clean() def test_product_attributes_cant_be_python_keywords(): attr = models.ProductAttribute(name="A", code="import") with pytest.raises(ValidationError): attr.full_clean()
I need integration test for this code import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from phonenumber_field.modelfields import PhoneNumberField from oscar.core.compat import AUTH_USER_MODEL from oscar.models.fields import UppercaseCharField class AbstractAddress(models.Model): """ Superclass address object This is subclassed and extended to provide models for user, shipping and billing addresses. """ MR, MISS, MRS, MS, DR = ('Mr', 'Miss', 'Mrs', 'Ms', 'Dr') TITLE_CHOICES = ( (MR, _("Mr")), (MISS, _("Miss")), (MRS, _("Mrs")), (MS, _("Ms")), (DR, _("Dr")), ) POSTCODE_REQUIRED = 'postcode' in settings.OSCAR_REQUIRED_ADDRESS_FIELDS # Regex for each country. Not listed countries don't use postcodes # Based on http://en.wikipedia.org/wiki/List_of_postal_codes POSTCODES_REGEX = { 'AC': r'^[A-Z]{4}[0-9][A-Z]$', 'AD': r'^AD[0-9]{3}$', 'AF': r'^[0-9]{4}$', 'AI': r'^AI-2640$', 'AL': r'^[0-9]{4}$', 'AM': r'^[0-9]{4}$', 'AR': r'^([0-9]{4}|[A-Z][0-9]{4}[A-Z]{3})$', 'AS': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'AT': r'^[0-9]{4}$', 'AU': r'^[0-9]{4}$', 'AX': r'^[0-9]{5}$', 'AZ': r'^AZ[0-9]{4}$', 'BA': r'^[0-9]{5}$', 'BB': r'^BB[0-9]{5}$', 'BD': r'^[0-9]{4}$', 'BE': r'^[0-9]{4}$', 'BG': r'^[0-9]{4}$', 'BH': r'^[0-9]{3,4}$', 'BL': r'^[0-9]{5}$', 'BM': r'^[A-Z]{2}([0-9]{2}|[A-Z]{2})', 'BN': r'^[A-Z]{2}[0-9]{4}$', 'BO': r'^[0-9]{4}$', 'BR': r'^[0-9]{5}(-[0-9]{3})?$', 'BT': r'^[0-9]{3}$', 'BY': r'^[0-9]{6}$', 'CA': r'^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$', 'CC': r'^[0-9]{4}$', 'CH': r'^[0-9]{4}$', 'CL': r'^([0-9]{7}|[0-9]{3}-[0-9]{4})$', 'CN': r'^[0-9]{6}$', 'CO': r'^[0-9]{6}$', 'CR': r'^[0-9]{4,5}$', 'CU': r'^[0-9]{5}$', 'CV': r'^[0-9]{4}$', 'CX': r'^[0-9]{4}$', 'CY': r'^[0-9]{4}$', 'CZ': r'^[0-9]{5}$', 'DE': r'^[0-9]{5}$', 'DK': r'^[0-9]{4}$', 'DO': r'^[0-9]{5}$', 'DZ': r'^[0-9]{5}$', 'EC': r'^EC[0-9]{6}$', 'EE': r'^[0-9]{5}$', 'EG': r'^[0-9]{5}$', 'ES': r'^[0-9]{5}$', 'ET': r'^[0-9]{4}$', 'FI': r'^[0-9]{5}$', 'FK': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'FM': r'^[0-9]{5}(-[0-9]{4})?$', 'FO': r'^[0-9]{3}$', 'FR': r'^[0-9]{5}$', 'GA': r'^[0-9]{2}.*[0-9]{2}$', 'GB': r'^[A-Z][A-Z0-9]{1,3}[0-9][A-Z]{2}$', 'GE': r'^[0-9]{4}$', 'GF': r'^[0-9]{5}$', 'GG': r'^([A-Z]{2}[0-9]{2,3}[A-Z]{2})$', 'GI': r'^GX111AA$', 'GL': r'^[0-9]{4}$', 'GP': r'^[0-9]{5}$', 'GR': r'^[0-9]{5}$', 'GS': r'^SIQQ1ZZ$', 'GT': r'^[0-9]{5}$', 'GU': r'^[0-9]{5}$', 'GW': r'^[0-9]{4}$', 'HM': r'^[0-9]{4}$', 'HN': r'^[0-9]{5}$', 'HR': r'^[0-9]{5}$', 'HT': r'^[0-9]{4}$', 'HU': r'^[0-9]{4}$', 'ID': r'^[0-9]{5}$', 'IL': r'^[0-9]{7}$', 'IM': r'^IM[0-9]{2,3}[A-Z]{2}$$', 'IN': r'^[0-9]{6}$', 'IO': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'IQ': r'^[0-9]{5}$', 'IR': r'^[0-9]{5}-[0-9]{5}$', 'IS': r'^[0-9]{3}$', 'IT': r'^[0-9]{5}$', 'JE': r'^JE[0-9]{2}[A-Z]{2}$', 'JM': r'^JM[A-Z]{3}[0-9]{2}$', 'JO': r'^[0-9]{5}$', 'JP': r'^[0-9]{3}-?[0-9]{4}$', 'KE': r'^[0-9]{5}$', 'KG': r'^[0-9]{6}$', 'KH': r'^[0-9]{5}$', 'KR': r'^[0-9]{5}$', 'KY': r'^KY[0-9]-[0-9]{4}$', 'KZ': r'^[0-9]{6}$', 'LA': r'^[0-9]{5}$', 'LB': r'^[0-9]{8}$', 'LI': r'^[0-9]{4}$', 'LK': r'^[0-9]{5}$', 'LR': r'^[0-9]{4}$', 'LS': r'^[0-9]{3}$', 'LT': r'^(LT-)?[0-9]{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', 'MZ': r'^[0-9]{4}$', 'NA': r'^[0-9]{5}$', 'NC': r'^[0-9]{5}$', 'NE': r'^[0-9]{4}$', 'NF': r'^[0-9]{4}$', 'NG': r'^[0-9]{6}$', 'NI': r'^[0-9]{5}$', 'NL': r'^[0-9]{4}[A-Z]{2}$', 'NO': r'^[0-9]{4}$', 'NP': r'^[0-9]{5}$', 'NZ': r'^[0-9]{4}$', 'OM': r'^[0-9]{3}$', 'PA': r'^[0-9]{6}$', 'PE': r'^[0-9]{5}$', 'PF': r'^[0-9]{5}$', 'PG': r'^[0-9]{3}$', 'PH': r'^[0-9]{4}$', 'PK': r'^[0-9]{5}$', 'PL': r'^[0-9]{2}-?[0-9]{3}$', 'PM': r'^[0-9]{5}$', 'PN': r'^[A-Z]{4}[0-9][A-Z]{2}$', 'PR': r'^[0-9]{5}$', 'PT': r'^[0-9]{4}(-?[0-9]{3})?$', 'PW': r'^[0-9]{5}$', 'PY': r'^[0-9]{4}$', 'RE': r'^[0-9]{5}$', 'RO': r'^[0-9]{6}$', 'RS': r'^[0-9]{5}$', 'RU': r'^[0-9]{6}$', 'SA': r'^[0-9]{5}$', 'SD': r'^[0-9]{5}$', 'SE': r'^[0-9]{5}$', 'SG': r'^([0-9]{2}|[0-9]{4}|[0-9]{6})$', 'SH': r'^(STHL1ZZ|TDCU1ZZ)$', 'SI': r'^(SI-)?[0-9]{4}$', 'SK': r'^[0-9]{5}$', 'SM': r'^[0-9]{5}$', 'SN': r'^[0-9]{5}$', 'SV': r'^01101$', 'SZ': r'^[A-Z][0-9]{3}$', 'TC': r'^TKCA1ZZ$', 'TD': r'^[0-9]{5}$', 'TH': r'^[0-9]{5}$', 'TJ': r'^[0-9]{6}$', 'TM': r'^[0-9]{6}$', 'TN': r'^[0-9]{4}$', 'TR': r'^[0-9]{5}$', 'TT': r'^[0-9]{6}$', 'TW': r'^([0-9]{3}|[0-9]{5})$', 'UA': r'^[0-9]{5}$', 'US': r'^[0-9]{5}(-[0-9]{4}|-[0-9]{6})?$', 'UY': r'^[0-9]{5}$', 'UZ': r'^[0-9]{6}$', 'VA': r'^00120$', 'VC': r'^VC[0-9]{4}', 'VE': r'^[0-9]{4}[A-Z]?$', 'VG': r'^VG[0-9]{4}$', 'VI': r'^[0-9]{5}$', 'VN': r'^[0-9]{6}$', 'WF': r'^[0-9]{5}$', 'XK': r'^[0-9]{5}$', 'YT': r'^[0-9]{5}$', 'ZA': r'^[0-9]{4}$', 'ZM': r'^[0-9]{5}$', } title = models.CharField( pgettext_lazy("Treatment Pronouns for the customer", "Title"), max_length=64, choices=TITLE_CHOICES, blank=True) first_name = models.CharField(_("First name"), max_length=255, blank=True) last_name = models.CharField(_("Last name"), max_length=255, blank=True) # We use quite a few lines of an address as they are often quite long and # it's easier to just hide the unnecessary ones than add extra ones. line1 = models.CharField(_("First line of address"), max_length=255) line2 = models.CharField( _("Second line of address"), max_length=255, blank=True) line3 = models.CharField( _("Third line of address"), max_length=255, blank=True) line4 = models.CharField(_("City"), max_length=255, blank=True) state = models.CharField(_("State/County"), max_length=255, blank=True) postcode = UppercaseCharField( _("Post/Zip-code"), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', on_delete=models.CASCADE, verbose_name=_("Country")) #: A field only used for searching addresses - this contains all the #: relevant fields. This is effectively a poor man's Solr text field. search_text = models.TextField( _("Search text - used only for searching addresses"), editable=False) # Fields, used for `summary` property definition and hash generation. base_fields = hash_fields = ['salutation', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode', 'country'] def __str__(self): return self.summary class Meta: abstract = True verbose_name = _('Address') verbose_name_plural = _('Addresses') # Saving def save(self, *args, **kwargs): self._update_search_text() super().save(*args, **kwargs) def clean(self): # Strip all whitespace for field in ['first_name', 'last_name', 'line1', 'line2', 'line3', 'line4', 'state', 'postcode']: if self.__dict__[field]: self.__dict__[field] = self.__dict__[field].strip() # Ensure postcodes are valid for country self.ensure_postcode_is_valid_for_country() def ensure_postcode_is_valid_for_country(self): """ Validate postcode given the country """ if not self.postcode and self.POSTCODE_REQUIRED and self.country_id: country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) if regex: msg = _("Addresses in %(country)s require a valid postcode") \ % {'country': self.country} raise exceptions.ValidationError(msg) if self.postcode and self.country_id: # Ensure postcodes are always uppercase postcode = self.postcode.upper().replace(' ', '') country_code = self.country.iso_3166_1_a2 regex = self.POSTCODES_REGEX.get(country_code, None) # Validate postcode against regex for the country if available if regex and not re.match(regex, postcode): msg = _("The postcode '%(postcode)s' is not valid " "for %(country)s") \ % {'postcode': self.postcode, 'country': self.country} raise exceptions.ValidationError( {'postcode': [msg]}) def _update_search_text(self): search_fields = filter( bool, [self.first_name, self.last_name, self.line1, self.line2, self.line3, self.line4, self.state, self.postcode, self.country.name]) self.search_text = ' '.join(search_fields) # Properties @property def city(self): # Common alias return self.line4 @property def summary(self): """ Returns a single string summary of the address, separating fields using commas. """ return ", ".join(self.active_address_fields()) @property def salutation(self): """ Name (including title) """ return self.join_fields( ('title', 'first_name', 'last_name'), separator=" ") @property def name(self): return self.join_fields(('first_name', 'last_name'), separator=" ") # Helpers def get_field_values(self, fields): field_values = [] for field in fields: # Title is special case if field == 'title': value = self.get_title_display() elif field == 'country': try: value = self.country.printable_name except exceptions.ObjectDoesNotExist: value = '' elif field == 'salutation': value = self.salutation else: value = getattr(self, field) field_values.append(value) return field_values def get_address_field_values(self, fields): """ Returns set of field values within the salutation and country. """ field_values = [f.strip() for f in self.get_field_values(fields) if f] return field_values def generate_hash(self): """ Returns a hash of the address, based on standard set of fields, listed out in `hash_fields` property. """ field_values = self.get_address_field_values(self.hash_fields) # Python 2 and 3 generates CRC checksum in different ranges, so # in order to generate platform-independent value we apply # `& 0xffffffff` expression. return zlib.crc32(', '.join(field_values).upper().encode('UTF8')) & 0xffffffff def join_fields(self, fields, separator=", "): """ Join a sequence of fields using the specified separator """ field_values = self.get_field_values(fields) return separator.join(filter(bool, field_values)) def populate_alternative_model(self, address_model): """ For populating an address model using the matching fields from this one. This is used to convert a user address to a shipping address as part of the checkout process. """ destination_field_names = [ field.name for field in address_model._meta.fields] for field_name in [field.name for field in self._meta.fields]: if field_name in destination_field_names and field_name != 'id': setattr(address_model, field_name, getattr(self, field_name)) def active_address_fields(self): """ Returns the non-empty components of the address, but merging the title, first_name and last_name into a single line. It uses fields listed out in `base_fields` property. """ return self.get_address_field_values(self.base_fields) class AbstractCountry(models.Model): """ International Organization for Standardization (ISO) 3166-1 Country list. The field names are a bit awkward, but kept for backwards compatibility. pycountry's syntax of alpha2, alpha3, name and official_name seems sane. """ iso_3166_1_a2 = models.CharField( _('ISO 3166-1 alpha-2'), max_length=2, primary_key=True) iso_3166_1_a3 = models.CharField( _('ISO 3166-1 alpha-3'), max_length=3, blank=True) iso_3166_1_numeric = models.CharField( _('ISO 3166-1 numeric'), blank=True, max_length=3) #: The commonly used name; e.g. 'United Kingdom' printable_name = models.CharField(_('Country name'), max_length=128) #: The full official name of a country #: e.g. 'United Kingdom of Great Britain and Northern Ireland' name = models.CharField(_('Official name'), max_length=128) display_order = models.PositiveSmallIntegerField( _("Display order"), default=0, db_index=True, help_text=_('Higher the number, higher the country in the list.')) is_shipping_country = models.BooleanField( _("Is shipping country"), default=False, db_index=True) class Meta: abstract = True app_label = 'address' verbose_name = _('Country') verbose_name_plural = _('Countries') ordering = ('-display_order', 'printable_name',) def __str__(self): return self.printable_name or self.name @property def code(self): """ Shorthand for the ISO 3166 Alpha-2 code """ return self.iso_3166_1_a2 @property def numeric_code(self): """ Shorthand for the ISO 3166 numeric code. iso_3166_1_numeric used to wrongly be a integer field, but has to be padded with leading zeroes. It's since been converted to a char field, but the database might still contain non-padded strings. That's why the padding is kept. """ return "%.03d" % int(self.iso_3166_1_numeric) class AbstractShippingAddress(AbstractAddress): """ A shipping address. A shipping address should not be edited once the order has been placed - it should be read-only after that. NOTE: ShippingAddress is a model of the order app. But moving it there is tricky due to circular import issues that are amplified by get_model/get_class calls pre-Django 1.7 to register receivers. So... TODO: Once Django 1.6 support is dropped, move AbstractBillingAddress and AbstractShippingAddress to the order app, and move PartnerAddress to the partner app. """ phone_number = PhoneNumberField( _("Phone number"), blank=True, help_text=_("In case we need to call you about your order")) notes = models.TextField( blank=True, verbose_name=_('Instructions'), help_text=_("Tell us anything we should know when delivering " "your order.")) class Meta: abstract = True # ShippingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Shipping address") verbose_name_plural = _("Shipping addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractUserAddress(AbstractShippingAddress): """ A user's address. A user can have many of these and together they form an 'address book' of sorts for the user. We use a separate model for shipping and billing (even though there will be some data duplication) because we don't want shipping/billing addresses changed or deleted once an order has been placed. By having a separate model, we allow users the ability to add/edit/delete from their address book without affecting orders already placed. """ user = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='addresses', verbose_name=_("User")) #: Whether this address is the default for shipping is_default_for_shipping = models.BooleanField( _("Default shipping address?"), default=False) #: Whether this address should be the default for billing. is_default_for_billing = models.BooleanField( _("Default billing address?"), default=False) #: We keep track of the number of times an address has been used #: as a shipping address so we can show the most popular ones #: first at the checkout. num_orders_as_shipping_address = models.PositiveIntegerField( _("Number of Orders as Shipping Address"), default=0) #: Same as previous, but for billing address. num_orders_as_billing_address = models.PositiveIntegerField( _("Number of Orders as Billing Address"), default=0) #: A hash is kept to try and avoid duplicate addresses being added #: to the address book. hash = models.CharField(_("Address Hash"), max_length=255, db_index=True, editable=False) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) def save(self, *args, **kwargs): """ Save a hash of the address fields """ # Save a hash of the address fields so we can check whether two # addresses are the same to avoid saving duplicates self.hash = self.generate_hash() # Ensure that each user only has one default shipping address # and billing address self._ensure_defaults_integrity() super().save(*args, **kwargs) def _ensure_defaults_integrity(self): if self.is_default_for_shipping: self.__class__._default_manager\ .filter(user=self.user, is_default_for_shipping=True)\ .update(is_default_for_shipping=False) if self.is_default_for_billing: self.__class__._default_manager\ .filter(user=self.user, is_default_for_billing=True)\ .update(is_default_for_billing=False) class Meta: abstract = True app_label = 'address' verbose_name = _("User address") verbose_name_plural = _("User addresses") ordering = ['-num_orders_as_shipping_address'] unique_together = ('user', 'hash') def validate_unique(self, exclude=None): super().validate_unique(exclude) qs = self.__class__.objects.filter( user=self.user, hash=self.generate_hash()) if self.id: qs = qs.exclude(id=self.id) if qs.exists(): raise exceptions.ValidationError({ '__all__': [_("This address is already in your address" " book")]}) class AbstractBillingAddress(AbstractAddress): class Meta: abstract = True # BillingAddress is registered in order/models.py app_label = 'order' verbose_name = _("Billing address") verbose_name_plural = _("Billing addresses") @property def order(self): """ Return the order linked to this shipping address """ try: return self.order_set.all()[0] except IndexError: return None class AbstractPartnerAddress(AbstractAddress): """ A partner can have one or more addresses. This can be useful e.g. when determining US tax which depends on the origin of the shipment. """ partner = models.ForeignKey( 'partner.Partner', on_delete=models.CASCADE, related_name='addresses', verbose_name=_('Partner')) class Meta: abstract = True app_label = 'partner' verbose_name = _("Partner address") verbose_name_plural = _("Partner addresses")
from django.test import TestCase from oscar.test import factories from oscar.core.loading import get_model Product = get_model('catalogue', 'Product') class ProductOptionTests(TestCase): def setUp(self): self.product_class = factories.ProductClassFactory() self.product = factories.create_product(product_class=self.product_class) self.option = factories.OptionFactory() def test_product_has_options_per_product_class(self): self.product_class.options.add(self.option) self.assertTrue(self.product.has_options) def test_product_has_options_per_product(self): self.product.product_options.add(self.option) self.assertTrue(self.product.has_options) def test_queryset_per_product_class(self): self.product_class.options.add(self.option) qs = Product.browsable.base_queryset().filter(id=self.product.id) product = qs.first() self.assertTrue(product.has_options) self.assertEquals(product.num_product_class_options, 1) def test_queryset_per_product(self): self.product.product_options.add(self.option) qs = Product.browsable.base_queryset().filter(id=self.product.id) product = qs.first() self.assertTrue(product.has_options) self.assertEquals(product.num_product_options, 1)
"I need integration test for this code\n\nimport re\nimport zlib\n\nfrom django.conf import settings(...TRUNCATED)
"# coding=utf-8\nfrom django.db import IntegrityError\nfrom django.test import TestCase\nfrom django(...TRUNCATED)
"I need integration test for this code\n\nimport re\nimport zlib\n\nfrom django.conf import settings(...TRUNCATED)
"from django.test import TestCase\n\nfrom oscar.apps.catalogue import models\n\n\nclass TestProductC(...TRUNCATED)

Dataset Card for [Dataset Name]

Dataset Summary

[More Information Needed]

Supported Tasks and Leaderboards

[More Information Needed]

Languages

[More Information Needed]

Dataset Structure

Data Instances

[More Information Needed]

Data Fields

[More Information Needed]

Data Splits

[More Information Needed]

Dataset Creation

Curation Rationale

[More Information Needed]

Source Data

Initial Data Collection and Normalization

[More Information Needed]

Who are the source language producers?

[More Information Needed]

Annotations

Annotation process

[More Information Needed]

Who are the annotators?

[More Information Needed]

Personal and Sensitive Information

[More Information Needed]

Considerations for Using the Data

Social Impact of Dataset

[More Information Needed]

Discussion of Biases

[More Information Needed]

Other Known Limitations

[More Information Needed]

Additional Information

Dataset Curators

[More Information Needed]

Licensing Information

[More Information Needed]

Citation Information

[More Information Needed]

Contributions

Thanks to @github-username for adding this dataset.

Downloads last month
0
Edit dataset card