input
stringclasses
1 value
instruction
stringclasses
326 values
output
stringclasses
36 values
I need integration test for this code from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class WishlistsConfig(AppConfig): label = 'wishlists' name = 'oscar.apps.wishlists' verbose_name = _('Wishlists')
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings class SlugFieldTest(TestCase): def test_slugfield_allow_unicode_kwargs_precedence(self): from oscar.models.fields.slugfield import SlugField with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): slug_field = SlugField(allow_unicode=False) self.assertFalse(slug_field.allow_unicode) slug_field = SlugField() self.assertTrue(slug_field.allow_unicode)
I need integration test for this code from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class WishlistsConfig(AppConfig): label = 'wishlists' name = 'oscar.apps.wishlists' verbose_name = _('Wishlists')
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings from oscar.core import utils def sluggish(value, allow_unicode=False): return value.upper() class TestSlugify(TestCase): def test_default_unicode_to_ascii(self): self.assertEqual('konig-der-straxdfe', utils.slugify('König der Straße')) self.assertEqual('not-fancy', utils.slugify('Not fancy')) self.assertEqual('u4e01u4e02-u4e03u4e04u4e05', utils.slugify('丁丂 七丄丅')) @override_settings(OSCAR_SLUG_ALLOW_UNICODE=True) def test_allow_unicode(self): self.assertEqual('könig-der-straße', utils.slugify('König der Straße')) self.assertEqual('丁丂-七丄丅', utils.slugify('丁丂 七丄丅')) self.assertEqual('not-fancy', utils.slugify('Not fancy')) @override_settings(OSCAR_SLUG_FUNCTION='tests.integration.core.test_utils.sluggish') def test_custom_slugifier(self): self.assertEqual('HAM AND EGGS', utils.slugify('Ham and eggs')) @override_settings(OSCAR_SLUG_MAP={'c++': 'cpp'}) def test_uses_custom_mappings(self): self.assertEqual('cpp', utils.slugify('c++')) @override_settings(OSCAR_SLUG_BLACKLIST=['the']) def test_uses_blacklist(self): self.assertEqual('bible', utils.slugify('The Bible')) @override_settings(OSCAR_SLUG_BLACKLIST=['the', 'bible']) def test_uses_blacklist_doesnt_reduce_to_nothing(self): self.assertEqual('bible', utils.slugify('The Bible'))
I need integration test for this code from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class WishlistsConfig(AppConfig): label = 'wishlists' name = 'oscar.apps.wishlists' verbose_name = _('Wishlists')
from django.core.exceptions import ValidationError from django.contrib.flatpages.models import FlatPage from django.test import TestCase, override_settings from django.utils.translation import activate from oscar.core.validators import ExtendedURLValidator, URLDoesNotExistValidator class TestExtendedURLValidator(TestCase): def setUp(self): self.validator = ExtendedURLValidator() def test_validates_local_url(self): try: self.validator('/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validates_local_url_with_query_strings(self): try: self.validator('/?q=test') # Query strings shouldn't affect validation except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_raises_validation_error_for_missing_urls(self): with self.assertRaises(ValidationError): self.validator('/invalid/') def test_validates_urls_missing_preceding_slash(self): try: self.validator('catalogue/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_raises_validation_error_for_urls_without_trailing_slash(self): with self.assertRaises(ValidationError): self.validator('/catalogue') # Missing the / is bad def test_validates_flatpages_urls(self): FlatPage.objects.create(title='test page', url='/test/page/') try: self.validator('/test/page/') except ValidationError: self.fail('ExtendedURLValidator raises ValidationError' 'unexpectedly!') @override_settings( LANGUAGES=( ('de', 'German'), ('en-gb', 'British English'), ) ) class TestExtendedURLValidatorForLocalePrefixURLS(TestCase): def setUp(self): self.validator = ExtendedURLValidator() def test_validate_same_locals(self): """ Current locale is default ("en-gb"), URL has locale prefix of default and current locale ("en-gb"). """ try: self.validator('/en-gb/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_prefix_locale_is_non_default(self): """ Current locale is default ("en-gb"), URL has locale prefix of non-default locale ("de"). """ try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_locale_is_non_default(self): """ Current locale is non-default ("de"), URL has locale prefix of default locale ("en-gb"). """ activate('de') try: self.validator('/en-gb/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_and_prefix_locales_are_non_default_and_same(self): """ Current locale is non-default ("de"), URL has locale prefix of non-default locale ("de"). """ activate('de') try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_and_prefix_locales_are_non_default_and_different(self): """ Current locale is non-default ("it"), URL has locale prefix of non-default locale ("de"). """ activate('it') try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') class TestURLDoesNotExistValidator(TestCase): def setUp(self): self.validator = URLDoesNotExistValidator() def test_raises_exception_for_local_urls(self): self.assertRaises(ValidationError, self.validator, '/') def test_raises_exception_for_flatpages(self): FlatPage.objects.create(title='test page', url='/test/page/') self.assertRaises(ValidationError, self.validator, '/test/page/')
I need integration test for this code from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class WishlistsConfig(AppConfig): label = 'wishlists' name = 'oscar.apps.wishlists' verbose_name = _('Wishlists')
import pytest from oscar.views import handler403, handler404, handler500 @pytest.mark.django_db def test_handler403_response_status(rf): request = rf.get('/') response = handler403(request, exception=None) assert response.status_code == 403 @pytest.mark.django_db def test_handler404_response_status(rf): request = rf.get('/') response = handler404(request, exception=None) assert response.status_code == 404 @pytest.mark.django_db def test_handler500_response_status(rf): request = rf.get('/') response = handler500(request) assert response.status_code == 500
I need integration test for this code from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class WishlistsConfig(AppConfig): label = 'wishlists' name = 'oscar.apps.wishlists' verbose_name = _('Wishlists')
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
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 # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# -*- 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 # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
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 # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# -*- 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 # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
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 # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
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 # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# coding=utf-8 from django.db import IntegrityError from django.test import TestCase from django.core.exceptions import ValidationError from oscar.apps.catalogue.models import (Product, ProductClass, ProductAttribute, AttributeOption, ProductRecommendation) from oscar.test import factories class ProductTests(TestCase): def setUp(self): self.product_class, _ = ProductClass.objects.get_or_create( name='Clothing') class ProductCreationTests(ProductTests): def setUp(self): super().setUp() ProductAttribute.objects.create(product_class=self.product_class, name='Number of pages', code='num_pages', type='integer') Product.ENABLE_ATTRIBUTE_BINDING = True def tearDown(self): Product.ENABLE_ATTRIBUTE_BINDING = False def test_create_products_with_attributes(self): product = Product(upc='1234', product_class=self.product_class, title='testing') product.attr.num_pages = 100 product.save() def test_none_upc_is_represented_as_empty_string(self): product = Product(product_class=self.product_class, title='testing', upc=None) product.save() product.refresh_from_db() self.assertEqual(product.upc, '') def test_upc_uniqueness_enforced(self): Product.objects.create(product_class=self.product_class, title='testing', upc='bah') self.assertRaises(IntegrityError, Product.objects.create, product_class=self.product_class, title='testing', upc='bah') def test_allow_two_products_without_upc(self): for x in range(2): Product.objects.create(product_class=self.product_class, title='testing', upc=None) class TopLevelProductTests(ProductTests): def test_top_level_products_must_have_titles(self): product = Product(product_class=self.product_class) self.assertRaises(ValidationError, product.clean) def test_top_level_products_must_have_product_class(self): product = Product(title="Kopfhörer") self.assertRaises(ValidationError, product.clean) def test_top_level_products_are_part_of_browsable_set(self): product = Product.objects.create( product_class=self.product_class, title="Kopfhörer") self.assertEqual(set([product]), set(Product.browsable.all())) class ChildProductTests(ProductTests): def setUp(self): super().setUp() self.parent = Product.objects.create( title="Parent product", product_class=self.product_class, structure=Product.PARENT, is_discountable=False) def test_child_products_dont_need_titles(self): Product.objects.create( parent=self.parent, structure=Product.CHILD) def test_child_products_dont_need_a_product_class(self): Product.objects.create(parent=self.parent, structure=Product.CHILD) def test_child_products_inherit_fields(self): p = Product.objects.create( parent=self.parent, structure=Product.CHILD, is_discountable=True) self.assertEqual("Parent product", p.get_title()) self.assertEqual("Clothing", p.get_product_class().name) self.assertEqual(False, p.get_is_discountable()) def test_child_products_are_not_part_of_browsable_set(self): Product.objects.create( product_class=self.product_class, parent=self.parent, structure=Product.CHILD) self.assertEqual(set([self.parent]), set(Product.browsable.all())) class TestAChildProduct(TestCase): def setUp(self): clothing = ProductClass.objects.create( name='Clothing', requires_shipping=True) self.parent = clothing.products.create( title="Parent", structure=Product.PARENT) self.child = self.parent.children.create(structure=Product.CHILD) def test_delegates_requires_shipping_logic(self): self.assertTrue(self.child.is_shipping_required) class ProductAttributeCreationTests(TestCase): def test_validating_option_attribute(self): option_group = factories.AttributeOptionGroupFactory() option_1 = factories.AttributeOptionFactory(group=option_group) option_2 = factories.AttributeOptionFactory(group=option_group) pa = factories.ProductAttribute( type='option', option_group=option_group) self.assertRaises(ValidationError, pa.validate_value, 'invalid') pa.validate_value(option_1) pa.validate_value(option_2) invalid_option = AttributeOption(option='invalid option') self.assertRaises( ValidationError, pa.validate_value, invalid_option) def test_entity_attributes(self): unrelated_object = factories.PartnerFactory() attribute = factories.ProductAttributeFactory(type='entity') attribute_value = factories.ProductAttributeValueFactory( attribute=attribute, value_entity=unrelated_object) self.assertEqual(attribute_value.value, unrelated_object) class ProductRecommendationTests(ProductTests): def setUp(self): super().setUp() self.primary_product = Product.objects.create( upc='1234', product_class=self.product_class, title='Primary Product' ) def test_recommended_products_ordering(self): secondary_products = [] for i in range(5): secondary_products.append(Product.objects.create( upc='secondary%s' % i, product_class=self.product_class, title='Secondary Product #%s' % i )) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[3], ranking=5) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[1], ranking=2) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[2], ranking=4) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[4], ranking=1) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[0], ranking=3) recommended_products = [ secondary_products[3], secondary_products[2], secondary_products[0], secondary_products[1], secondary_products[4] ] self.assertEqual(self.primary_product.sorted_recommended_products, recommended_products)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.test import TestCase from oscar.apps.catalogue import models class TestProductClassModel(TestCase): def test_slug_is_auto_created(self): books = models.ProductClass.objects.create( name="Book", ) self.assertEqual('book', books.slug) def test_has_attribute_for_whether_shipping_is_required(self): models.ProductClass.objects.create( name="Download", requires_shipping=False, )
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
import os import tempfile from unittest import mock from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import TestCase, override_settings from oscar.apps.catalogue.abstract_models import MissingProductImage from oscar.test import factories class TestProductImages(TestCase): def test_images_are_in_consecutive_order(self): product = factories.create_product() for i in range(4): factories.create_product_image(product=product, display_order=i) product.images.all()[2].delete() for idx, im in enumerate(product.images.all()): self.assertEqual(im.display_order, idx) def test_variant_images(self): parent = factories.ProductFactory(structure='parent') variant = factories.create_product(parent=parent) factories.create_product_image(product=variant, caption='Variant Image') all_images = variant.get_all_images() self.assertEquals(all_images.count(), 1) product_image = all_images.first() self.assertEquals(product_image.caption, 'Variant Image') def test_variant_images_fallback_to_parent(self): parent = factories.ProductFactory(structure='parent') variant = factories.create_product(parent=parent) factories.create_product_image(product=parent, caption='Parent Product Image') all_images = variant.get_all_images() self.assertEquals(all_images.count(), 1) product_image = all_images.first() self.assertEquals(product_image.caption, 'Parent Product Image') class TestMissingProductImage(StaticLiveServerTestCase): TEMP_MEDIA_ROOT = tempfile.mkdtemp() @override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT) @mock.patch('oscar.apps.catalogue.abstract_models.find') def test_symlink_creates_directories(self, mock_find): # Create a fake empty file to symlink img = tempfile.NamedTemporaryFile(delete=False) img.close() mock_find.return_value = img.name # Initialise the class with a nested path path = 'image/path.jpg' MissingProductImage(path) # Check that the directory exists image_path = os.path.join(self.TEMP_MEDIA_ROOT, path) self.assertTrue(os.path.exists(image_path)) # Clean up for f in [image_path, img.name]: os.unlink(f) for d in [os.path.join(self.TEMP_MEDIA_ROOT, 'image'), self.TEMP_MEDIA_ROOT]: os.rmdir(d) @mock.patch('oscar.apps.catalogue.abstract_models.MissingProductImage.symlink_missing_image') def test_no_symlink_when_no_media_root(self, mock_symlink): MissingProductImage() self.assertEqual(mock_symlink.call_count, 0)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.test import TestCase from django.test.utils import override_settings from oscar.apps.catalogue.search_handlers import ( get_product_search_handler_class, ) class TestSearchHandler(object): pass class TestProductSearchHandlerSetting(TestCase): def test_product_search_handler_setting(self): """ Test that the `OSCAR_PRODUCT_SEARCH_HANDLER` setting, when set, dictates the return value of the `get_product_search_handler_class` function. """ handler_override = 'tests.integration.catalogue.test_product_search_handler_setting.TestSearchHandler' with override_settings(OSCAR_PRODUCT_SEARCH_HANDLER=handler_override): handler_class = get_product_search_handler_class() self.assertEqual(handler_class, TestSearchHandler)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.test import TestCase from oscar.apps.catalogue.reviews import forms from oscar.test.factories import UserFactory, create_product class TestReviewForm(TestCase): def test_cleans_title(self): product = create_product() reviewer = UserFactory() data = { 'title': ' This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } form = forms.ProductReviewForm( product=product, user=reviewer, data=data) assert form.is_valid() review = form.save() assert review.title == "This product is lovely" def test_validates_empty_data_correctly(self): form = forms.ProductReviewForm(product=None, user=None, data={}) assert form.is_valid() is False def test_validates_correctly(self): data = { 'title': 'This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } form = forms.ProductReviewForm(product=None, user=None, data=data) assert form.is_valid() class TestVoteForm(TestCase): def setUp(self): self.product = create_product() self.reviewer = UserFactory() self.voter = UserFactory() self.review = self.product.reviews.create( title='This is nice', score=3, body="This is the body", user=self.reviewer) def test_allows_real_users_to_vote(self): form = forms.VoteForm(self.review, self.voter, data={'delta': 1}) self.assertTrue(form.is_valid()) def test_prevents_users_from_voting_more_than_once(self): self.review.vote_up(self.voter) form = forms.VoteForm(self.review, self.voter, data={'delta': 1}) self.assertFalse(form.is_valid()) self.assertTrue(len(form.errors['__all__']) > 0) def test_prevents_users_voting_on_their_own_reviews(self): form = forms.VoteForm(self.review, self.reviewer, data={'delta': 1}) self.assertFalse(form.is_valid()) self.assertTrue(len(form.errors['__all__']) > 0)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.test import TestCase from django.core.exceptions import ValidationError from oscar.core.compat import get_user_model from oscar.apps.catalogue.reviews import models from oscar.test.factories import create_product from oscar.test.factories import UserFactory User = get_user_model() class TestAnAnonymousReview(TestCase): def setUp(self): self.product = create_product() self.data = { 'product': self.product, 'title': 'This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } def review(self, **kwargs): if kwargs: data = self.data.copy() data.update(kwargs) else: data = self.data return models.ProductReview(**data) def test_can_be_created(self): review = self.review() review.full_clean() def test_requires_a_title(self): review = self.review(title="") self.assertRaises(ValidationError, review.full_clean) def test_requires_a_body(self): review = self.review(body="") self.assertRaises(ValidationError, review.full_clean) def test_requires_a_name(self): review = self.review(name="") self.assertRaises(ValidationError, review.full_clean) def test_requires_an_email_address(self): review = self.review(email="") self.assertRaises(ValidationError, review.full_clean) def test_requires_non_whitespace_title(self): review = self.review(title=" ") self.assertRaises(ValidationError, review.full_clean) def test_starts_with_no_votes(self): review = self.review() review.save() self.assertFalse(review.has_votes) self.assertEqual(0, review.num_up_votes) self.assertEqual(0, review.num_down_votes) def test_has_reviewer_name_property(self): review = self.review(name="Dave") self.assertEqual("Dave", review.reviewer_name) def test_review_moderate_setting_false(self): with self.settings(OSCAR_MODERATE_REVIEWS=False): review = self.review() self.assertEqual(1, review.status) def test_review_moderate_setting_true(self): with self.settings(OSCAR_MODERATE_REVIEWS=True): review = self.review() self.assertEqual(0, review.status) class TestAUserReview(TestCase): def setUp(self): self.product = create_product() self.user = UserFactory(first_name="Tom", last_name="Thumb") self.data = { 'product': self.product, 'title': 'This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'user': self.user } def review(self, **kwargs): if kwargs: data = self.data.copy() data.update(kwargs) else: data = self.data return models.ProductReview(**data) def test_can_be_created(self): review = self.review() review.full_clean() def test_requires_a_title(self): review = self.review(title="") self.assertRaises(ValidationError, review.full_clean) def test_requires_a_body(self): review = self.review(body="") self.assertRaises(ValidationError, review.full_clean) def test_has_reviewer_name_property(self): review = self.review() self.assertEqual("Tom Thumb", review.reviewer_name) def test_num_approved_reviews(self): review = self.review() review.save() self.assertEqual(self.product.num_approved_reviews, 1) self.assertEqual(self.product.reviews.approved().first(), review) def test_review_moderate_setting_false(self): with self.settings(OSCAR_MODERATE_REVIEWS=False): review = self.review() self.assertEqual(1, review.status) def test_review_moderate_setting_true(self): with self.settings(OSCAR_MODERATE_REVIEWS=True): review = self.review() self.assertEqual(0, review.status) class TestVotingOnAReview(TestCase): def setUp(self): self.product = create_product() self.user = UserFactory() self.voter = UserFactory() self.review = self.product.reviews.create( title='This is nice', score=3, body="This is the body", user=self.user) def test_updates_totals_for_upvote(self): self.review.vote_up(self.voter) self.assertTrue(self.review.has_votes) self.assertEqual(1, self.review.total_votes) self.assertEqual(1, self.review.delta_votes) def test_updates_totals_for_downvote(self): self.review.vote_down(self.voter) self.assertTrue(self.review.has_votes) self.assertEqual(1, self.review.total_votes) self.assertEqual(-1, self.review.delta_votes) def test_is_permitted_for_normal_user(self): is_allowed, reason = self.review.can_user_vote(self.voter) self.assertTrue(is_allowed, reason) def test_is_not_permitted_for_reviewer(self): is_allowed, reason = self.review.can_user_vote(self.user) self.assertFalse(is_allowed, reason) def test_is_not_permitted_for_previous_voter(self): self.review.vote_up(self.voter) is_allowed, reason = self.review.can_user_vote(self.voter) self.assertFalse(is_allowed, reason)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from decimal import Decimal as D from unittest import mock from django.test import TestCase, override_settings from django.conf import settings from oscar.apps.basket import forms, formsets from oscar.apps.offer.utils import Applicator from oscar.core.loading import get_model from oscar.test import factories from oscar.test.basket import add_product from oscar.test.factories import ( BenefitFactory, ConditionalOfferFactory, ConditionFactory, RangeFactory) Line = get_model('basket', 'Line') class TestBasketLineForm(TestCase): def setUp(self): self.applicator = Applicator() rng = RangeFactory(includes_all_products=True) self.condition = ConditionFactory( range=rng, type=ConditionFactory._meta.model.VALUE, value=D('100'), proxy_class=None) self.benefit = BenefitFactory( range=rng, type=BenefitFactory._meta.model.FIXED, value=D('10'), max_affected_items=1) self.basket = factories.create_basket() self.line = self.basket.all_lines()[0] def mock_availability_return_value(self, is_available, reason=''): policy = self.line.purchase_info.availability policy.is_purchase_permitted = mock.MagicMock( return_value=(is_available, reason)) def build_form(self, quantity=None): if quantity is None: quantity = self.line.quantity return forms.BasketLineForm( strategy=self.basket.strategy, data={'quantity': quantity}, instance=self.line) def test_enforces_availability_policy_for_valid_quantities(self): self.mock_availability_return_value(True) form = self.build_form() self.assertTrue(form.is_valid()) def test_enforces_availability_policy_for_invalid_quantities(self): self.mock_availability_return_value(False, "Some reason") form = self.build_form() self.assertFalse(form.is_valid()) self.assertEqual( form.errors['quantity'], ['Some reason']) def test_skips_availability_policy_for_zero_quantities(self): self.mock_availability_return_value(True) form = self.build_form(quantity=0) self.assertTrue(form.is_valid()) def test_enforces_max_line_quantity_for_new_product(self): invalid_qty = settings.OSCAR_MAX_BASKET_QUANTITY_THRESHOLD + 1 form = self.build_form(quantity=invalid_qty) self.assertFalse(form.is_valid()) @override_settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=10) def test_enforce_max_line_quantity_for_existing_product(self): self.basket.flush() product = factories.create_product(num_in_stock=20) add_product(self.basket, D('100'), 4, product) self.line = self.basket.all_lines()[0] form = self.build_form(quantity=6) self.assertTrue(form.is_valid()) form.save() form = self.build_form(quantity=11) self.assertFalse(form.is_valid()) def test_line_quantity_max_attribute_per_num_available(self): self.basket.flush() product = factories.create_product(num_in_stock=20) add_product(self.basket, D('100'), 4, product) self.line = self.basket.all_lines()[0] form = self.build_form() self.assertIn('max="20"', str(form['quantity'])) @override_settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=10) def test_line_quantity_max_attribute_per_basket_threshold(self): self.basket.flush() product = factories.create_product(num_in_stock=20) add_product(self.basket, D('100'), 4, product) self.line = self.basket.all_lines()[0] form = self.build_form() self.assertIn('max="6"', str(form['quantity'])) def test_basketline_formset_ordering(self): # when we use a unordered queryset in the Basketlineformset, the # discounts will be lost because django will query the database # again to enforce ordered results add_product(self.basket, D('100'), 5) offer = ConditionalOfferFactory( pk=1, condition=self.condition, benefit=self.benefit) # now we force an unordered queryset so we can see that our discounts # will disappear due to a new ordering query (see django/forms/model.py) default_line_ordering = Line._meta.ordering Line._meta.ordering = [] self.basket._lines = self.basket.lines.all() self.applicator.apply_offers(self.basket, [offer]) formset = formsets.BasketLineFormSet( strategy=self.basket.strategy, queryset=self.basket.all_lines()) # the discount is in all_lines(): self.assertTrue(self.basket.all_lines()[0].has_discount) # but not in the formset self.assertFalse(formset.forms[0].instance.has_discount) # Restore the ordering on the line Line._meta.ordering = default_line_ordering # clear the cached lines and apply the offer again self.basket._lines = None self.applicator.apply_offers(self.basket, [offer]) formset = formsets.BasketLineFormSet( strategy=self.basket.strategy, queryset=self.basket.all_lines()) self.assertTrue(formset.forms[0].instance.has_discount) class TestAddToBasketForm(TestCase): def test_allows_a_product_quantity_to_be_increased(self): basket = factories.create_basket() product = basket.all_lines()[0].product # Add more of the same product data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertTrue(form.is_valid()) def test_checks_whether_passed_product_id_matches_a_real_product(self): basket = factories.create_basket() product = basket.all_lines()[0].product # Add more of the same product data = {'quantity': -1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) def test_checks_if_purchase_is_permitted(self): basket = factories.BasketFactory() product = factories.ProductFactory() # Build a 4-level mock monster so we can force the return value of # whether the product is available to buy. This is a serious code smell # and needs to be remedied. info = mock.Mock() info.availability = mock.Mock() info.availability.is_purchase_permitted = mock.Mock( return_value=(False, "Not on your nelly!")) basket.strategy.fetch_for_product = mock.Mock( return_value=info) data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) self.assertEqual('Not on your nelly!', form.errors['__all__'][0]) def test_mixed_currency_baskets_are_not_permitted(self): # Ensure basket is one currency basket = mock.Mock() basket.currency = 'GBP' basket.num_items = 1 # Ensure new product has different currency info = mock.Mock() info.price.currency = 'EUR' basket.strategy.fetch_for_product = mock.Mock( return_value=info) product = factories.ProductFactory() data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) def test_cannot_add_a_product_without_price(self): basket = factories.BasketFactory() product = factories.create_product(price=None) data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors['__all__'][0], 'This product cannot be added to the basket because a price ' 'could not be determined for it.', )
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import AnonymousUser from oscar.apps.basket import middleware class TestBasketMiddleware(TestCase): @staticmethod def get_response_for_test(request): return HttpResponse() def setUp(self): self.middleware = middleware.BasketMiddleware(self.get_response_for_test) self.request = RequestFactory().get('/') self.request.user = AnonymousUser() self.middleware(self.request) def test_basket_is_attached_to_request(self): self.assertTrue(hasattr(self.request, 'basket')) def test_strategy_is_attached_to_basket(self): self.assertTrue(hasattr(self.request.basket, 'strategy')) def test_strategy_is_attached_to_request(self): self.assertTrue(hasattr(self.request, 'strategy')) def test_get_cookie_basket_handles_invalid_signatures(self): request_factory = RequestFactory() request_factory.cookies['oscar_open_basket'] = '1:NOTAVALIDHASH' request = request_factory.get('/') request.cookies_to_delete = [] cookie_basket = self.middleware.get_cookie_basket("oscar_open_basket", request, None) self.assertEqual(None, cookie_basket) self.assertIn("oscar_open_basket", request.cookies_to_delete)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# -*- coding: utf-8 -*- from decimal import Decimal as D from django.test import TestCase from oscar.apps.basket.models import Basket from oscar.apps.catalogue.models import Option from oscar.apps.partner import availability, prices, strategy from oscar.test import factories from oscar.test.factories import ( BasketFactory, BasketLineAttributeFactory, OptionFactory, ProductFactory) class TestANewBasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() def test_has_zero_lines(self): self.assertEqual(0, self.basket.num_lines) def test_has_zero_items(self): self.assertEqual(0, self.basket.num_items) def test_doesnt_contain_vouchers(self): self.assertFalse(self.basket.contains_a_voucher) def test_can_be_edited(self): self.assertTrue(self.basket.can_be_edited) def test_is_empty(self): self.assertTrue(self.basket.is_empty) def test_is_not_submitted(self): self.assertFalse(self.basket.is_submitted) def test_has_no_applied_offers(self): self.assertEqual({}, self.basket.applied_offers()) class TestBasketLine(TestCase): def test_description(self): basket = BasketFactory() product = ProductFactory(title="A product") basket.add_product(product) line = basket.lines.first() self.assertEqual(line.description, "A product") def test_description_with_attributes(self): basket = BasketFactory() product = ProductFactory(title="A product") basket.add_product(product) line = basket.lines.first() BasketLineAttributeFactory( line=line, value='\u2603', option__name='with') self.assertEqual(line.description, "A product (with = '\u2603')") def test_create_line_reference(self): basket = BasketFactory() product = ProductFactory(title="A product") option = OptionFactory(name="product_option", code="product_option") option_product = ProductFactory(title='Asunción') options = [{'option': option, 'value': option_product}] basket.add_product(product, options=options) def test_basket_lines_queryset_is_ordered(self): # This is needed to make sure a formset is not performing the query # again with an order_by clause (losing all calculated discounts) basket = BasketFactory() product = ProductFactory(title="A product") another_product = ProductFactory(title="Another product") basket.add_product(product) basket.add_product(another_product) queryset = basket.all_lines() self.assertTrue(queryset.ordered) def test_line_tax_for_zero_tax_strategies(self): basket = Basket() basket.strategy = strategy.Default() product = factories.create_product() # Tax for the default strategy will be 0 factories.create_stockrecord( product, price_excl_tax=D('75.00'), num_in_stock=10) basket.add(product, 1) self.assertEqual(basket.lines.first().line_tax, D('0')) def test_line_tax_for_unknown_tax_strategies(self): class UnknownTaxStrategy(strategy.Default): """ A test strategy where the tax is not known """ def pricing_policy(self, product, stockrecord): return prices.FixedPrice('GBP', stockrecord.price_excl_tax, tax=None) basket = Basket() basket.strategy = UnknownTaxStrategy() product = factories.create_product() factories.create_stockrecord(product, num_in_stock=10) basket.add(product, 1) self.assertEqual(basket.lines.first().line_tax, None) class TestAddingAProductToABasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() self.product = factories.create_product() self.record = factories.create_stockrecord( currency='GBP', product=self.product, price_excl_tax=D('10.00')) self.purchase_info = factories.create_purchase_info(self.record) self.basket.add(self.product) def test_creates_a_line(self): self.assertEqual(1, self.basket.num_lines) def test_sets_line_prices(self): line = self.basket.lines.all()[0] self.assertEqual(line.price_incl_tax, self.purchase_info.price.incl_tax) self.assertEqual(line.price_excl_tax, self.purchase_info.price.excl_tax) def test_adding_negative_quantity(self): self.assertEqual(1, self.basket.num_lines) self.basket.add(self.product, quantity=4) self.assertEqual(5, self.basket.line_quantity(self.product, self.record)) self.basket.add(self.product, quantity=-10) self.assertEqual(0, self.basket.line_quantity(self.product, self.record)) def test_means_another_currency_product_cannot_be_added(self): product = factories.create_product() factories.create_stockrecord( currency='USD', product=product, price_excl_tax=D('20.00')) with self.assertRaises(ValueError): self.basket.add(product) def test_cannot_add_a_product_without_price(self): product = factories.create_product(price=None) with self.assertRaises(ValueError): self.basket.add(product) class TestANonEmptyBasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() self.product = factories.create_product() self.record = factories.create_stockrecord( self.product, price_excl_tax=D('10.00')) self.purchase_info = factories.create_purchase_info(self.record) self.basket.add(self.product, 10) def test_can_be_flushed(self): self.basket.flush() self.assertEqual(self.basket.num_items, 0) def test_returns_correct_product_quantity(self): self.assertEqual(10, self.basket.product_quantity( self.product)) def test_returns_correct_line_quantity_for_existing_product_and_stockrecord(self): self.assertEqual(10, self.basket.line_quantity( self.product, self.record)) def test_returns_zero_line_quantity_for_alternative_stockrecord(self): record = factories.create_stockrecord( self.product, price_excl_tax=D('5.00')) self.assertEqual(0, self.basket.line_quantity( self.product, record)) def test_returns_zero_line_quantity_for_missing_product_and_stockrecord(self): product = factories.create_product() record = factories.create_stockrecord( product, price_excl_tax=D('5.00')) self.assertEqual(0, self.basket.line_quantity( product, record)) def test_returns_correct_quantity_for_existing_product_and_stockrecord_and_options(self): product = factories.create_product() record = factories.create_stockrecord( product, price_excl_tax=D('5.00')) option = Option.objects.create(name="Message") options = [{"option": option, "value": "2"}] self.basket.add(product, options=options) self.assertEqual(0, self.basket.line_quantity( product, record)) self.assertEqual(1, self.basket.line_quantity( product, record, options)) def test_total_sums_product_totals(self): product = factories.create_product() factories.create_stockrecord( product, price_excl_tax=D('5.00')) self.basket.add(product, 1) self.assertEqual(self.basket.total_excl_tax, 105) def test_totals_for_free_products(self): basket = Basket() basket.strategy = strategy.Default() # Add a zero-priced product to the basket product = factories.create_product() factories.create_stockrecord( product, price_excl_tax=D('0.00'), num_in_stock=10) basket.add(product, 1) self.assertEqual(basket.lines.count(), 1) self.assertEqual(basket.total_excl_tax, 0) self.assertEqual(basket.total_incl_tax, 0) def test_basket_prices_calculation_for_unavailable_pricing(self): new_product = factories.create_product() factories.create_stockrecord( new_product, price_excl_tax=D('5.00')) self.basket.add(new_product, 1) class UnavailableProductStrategy(strategy.Default): """ A test strategy that makes a specific product unavailable """ def availability_policy(self, product, stockrecord): if product == new_product: return availability.Unavailable() return super().availability_policy(product, stockrecord) def pricing_policy(self, product, stockrecord): if product == new_product: return prices.Unavailable() return super().pricing_policy(product, stockrecord) self.basket.strategy = UnavailableProductStrategy() line = self.basket.all_lines()[1] self.assertEqual(line.get_warning(), "'D\xf9\uff4d\u03fb\u03d2 title' is no longer available") self.assertIsNone(line.line_price_excl_tax) self.assertIsNone(line.line_price_incl_tax) self.assertIsNone(line.line_price_excl_tax_incl_discounts) self.assertIsNone(line.line_price_incl_tax_incl_discounts) self.assertIsNone(line.line_tax) self.assertEqual(self.basket.total_excl_tax, 100) self.assertEqual(self.basket.total_incl_tax, 100) self.assertEqual(self.basket.total_excl_tax_excl_discounts, 100) self.assertEqual(self.basket.total_incl_tax_excl_discounts, 100) def test_max_allowed_quantity(self): self.basket.add_product(self.product, quantity=3) # max allowed here is 7 (20-10+3) with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=20): max_allowed, basket_threshold = self.basket.max_allowed_quantity() self.assertEqual(max_allowed, 7) self.assertEqual(basket_threshold, 20) # but we can also completely disable the threshold with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=None): max_allowed, basket_threshold = self.basket.max_allowed_quantity() self.assertEqual(max_allowed, None) self.assertEqual(basket_threshold, None) def test_is_quantity_allowed(self): with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=20): # 7 or below is possible allowed, message = self.basket.is_quantity_allowed(qty=7) self.assertTrue(allowed) self.assertIsNone(message) # but above it's not allowed, message = self.basket.is_quantity_allowed(qty=11) self.assertFalse(allowed) self.assertIsNotNone(message) with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=None): # with the treshold disabled all quantities are possible allowed, message = self.basket.is_quantity_allowed(qty=7) self.assertTrue(allowed) self.assertIsNone(message) allowed, message = self.basket.is_quantity_allowed(qty=5000) self.assertTrue(allowed) self.assertIsNone(message) class TestMergingTwoBaskets(TestCase): def setUp(self): self.product = factories.create_product() self.record = factories.create_stockrecord( self.product, price_excl_tax=D('10.00')) self.purchase_info = factories.create_purchase_info(self.record) self.main_basket = Basket() self.main_basket.strategy = strategy.Default() self.main_basket.add(self.product, quantity=2) self.merge_basket = Basket() self.merge_basket.strategy = strategy.Default() self.merge_basket.add(self.product, quantity=1) self.main_basket.merge(self.merge_basket) def test_doesnt_sum_quantities(self): self.assertEqual(1, self.main_basket.num_lines) def test_changes_status_of_merge_basket(self): self.assertEqual(Basket.MERGED, self.merge_basket.status) class TestASubmittedBasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() self.basket.submit() def test_has_correct_status(self): self.assertTrue(self.basket.is_submitted) def test_can_be_edited(self): self.assertFalse(self.basket.can_be_edited) class TestMergingAVoucherBasket(TestCase): def test_transfers_vouchers_to_new_basket(self): baskets = [factories.BasketFactory(), factories.BasketFactory()] voucher = factories.VoucherFactory() baskets[0].vouchers.add(voucher) baskets[1].merge(baskets[0]) self.assertEqual(1, baskets[1].vouchers.all().count())
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
import datetime from django.test import TestCase from oscar.apps.basket.reports import ( OpenBasketReportGenerator, SubmittedBasketReportGenerator) class TestBasketReports(TestCase): def test_open_report_doesnt_error(self): data = { 'start_date': datetime.date(2012, 5, 1), 'end_date': datetime.date(2012, 5, 17), 'formatter': 'CSV' } generator = OpenBasketReportGenerator(**data) generator.generate() def test_submitted_report_doesnt_error(self): data = { 'start_date': datetime.date(2012, 5, 1), 'end_date': datetime.date(2012, 5, 17), 'formatter': 'CSV' } generator = SubmittedBasketReportGenerator(**data) generator.generate()
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
import pytest from oscar.test.factories import ( BasketFactory, ConditionalOfferFactory, ProductFactory) @pytest.fixture def filled_basket(): basket = BasketFactory() product1 = ProductFactory() product2 = ProductFactory() basket.add_product(product1, quantity=10) basket.add_product(product2, quantity=20) return basket @pytest.mark.django_db class TestLineOfferConsumer(object): def test_consumed_no_offer(self, filled_basket): for line in filled_basket.all_lines(): assert line.consumer.consumed() == 0 def test_consumed_with_offer(self, filled_basket): offer1 = ConditionalOfferFactory(name='offer1') offer2 = ConditionalOfferFactory(name='offer2') offer1.exclusive = False offer2.exclusive = False for line in filled_basket.all_lines(): assert line.consumer.consumed(offer1) == 0 assert line.consumer.consumed(offer2) == 0 line1 = filled_basket.all_lines()[0] line2 = filled_basket.all_lines()[1] line1.consumer.consume(1, offer1) assert line1.consumer.consumed() == 1 assert line1.consumer.consumed(offer1) == 1 assert line1.consumer.consumed(offer2) == 0 line1.consumer.consume(9, offer1) assert line1.consumer.consumed() == line1.quantity assert line1.consumer.consumed(offer1) == line1.quantity assert line1.consumer.consumed(offer2) == 0 line1.consumer.consume(99, offer1) assert line1.consumer.consumed(offer1) == line1.quantity assert line1.consumer.consumed(offer2) == 0 line1.consumer.consume(1, offer2) line2.consumer.consume(1, offer2) assert line1.consumer.consumed(offer2) == 1 assert line2.consumer.consumed(offer2) == 1 def test_consume(self, filled_basket): line = filled_basket.all_lines()[0] line.consume(1) assert line.quantity_with_discount == 1 line.consume(99) assert line.quantity_with_discount == 10 def test_consumed_with_exclusive_offer(self, filled_basket): offer1 = ConditionalOfferFactory(name='offer1') offer2 = ConditionalOfferFactory(name='offer2') offer3 = ConditionalOfferFactory(name='offer3') offer1.exclusive = True offer2.exclusive = False offer3.exclusive = False for line in filled_basket.all_lines(): assert line.consumer.consumed(offer1) == 0 assert line.consumer.consumed(offer2) == 0 line1 = filled_basket.all_lines()[0] line2 = filled_basket.all_lines()[1] line1.consumer.consume(1, offer1) assert line1.is_available_for_offer_discount(offer2) is True line1.consumer.consume(99, offer1) assert line1.is_available_for_offer_discount(offer2) is False line2.consumer.consume(1, offer2) assert line2.is_available_for_offer_discount(offer1) is True line2.consumer.consume(99, offer2) assert line2.is_available_for_offer_discount(offer1) is False assert line2.is_available_for_offer_discount(offer3) is True
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.contrib.messages import get_messages from django.test import TestCase from django.urls import reverse from oscar.apps.basket import views from oscar.test import factories from tests.fixtures import RequestFactory class TestVoucherAddView(TestCase): def test_get(self): request = RequestFactory().get('/') view = views.VoucherAddView.as_view() response = view(request) self.assertEqual(response.status_code, 302) def _get_voucher_message(self, request): return '\n'.join(str(m.message) for m in get_messages(request)) def test_post_valid(self): voucher = factories.VoucherFactory() self.assertTrue(voucher.is_active()) data = { 'code': voucher.code } request = RequestFactory().post('/', data=data) request.basket.save() view = views.VoucherAddView.as_view() response = view(request) self.assertEqual(response.status_code, 302) voucher = voucher.__class__.objects.get(pk=voucher.pk) self.assertEqual(voucher.num_basket_additions, 1, msg=self._get_voucher_message(request)) def test_post_valid_from_set(self): voucherset = factories.VoucherSetFactory() voucher = voucherset.vouchers.first() self.assertTrue(voucher.is_active()) data = { 'code': voucher.code } request = RequestFactory().post('/', data=data) request.basket.save() view = views.VoucherAddView.as_view() response = view(request) self.assertEqual(response.status_code, 302) voucher = voucher.__class__.objects.get(pk=voucher.pk) self.assertEqual(voucher.num_basket_additions, 1, msg=self._get_voucher_message(request)) self.assertEqual(voucherset.num_basket_additions, 1) class TestVoucherRemoveView(TestCase): def test_post_valid(self): voucher = factories.VoucherFactory(num_basket_additions=5) data = { 'code': voucher.code } request = RequestFactory().post('/', data=data) request.basket.save() request.basket.vouchers.add(voucher) view = views.VoucherRemoveView.as_view() response = view(request, pk=voucher.pk) self.assertEqual(response.status_code, 302) voucher = voucher.__class__.objects.get(pk=voucher.pk) self.assertEqual(voucher.num_basket_additions, 4) def test_post_with_missing_voucher(self): """ If the voucher is missing, verify the view queues a message and redirects. """ pk = '12345' view = views.VoucherRemoveView.as_view() request = RequestFactory().post('/') request.basket.save() response = view(request, pk=pk) self.assertEqual(response.status_code, 302) actual = list(get_messages(request))[-1].message expected = "No voucher found with id '{}'".format(pk) self.assertEqual(actual, expected) class TestBasketSummaryView(TestCase): def setUp(self): self.url = reverse('basket:summary') self.country = factories.CountryFactory() self.user = factories.UserFactory() def test_default_shipping_address(self): user_address = factories.UserAddressFactory( country=self.country, user=self.user, is_default_for_shipping=True ) request = RequestFactory().get(self.url, user=self.user) view = views.BasketView(request=request) self.assertEquals(view.get_default_shipping_address(), user_address) def test_default_shipping_address_for_anonymous_user(self): request = RequestFactory().get(self.url) view = views.BasketView(request=request) self.assertIsNone(view.get_default_shipping_address())
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from decimal import Decimal as D from unittest import mock from django.test import TestCase from oscar.apps.checkout import calculators from oscar.core import prices class TestOrderTotalCalculator(TestCase): def setUp(self): self.calculator = calculators.OrderTotalCalculator() def test_returns_correct_totals_when_tax_is_not_known(self): basket = mock.Mock() basket.total_excl_tax = D('10.00') basket.is_tax_known = False shipping_charge = prices.Price( currency=basket.currency, excl_tax=D('5.00')) total = self.calculator.calculate(basket, shipping_charge) self.assertIsInstance(total, prices.Price) self.assertEqual(D('10.00') + D('5.00'), total.excl_tax) self.assertFalse(total.is_tax_known) def test_returns_correct_totals_when_tax_is_known(self): basket = mock.Mock() basket.total_excl_tax = D('10.00') basket.total_incl_tax = D('12.00') basket.is_tax_known = True shipping_charge = prices.Price( currency=basket.currency, excl_tax=D('5.00'), tax=D('0.50')) total = self.calculator.calculate(basket, shipping_charge) self.assertIsInstance(total, prices.Price) self.assertEqual(D('10.00') + D('5.00'), total.excl_tax) self.assertTrue(total.is_tax_known) self.assertEqual(D('12.00') + D('5.50'), total.incl_tax) self.assertEqual(D('2.00') + D('0.50'), total.tax)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings from oscar.apps.address.models import Country from oscar.apps.checkout.forms import ShippingAddressForm from oscar.test.factories import CountryFactory class AnotherShippingAddressForm(ShippingAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' }, 'another_phone_number': { 'required': False, 'help_text': 'Another phone number help text', 'max_length': 32, 'label': 'Another phone number' }, } class TestShippingAddressForm(TestCase): minimal_data = { 'first_name': 'Bärry', 'last_name': 'Chuckle', 'line1': '1 King St', 'line4': 'Gothám', 'postcode': 'N1 7RR' } def setUp(self): CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) def test_removes_country_field(self): self.assertTrue('country' not in ShippingAddressForm().fields) def test_keeps_country_field(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) self.assertTrue('country' in ShippingAddressForm().fields) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('last_name', 'postcode')) def test_required_fields_validated(self): form = ShippingAddressForm() self.assertTrue(form.fields['last_name'].required) self.assertTrue(form.fields['postcode'].required) self.assertFalse(form.fields['first_name'].required) self.assertFalse(form.fields['line2'].required) self.assertFalse(form.fields['line3'].required) self.assertFalse(form.fields['line4'].required) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('phone_number',)) def test_required_phone_number_validated(self): # This needs a separate test because of the logic in PhoneNumberMixin form = ShippingAddressForm() self.assertTrue(form.fields['phone_number'].required) # Tests where the country field is hidden def test_is_valid_without_phone_number(self): self.assertTrue(ShippingAddressForm(self.minimal_data).is_valid()) def test_only_accepts_british_local_phone_number(self): data = self.minimal_data.copy() data['phone_number'] = '07 914721389' # local UK number self.assertTrue(ShippingAddressForm(data).is_valid()) data['phone_number'] = '0176 968 426 71' # local German number self.assertFalse(ShippingAddressForm(data).is_valid()) def test_only_accepts_british_local_phone_numbers(self): data = self.minimal_data.copy() # Both numbers are British local numbers data['phone_number'] = '07 914721389' data['another_phone_number'] = '0344493 0787' # British Airways self.assertTrue(AnotherShippingAddressForm(data).is_valid()) # Both numbers are local German numbers data['phone_number'] = '0176 968 426 71' data['another_phone_number'] = '07032 15 49225' # IBM Germany self.assertFalse(AnotherShippingAddressForm(data).is_valid()) # One number is British number, another is German number data['phone_number'] = '07 914721389' data['another_phone_number'] = '0176 968 426 71' self.assertFalse(AnotherShippingAddressForm(data).is_valid()) # As previous case, but numbers are reversed data['phone_number'] = '0176 968 426 71' data['another_phone_number'] = '07 914721389' self.assertFalse(AnotherShippingAddressForm(data).is_valid()) def test_is_valid_with_international_phone_number(self): data = self.minimal_data.copy() data['phone_number'] = '+49 176 968426 71' form = ShippingAddressForm(data) self.assertTrue(form.is_valid()) def test_is_valid_with_international_phone_numbers(self): data = self.minimal_data.copy() data['phone_number'] = '+49 176 968426 71' data['another_phone_number'] = '+49-1805-426452' form = AnotherShippingAddressForm(data) self.assertTrue(form.is_valid()) # Tests where the country field exists def test_needs_country_data(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) self.assertFalse(ShippingAddressForm(self.minimal_data).is_valid()) data = self.minimal_data.copy() data['country'] = Country.objects.get(iso_3166_1_a2='GB').pk self.assertTrue(ShippingAddressForm(data).is_valid()) def test_only_accepts_local_phone_number_when_country_matches(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) data = self.minimal_data.copy() data['phone_number'] = '07 914721389' # local UK number data['country'] = Country.objects.get(iso_3166_1_a2='DE').pk self.assertFalse(ShippingAddressForm(data).is_valid()) data['country'] = Country.objects.get(iso_3166_1_a2='GB').pk self.assertTrue(ShippingAddressForm(data).is_valid()) def test_only_accepts_local_phone_numbers_when_country_matches(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) data = self.minimal_data.copy() # Local UK numbers data['phone_number'] = '07 914721389' data['another_phone_number'] = '0344493 0787' data['country'] = Country.objects.get(iso_3166_1_a2='DE').pk self.assertFalse(ShippingAddressForm(data).is_valid()) data['country'] = Country.objects.get(iso_3166_1_a2='GB').pk self.assertTrue(ShippingAddressForm(data).is_valid()) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('phone_number',)) def test_local_phone_number_invalid_without_country(self): # Add another country, so we have two. CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) data = self.minimal_data.copy() data['phone_number'] = '07 914721389' # User hasn't selected a country. Because there are multiple country # choices we should not accept the local number. form = ShippingAddressForm(data) self.assertFalse(form.is_valid()) self.assertIn('phone_number', form.errors)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from decimal import Decimal as D from unittest import mock from django.http import HttpRequest from django.test import TestCase from django.test.utils import override_settings from oscar.apps.checkout.calculators import OrderTotalCalculator from oscar.apps.checkout.mixins import CheckoutSessionMixin, OrderPlacementMixin from oscar.apps.checkout.exceptions import FailedPreCondition from oscar.core.loading import get_model from oscar.test import factories from oscar.test.basket import add_product from oscar.test.utils import RequestFactory from oscar.apps.shipping.methods import FixedPrice, Free Order = get_model('order', 'Order') class TestOrderPlacementMixin(TestCase): def test_returns_none_when_no_shipping_address_passed_to_creation_method(self): address = OrderPlacementMixin().create_shipping_address( user=mock.Mock(), shipping_address=None) self.assertEqual(address, None) def test_update_address_book(self): basket = factories.create_basket(empty=True) user = factories.UserFactory() add_product(basket, D('12.00')) shipping_method = FixedPrice(D('5.00'), D('5.00')) billing_address = factories.BillingAddressFactory(line1='1 Boardwalk Place', line2='Trafalgar Way', line3='Tower Hamlets', line4='London') shipping_address = factories.ShippingAddressFactory(line1='Knightsbridge', line2='159', line4='London') shipping_charge = shipping_method.calculate(basket) order_total = OrderTotalCalculator().calculate(basket, shipping_charge) order_submission_data = {'user': user, 'order_number': '12345', 'basket': basket, 'shipping_address': shipping_address, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'billing_address': billing_address, 'order_total': order_total} OrderPlacementMixin().place_order(**order_submission_data) self.assertEqual(user.addresses.filter(hash=billing_address.generate_hash()).count(), 1) self.assertEqual(user.addresses.filter(hash=shipping_address.generate_hash()).count(), 1) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 1) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 1) order_submission_data['order_number'] = '12346' OrderPlacementMixin().place_order(**order_submission_data) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 2) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 2) order_submission_data.pop('billing_address', None) order_submission_data['order_number'] = '123457' OrderPlacementMixin().place_order(**order_submission_data) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 2) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 3) shipping_address.line2 = '160' order_submission_data['billing_address'] = billing_address order_submission_data['order_number'] = '123458' OrderPlacementMixin().place_order(**order_submission_data) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 3) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 1) @override_settings(SITE_ID='') def test_multi_site(self): basket = factories.create_basket(empty=True) site1 = factories.SiteFactory() site2 = factories.SiteFactory() request = HttpRequest() request.META['SERVER_PORT'] = 80 request.META['SERVER_NAME'] = site1.domain user = factories.UserFactory() add_product(basket, D('12.00')) shipping_method = Free() shipping_charge = shipping_method.calculate(basket) order_total = OrderTotalCalculator().calculate(basket, shipping_charge) billing_address = factories.BillingAddressFactory() shipping_address = factories.ShippingAddressFactory() order_submission_data = {'user': user, 'order_number': '12345', 'basket': basket, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'order_total': order_total, 'billing_address': billing_address, 'shipping_address': shipping_address, 'request': request} OrderPlacementMixin().place_order(**order_submission_data) order1 = Order.objects.get(number='12345') self.assertEqual(order1.site, site1) add_product(basket, D('12.00')) request.META['SERVER_NAME'] = site2.domain order_submission_data['order_number'] = '12346' order_submission_data['request'] = request OrderPlacementMixin().place_order(**order_submission_data) order2 = Order.objects.get(number='12346') self.assertEqual(order2.site, site2) def test_multiple_payment_events(self): basket = factories.create_basket(empty=True) user = factories.UserFactory() add_product(basket, D('100.00')) order_placement = OrderPlacementMixin() order_placement.add_payment_event('Gift Card Payment', D('10')) order_placement.add_payment_event('Credit Card Payment', D('90')) shipping_method = Free() shipping_charge = shipping_method.calculate(basket) order_total = OrderTotalCalculator().calculate(basket, shipping_charge) billing_address = factories.BillingAddressFactory() shipping_address = factories.ShippingAddressFactory() order_submission_data = {'user': user, 'order_number': '12345', 'basket': basket, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'order_total': order_total, 'billing_address': billing_address, 'shipping_address': shipping_address} order_placement.place_order(**order_submission_data) order1 = Order.objects.get(number='12345') self.assertEqual(order1.payment_events.count(), 2) event1 = order1.payment_events.all()[0] event2 = order1.payment_events.all()[1] self.assertEqual(event1.event_type.name, 'Credit Card Payment') self.assertEqual(event1.amount, D('90')) self.assertEqual(event1.lines.count(), 1) self.assertEqual(event2.event_type.name, 'Gift Card Payment') self.assertEqual(event2.amount, D('10')) self.assertEqual(event2.lines.count(), 1) class TestCheckoutSessionMixin(TestCase): def setUp(self): self.request = RequestFactory().get('/') self.product = factories.create_product(num_in_stock=10) self.stock_record = self.product.stockrecords.first() def add_product_to_basket(self, product, quantity=1): self.request.basket.add_product(product, quantity=quantity) self.assertEqual(len(self.request.basket.all_lines()), 1) self.assertEqual(self.request.basket.all_lines()[0].product, product) def test_check_basket_is_valid_no_stock_available(self): self.add_product_to_basket(self.product) CheckoutSessionMixin().check_basket_is_valid(self.request) self.stock_record.allocate(10) self.stock_record.save() with self.assertRaises(FailedPreCondition): CheckoutSessionMixin().check_basket_is_valid(self.request) def test_check_basket_is_valid_stock_exceeded(self): self.add_product_to_basket(self.product) CheckoutSessionMixin().check_basket_is_valid(self.request) self.request.basket.add_product(self.product, quantity=11) with self.assertRaises(FailedPreCondition): CheckoutSessionMixin().check_basket_is_valid(self.request)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from unittest import mock from django.test import TestCase from django.test.client import RequestFactory from django.contrib.sessions.middleware import SessionMiddleware from oscar.apps.checkout.utils import CheckoutSessionData class TestCheckoutSession(TestCase): """ oscar.apps.checkout.utils.CheckoutSessionData """ def setUp(self): request = RequestFactory().get('/') SessionMiddleware().process_request(request) self.session_data = CheckoutSessionData(request) def test_allows_data_to_be_written_and_read_out(self): self.session_data._set('namespace', 'key', 'value') self.assertEqual('value', self.session_data._get('namespace', 'key')) def test_allows_set_data_can_be_unset(self): self.session_data._set('namespace', 'key', 'value') self.session_data._unset('namespace', 'key') self.assertIsNone(self.session_data._get('namespace', 'key')) def test_stores_guest_email(self): self.session_data.set_guest_email('a@a.com') self.assertEqual('a@a.com', self.session_data.get_guest_email()) def test_allows_a_namespace_to_be_flushed(self): self.session_data._set('ns', 'a', 1) self.session_data._set('ns', 'b', 2) self.session_data._flush_namespace('ns') self.assertIsNone(self.session_data._get('ns', 'a')) self.assertIsNone(self.session_data._get('ns', 'b')) def test_allows_bill_to_user_address(self): address = mock.Mock() address.id = 1 self.session_data.bill_to_user_address(address) self.assertEqual(1, self.session_data.billing_user_address_id())
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse from oscar.test.factories import OrderFactory class ThankYouViewTestCase(TestCase): @override_settings(OSCAR_ALLOW_ANON_CHECKOUT=True) def test_analytics_event_triggered_only_on_first_view(self): order = OrderFactory() session = self.client.session # Put the order ID in the session, mimicking a completed order, # so that we can reach the thank you page. session['checkout_order_id'] = order.pk session.save() r1 = self.client.get(reverse('checkout:thank-you'), follow=True) self.assertTrue(r1.context['send_analytics_event']) # Request the view a second time r2 = self.client.get(reverse('checkout:thank-you'), follow=True) self.assertFalse(r2.context['send_analytics_event'])
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# coding=utf-8 """ AutoSlugField taken from django-extensions at 15d3eb305957cee4768dd86e44df1bdad341a10e Uses Oscar's slugify function instead of Django's Copyright (c) 2007 Michael Trier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from django.db import models from django.test import TestCase from django.test.utils import override_settings from oscar.core.loading import get_model SluggedTestModel = get_model('model_tests_app', 'sluggedtestmodel') ChildSluggedTestModel = get_model('model_tests_app', 'childsluggedtestmodel') CustomSluggedTestModel = get_model('model_tests_app', 'CustomSluggedTestModel') class AutoSlugFieldTest(TestCase): def tearDown(self): super().tearDown() SluggedTestModel.objects.all().delete() def test_auto_create_slug(self): m = SluggedTestModel(title='foo') m.save() self.assertEqual(m.slug, 'foo') def test_auto_create_next_slug(self): m = SluggedTestModel(title='foo') m.save() m = SluggedTestModel(title='foo') m.save() self.assertEqual(m.slug, 'foo-2') def test_auto_create_slug_with_number(self): m = SluggedTestModel(title='foo 2012') m.save() self.assertEqual(m.slug, 'foo-2012') def test_auto_update_slug_with_number(self): m = SluggedTestModel(title='foo 2012') m.save() m.save() self.assertEqual(m.slug, 'foo-2012') def test_auto_create_unicode_slug(self): with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): m = SluggedTestModel(title='Château Margaux 1960') m.save() self.assertEqual(m.slug, 'château-margaux-1960') def test_auto_create_next_unicode_slug(self): with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): m1 = SluggedTestModel(title='Château Margaux 1960') m1.save() m2 = SluggedTestModel(title='Château Margaux 1960') m2.save() self.assertEqual(m2.slug, 'château-margaux-1960-2') def test_switch_to_unicode_slug(self): m = SluggedTestModel(title='Château Margaux 1960') m.save() self.assertEqual(m.slug, 'chateau-margaux-1960') with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): m = SluggedTestModel(title='Château Margaux 1960') m.save() self.assertEqual(m.slug, 'château-margaux-1960') def test_autoslugfield_allow_unicode_kwargs_precedence(self): from oscar.models.fields import AutoSlugField with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): autoslug_field = AutoSlugField(populate_from='title', allow_unicode=False) self.assertFalse(autoslug_field.allow_unicode) autoslug_field = AutoSlugField(populate_from='title') self.assertTrue(autoslug_field.allow_unicode) def test_update_slug(self): m = SluggedTestModel(title='foo') m.save() self.assertEqual(m.slug, 'foo') # update m instance without using `save' SluggedTestModel.objects.filter(pk=m.pk).update(slug='foo-2012') # update m instance with new data from the db m = SluggedTestModel.objects.get(pk=m.pk) self.assertEqual(m.slug, 'foo-2012') m.save() self.assertEqual(m.title, 'foo') self.assertEqual(m.slug, 'foo-2012') # Check slug is not overwrite m.title = 'bar' m.save() self.assertEqual(m.title, 'bar') self.assertEqual(m.slug, 'foo-2012') def test_simple_slug_source(self): m = SluggedTestModel(title='-foo') m.save() self.assertEqual(m.slug, 'foo') n = SluggedTestModel(title='-foo') n.save() self.assertEqual(n.slug, 'foo-2') n.save() self.assertEqual(n.slug, 'foo-2') def test_empty_slug_source(self): # regression test m = SluggedTestModel(title='') m.save() self.assertEqual(m.slug, '-2') n = SluggedTestModel(title='') n.save() self.assertEqual(n.slug, '-3') n.save() self.assertEqual(n.slug, '-3') def test_inheritance_creates_next_slug(self): m = SluggedTestModel(title='foo') m.save() n = ChildSluggedTestModel(title='foo') n.save() self.assertEqual(n.slug, 'foo-2') o = SluggedTestModel(title='foo') o.save() self.assertEqual(o.slug, 'foo-3') def test_separator_and_uppercase_options(self): m = CustomSluggedTestModel(title="Password reset") m.save() self.assertEqual(m.slug, 'PASSWORD_RESET') m = CustomSluggedTestModel(title="Password reset") m.save() self.assertEqual(m.slug, 'PASSWORD_RESET_2') def test_migration(self): """ Tests making migrations with Django 1.7+'s migration framework """ import oscar from django.db import migrations from django.db.migrations.writer import MigrationWriter from oscar.models.fields import AutoSlugField fields = { 'autoslugfield': AutoSlugField(populate_from='otherfield'), } migration = type(str("Migration"), (migrations.Migration,), { "operations": [ migrations.CreateModel("MyModel", tuple(fields.items()), {'populate_from': 'otherfield'}, (models.Model,)), ], }) writer = MigrationWriter(migration) output = writer.as_string() if isinstance(output, str): output = output.encode('utf-8') # We don't test the output formatting - that's too fragile. # Just make sure it runs for now, and that things look alright. context = { 'migrations': migrations, 'oscar': oscar, } result = self.safe_exec(output, context=context) self.assertIn("Migration", result) def safe_exec(self, string, value=None, context=None): loc = {} g = globals() g.update(context) try: exec(string, g, loc) except Exception as e: if value: self.fail("Could not exec %r (from value %r): %s" % ( string.strip(), value, e)) else: self.fail("Could not exec %r: %s" % (string.strip(), e)) return loc
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# -*- coding: utf-8 -*- import codecs import datetime import io import os from tempfile import NamedTemporaryFile from django.utils.encoding import smart_text from django.test import TestCase, override_settings from oscar.core.compat import UnicodeCSVWriter, existing_user_fields class unicodeobj(object): def __init__(self, s): self.s = s def __str__(self): return self.s class TestExistingUserFields(TestCase): def test_order(self): fields = existing_user_fields(['email', 'first_name', 'last_name']) self.assertEqual(fields, ['email', 'first_name', 'last_name']) class TestUnicodeCSVWriter(TestCase): def test_can_write_different_values(self): writer = UnicodeCSVWriter(open_file=io.StringIO()) s = 'ünįcodē' rows = [[s, unicodeobj(s), 123, datetime.date.today()], ] writer.writerows(rows) self.assertRaises(TypeError, writer.writerows, [object()]) def test_context_manager(self): tmp_file = NamedTemporaryFile() with UnicodeCSVWriter(filename=tmp_file.name) as writer: s = 'ünįcodē' rows = [[s, unicodeobj(s), 123, datetime.date.today()], ] writer.writerows(rows) def test_csv_write_output(self): tmp_file = NamedTemporaryFile(delete=False) with UnicodeCSVWriter(filename=tmp_file.name) as writer: s = 'ünįcodē' row = [s, 123, 'foo-bar'] writer.writerows([row]) with open(tmp_file.name, 'r') as read_file: content = smart_text(read_file.read(), encoding='utf-8').strip() self.assertEqual(content, 'ünįcodē,123,foo-bar') # Clean up os.unlink(tmp_file.name) @override_settings(OSCAR_CSV_INCLUDE_BOM=True) def test_bom_write_with_open_file(self): csv_file = NamedTemporaryFile(delete=False) with open(csv_file.name, 'w') as open_file: writer = UnicodeCSVWriter(open_file=open_file, encoding="utf-8") s = 'ünįcodē' row = [s, 123, datetime.date.today()] writer.writerows([row]) with open(csv_file.name, 'rb') as read_file: self.assertTrue(read_file.read().startswith(codecs.BOM_UTF8)) # Clean up os.unlink(csv_file.name) @override_settings(OSCAR_CSV_INCLUDE_BOM=True) def test_bom_write_with_filename(self): csv_file = NamedTemporaryFile(delete=False) with UnicodeCSVWriter(filename=csv_file.name, encoding="utf-8") as writer: s = 'ünįcodē' row = [s, 123, datetime.date.today()] writer.writerows([row]) with open(csv_file.name, 'rb') as read_file: self.assertTrue(read_file.read().startswith(codecs.BOM_UTF8)) # Clean up os.unlink(csv_file.name) @override_settings(OSCAR_CSV_INCLUDE_BOM=True) def test_bom_not_written_for_other_encodings(self): csv_file = NamedTemporaryFile(delete=False) with UnicodeCSVWriter(filename=csv_file.name, encoding="ascii") as writer: s = 'boring ascii' row = [s, 123, datetime.date.today()] writer.writerows([row]) with open(csv_file.name, 'rb') as read_file: self.assertFalse(read_file.read().startswith(codecs.BOM_UTF8)) # Clean up os.unlink(csv_file.name)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
import pytest from django.conf import settings from django.test import TestCase from oscar.core import customisation VALID_FOLDER_PATH = 'tests/_site/apps' class TestUtilities(TestCase): def test_subfolder_extraction(self): folders = list(customisation.subfolders('/var/www/eggs')) self.assertEqual(folders, ['/var', '/var/www', '/var/www/eggs']) def test_raises_exception_for_nonexistant_app_label(): with pytest.raises(ValueError): customisation.fork_app('sillytown', 'somefolder') def test_raises_exception_if_app_has_already_been_forked(): # We piggyback on another test which means a custom app is already in # the settings we use for the test suite. We just check that's still # the case here. assert 'tests._site.apps.partner' in settings.INSTALLED_APPS with pytest.raises(ValueError): customisation.fork_app('partner', VALID_FOLDER_PATH) def test_creates_new_folder(tmpdir): path = tmpdir.mkdir('fork') customisation.fork_app('order', str(path)) path.join('order').ensure_dir() def test_creates_init_file(tmpdir): path = tmpdir.mkdir('fork') customisation.fork_app('order', str(path)) path.join('order').join('__init__.py').ensure() def test_handles_dashboard_app(tmpdir): # Dashboard apps are fiddly as they aren't identified by a single app # label. path = tmpdir.mkdir('fork') customisation.fork_app('dashboard.catalogue', str(path)) # Check __init__.py created (and supporting folders) path.join('dashboard').join('catalogue').join('__init__.py').ensure() def test_creates_models_and_admin_file(tmpdir): path = tmpdir.mkdir('fork') customisation.fork_app('order', str(path)) for module, expected_string in [ ('models', 'from oscar.apps.order.models import *'), ('admin', 'from oscar.apps.order.admin import *'), ('config', 'OrderConfig') ]: filepath = path.join('order').join('%s.py' % module) filepath.ensure() contents = filepath.read() assert expected_string in contents def test_copies_in_migrations_when_needed(tmpdir): path = tmpdir.mkdir('fork') for app, has_models in [('order', True), ('search', False)]: customisation.fork_app(app, str(path)) native_migration_path = path.join(app).join('migrations') assert has_models == native_migration_path.check() def test_dashboard_app_config(tmpdir, monkeypatch): path = tmpdir.mkdir('fork') customisation.fork_app('dashboard', str(path)) path.join('__init__.py').write('') monkeypatch.syspath_prepend(str(tmpdir)) config_module = __import__( '%s.dashboard.config' % path.basename, fromlist=['DashboardConfig'] ) assert hasattr(config_module, 'DashboardConfig')
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
import warnings from django.contrib.auth.models import AnonymousUser, Permission from django.test import TestCase from oscar.core.decorators import deprecated from oscar.test import factories from oscar.views.decorators import check_permissions class TestPermissionsDecorator(TestCase): def test_empty_permissions_passes(self): user = factories.UserFactory.build() self.assertTrue(check_permissions(user, [])) def test_properties_are_checked(self): staff_user = factories.UserFactory.build(is_staff=True) non_staff_user = factories.UserFactory.build(is_staff=False) self.assertTrue(check_permissions(staff_user, ['is_staff'])) self.assertFalse(check_permissions(non_staff_user, ['is_staff'])) def test_methods_are_checked(self): anonymous_user = AnonymousUser() known_user = factories.UserFactory.build() self.assertTrue(check_permissions(anonymous_user, ['is_anonymous'])) self.assertFalse(check_permissions(known_user, ['is_anonymous'])) def test_permissions_are_checked(self): user_with_perm = factories.UserFactory() user_without_perm = factories.UserFactory() perm = Permission.objects.get( content_type__app_label='address', codename='add_country') user_with_perm.user_permissions.add(perm) self.assertTrue( check_permissions(user_with_perm, ['address.add_country'])) self.assertFalse( check_permissions(user_without_perm, ['address.add_country'])) class TestDeprecatedDecorator(TestCase): def test_decorate_function(self): @deprecated def func(): return True with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") self.assertTrue(func()) assert len(caught) == 1 assert issubclass(caught[0].category, DeprecationWarning) def test_decorate_class(self): class Cls(object): val = False def __init__(self): self.val = True Deprecated = deprecated(Cls) # noqa with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") obj = Deprecated() self.assertTrue(obj.val) assert len(caught) == 1 assert issubclass(caught[0].category, DeprecationWarning) def test_subclass_decorated(self): class Cls(object): val = False def __init__(self): self.val = True Deprecated = deprecated(Cls) # noqa class SubCls(Deprecated): pass with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") obj = SubCls() self.assertTrue(obj.val) assert len(caught) == 1 assert issubclass(caught[0].category, DeprecationWarning)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from os.path import dirname import sys from django.test import override_settings, TestCase from django.conf import settings import oscar from oscar.core.loading import ( get_model, AppNotFoundError, get_classes, get_class, get_class_loader, ClassNotFoundError) from tests import temporary_python_path from tests._site.loader import DummyClass class TestClassLoading(TestCase): """ Oscar's class loading utilities """ def test_load_oscar_classes_correctly(self): Product, Category = get_classes('catalogue.models', ('Product', 'Category')) self.assertEqual('oscar.apps.catalogue.models', Product.__module__) self.assertEqual('oscar.apps.catalogue.models', Category.__module__) def test_load_oscar_class_correctly(self): Product = get_class('catalogue.models', 'Product') self.assertEqual('oscar.apps.catalogue.models', Product.__module__) def test_load_oscar_class_from_dashboard_subapp(self): ReportForm = get_class('dashboard.reports.forms', 'ReportForm') self.assertEqual('oscar.apps.dashboard.reports.forms', ReportForm.__module__) def test_raise_exception_when_bad_appname_used(self): with self.assertRaises(AppNotFoundError): get_classes('fridge.models', ('Product', 'Category')) def test_raise_exception_when_bad_classname_used(self): with self.assertRaises(ClassNotFoundError): get_class('catalogue.models', 'Monkey') def test_raise_importerror_if_app_raises_importerror(self): """ This tests that Oscar doesn't fall back to using the Oscar catalogue app if the overriding app throws an ImportError. """ apps = list(settings.INSTALLED_APPS) apps[apps.index('oscar.apps.catalogue')] = 'tests._site.import_error_app.catalogue' with override_settings(INSTALLED_APPS=apps): with self.assertRaises(ImportError): get_class('catalogue.app', 'CatalogueApplication') class ClassLoadingWithLocalOverrideTests(TestCase): def setUp(self): self.installed_apps = list(settings.INSTALLED_APPS) self.installed_apps[self.installed_apps.index('oscar.apps.shipping')] = 'tests._site.shipping' def test_loading_class_defined_in_local_module(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Free,) = get_classes('shipping.methods', ('Free',)) self.assertEqual('tests._site.shipping.methods', Free.__module__) def test_loading_class_which_is_not_defined_in_local_module(self): with override_settings(INSTALLED_APPS=self.installed_apps): (FixedPrice,) = get_classes('shipping.methods', ('FixedPrice',)) self.assertEqual('oscar.apps.shipping.methods', FixedPrice.__module__) def test_loading_class_from_module_not_defined_in_local_app(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Repository,) = get_classes('shipping.repository', ('Repository',)) self.assertEqual('oscar.apps.shipping.repository', Repository.__module__) def test_loading_classes_defined_in_both_local_and_oscar_modules(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Free, FixedPrice) = get_classes('shipping.methods', ('Free', 'FixedPrice')) self.assertEqual('tests._site.shipping.methods', Free.__module__) self.assertEqual('oscar.apps.shipping.methods', FixedPrice.__module__) def test_loading_classes_with_root_app(self): import tests._site.shipping path = dirname(dirname(tests._site.shipping.__file__)) with temporary_python_path([path]): self.installed_apps[ self.installed_apps.index('tests._site.shipping')] = 'shipping' with override_settings(INSTALLED_APPS=self.installed_apps): (Free,) = get_classes('shipping.methods', ('Free',)) self.assertEqual('shipping.methods', Free.__module__) def test_overriding_view_is_possible_without_overriding_app(self): from oscar.apps.customer.app import application, CustomerApplication # If test fails, it's helpful to know if it's caused by order of # execution self.assertEqual(CustomerApplication().summary_view.__module__, 'tests._site.apps.customer.views') self.assertEqual(application.summary_view.__module__, 'tests._site.apps.customer.views') class ClassLoadingWithLocalOverrideWithMultipleSegmentsTests(TestCase): def setUp(self): self.installed_apps = list(settings.INSTALLED_APPS) self.installed_apps[self.installed_apps.index('oscar.apps.shipping')] = 'tests._site.apps.shipping' def test_loading_class_defined_in_local_module(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Free,) = get_classes('shipping.methods', ('Free',)) self.assertEqual('tests._site.apps.shipping.methods', Free.__module__) class TestGetCoreAppsFunction(TestCase): """ oscar.get_core_apps function """ def test_returns_core_apps_when_no_overrides_specified(self): apps = oscar.get_core_apps() self.assertEqual(oscar.OSCAR_CORE_APPS, apps) def test_uses_non_dashboard_override_when_specified(self): apps = oscar.get_core_apps(overrides=['apps.shipping']) self.assertTrue('apps.shipping' in apps) self.assertTrue('oscar.apps.shipping' not in apps) def test_uses_dashboard_override_when_specified(self): apps = oscar.get_core_apps(overrides=['apps.dashboard.catalogue']) self.assertTrue('apps.dashboard.catalogue' in apps) self.assertTrue('oscar.apps.dashboard.catalogue' not in apps) self.assertTrue('oscar.apps.catalogue' in apps) class TestOverridingCoreApps(TestCase): def test_means_the_overriding_model_is_registered_first(self): klass = get_model('partner', 'StockRecord') self.assertEqual( 'tests._site.apps.partner.models', klass.__module__) class TestAppLabelsForModels(TestCase): def test_all_oscar_models_have_app_labels(self): from django.apps import apps models = apps.get_models() missing = [] for model in models: # Ignore non-Oscar models if 'oscar' not in repr(model): continue # Don't know how to get the actual model's Meta class. But if # the parent doesn't have a Meta class, it's doesn't have an # base in Oscar anyway and is not intended to be overridden abstract_model = model.__base__ meta_class = getattr(abstract_model, 'Meta', None) if meta_class is None: continue if not hasattr(meta_class, 'app_label'): missing.append(model) if missing: self.fail("Those models don't have an app_label set: %s" % missing) class TestDynamicLoadingOn3rdPartyApps(TestCase): core_app_prefix = 'thirdparty_package.apps' def setUp(self): self.installed_apps = list(settings.INSTALLED_APPS) sys.path.append('./tests/_site/') def tearDown(self): sys.path.remove('./tests/_site/') def test_load_core_3rd_party_class_correctly(self): self.installed_apps.append('thirdparty_package.apps.myapp') with override_settings(INSTALLED_APPS=self.installed_apps): Cow, Goat = get_classes('myapp.models', ('Cow', 'Goat'), self.core_app_prefix) self.assertEqual('thirdparty_package.apps.myapp.models', Cow.__module__) self.assertEqual('thirdparty_package.apps.myapp.models', Goat.__module__) def test_load_overriden_3rd_party_class_correctly(self): self.installed_apps.append('apps.myapp') with override_settings(INSTALLED_APPS=self.installed_apps): Cow, Goat = get_classes('myapp.models', ('Cow', 'Goat'), self.core_app_prefix) self.assertEqual('thirdparty_package.apps.myapp.models', Cow.__module__) self.assertEqual('apps.myapp.models', Goat.__module__) class OverriddenClassLoadingTestCase(TestCase): def test_non_override_class_loader(self): from oscar.apps.catalogue.views import ProductDetailView View = get_class('catalogue.views', 'ProductDetailView') self.assertEqual(View, ProductDetailView) @override_settings(OSCAR_DYNAMIC_CLASS_LOADER='tests._site.loader.custom_class_loader') def test_override_class_loader(self): # Clear lru cache for the class loader get_class_loader.cache_clear() View = get_class('catalogue.views', 'ProductDetailView') self.assertEqual(View, DummyClass) # Clear lru cache for the class loader again get_class_loader.cache_clear()
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django import forms from django.test import TestCase, override_settings from oscar.apps.address.forms import AbstractAddressForm from oscar.apps.address.models import UserAddress from oscar.apps.order.models import ShippingAddress from oscar.forms.mixins import PhoneNumberMixin from oscar.test.factories import CountryFactory class PhoneNumberMixinTestCase(TestCase): def test_mixin_adds_phone_number_field(self): class TestForm(PhoneNumberMixin, forms.Form): pass form = TestForm() self.assertIn('phone_number', form.fields) def test_mixin_adds_all_phone_number_fields(self): class TestForm(PhoneNumberMixin, forms.Form): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' }, 'another_phone_number': { 'required': False, 'help_text': 'Another phone number help text', 'max_length': 32, 'label': 'Another phone number' }, 'one_more_phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'One more phone number' }, } form = TestForm() self.assertIn('phone_number', form.fields) self.assertIn('another_phone_number', form.fields) self.assertIn('one_more_phone_number', form.fields) field = form.fields['another_phone_number'] self.assertEqual(field.help_text, 'Another phone number help text') def test_mixin_retains_existing_field_properties(self): class TestForm(PhoneNumberMixin, forms.ModelForm): class Meta: model = UserAddress fields = ['country', 'phone_number'] # Override default label and help text labels = {'phone_number': 'Special number'} help_texts = {'phone_number': 'Special help text'} form = TestForm() field = form.fields['phone_number'] self.assertEqual(field.label, 'Special number') self.assertEqual(field.help_text, 'Special help text') @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('phone_number',)) def test_required_empty_field_raises_validation_error(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': True, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['phone_number'], ['This field is required.']) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=[]) def test_optional_empty_field_validates(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertTrue(form.is_valid()) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=[]) def test_invalid_number_fails_validation(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '123456', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['phone_number'], ['This is not a valid local phone format for UNITED KINGDOM.']) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=[]) def test_valid_number_passes_validation(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '02089001234', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertTrue(form.is_valid())
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from oscar.models.fields import NullCharField class NullCharFieldTest(TestCase): def test_from_db_value_converts_null_to_string(self): field = NullCharField() self.assertEqual('', field.from_db_value(None, expression=None, connection=None, context=None)) def test_get_prep_value_converts_empty_string_to_null(self): field = NullCharField() self.assertEqual(None, field.get_prep_value('')) def test_raises_exception_for_invalid_null_blank_combo(self): with self.assertRaises(ImproperlyConfigured): NullCharField(null=True, blank=False) with self.assertRaises(ImproperlyConfigured): NullCharField(null=False, blank=True) with self.assertRaises(ImproperlyConfigured): NullCharField(null=False, blank=False)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from decimal import Decimal as D from itertools import product from django.test import TestCase from oscar.core.prices import Price class TestPriceObject(TestCase): def test_can_be_instantiated_with_tax_amount(self): price = Price('USD', D('10.00'), tax=D('2.00')) self.assertTrue(price.is_tax_known) self.assertEqual(D('12.00'), price.incl_tax) def test_can_have_tax_set_later(self): price = Price('USD', D('10.00')) price.tax = D('2.00') self.assertEqual(D('12.00'), price.incl_tax) def test_price_equals_reflexivity(self): for price in ( Price(currency='USD', excl_tax=D('10.00')), Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')), Price(currency='USD', excl_tax=D('10.00'), incl_tax=D('12.00')), ): self.assertEqual(price, price) def test_price_equals_formats(self): price1 = Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')) price2 = Price(currency='USD', excl_tax=D('10.00'), incl_tax=D('12.00')) self.assertEqual(price1, price2) def test_price_equals_currency_matters(self): price1 = Price(currency='EUR', excl_tax=D('10.00'), tax=D('2.00')) price2 = Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')) self.assertNotEqual(price1, price2) def test_price_equals_transitivity(self): prices = ( Price(currency='EUR', excl_tax=D('10.00'), tax=D('2.00')), Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')), Price(currency='USD', excl_tax=D('10.00'), incl_tax=D('12.00')), Price(currency='USD', excl_tax=D('10.00'), tax=D('8.00')) ) prices_product = product(prices, prices) for price1, price2 in prices_product: self.assertEqual(price1 == price2, price2 == price1)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings class SlugFieldTest(TestCase): def test_slugfield_allow_unicode_kwargs_precedence(self): from oscar.models.fields.slugfield import SlugField with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): slug_field = SlugField(allow_unicode=False) self.assertFalse(slug_field.allow_unicode) slug_field = SlugField() self.assertTrue(slug_field.allow_unicode)
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings from oscar.core import utils def sluggish(value, allow_unicode=False): return value.upper() class TestSlugify(TestCase): def test_default_unicode_to_ascii(self): self.assertEqual('konig-der-straxdfe', utils.slugify('König der Straße')) self.assertEqual('not-fancy', utils.slugify('Not fancy')) self.assertEqual('u4e01u4e02-u4e03u4e04u4e05', utils.slugify('丁丂 七丄丅')) @override_settings(OSCAR_SLUG_ALLOW_UNICODE=True) def test_allow_unicode(self): self.assertEqual('könig-der-straße', utils.slugify('König der Straße')) self.assertEqual('丁丂-七丄丅', utils.slugify('丁丂 七丄丅')) self.assertEqual('not-fancy', utils.slugify('Not fancy')) @override_settings(OSCAR_SLUG_FUNCTION='tests.integration.core.test_utils.sluggish') def test_custom_slugifier(self): self.assertEqual('HAM AND EGGS', utils.slugify('Ham and eggs')) @override_settings(OSCAR_SLUG_MAP={'c++': 'cpp'}) def test_uses_custom_mappings(self): self.assertEqual('cpp', utils.slugify('c++')) @override_settings(OSCAR_SLUG_BLACKLIST=['the']) def test_uses_blacklist(self): self.assertEqual('bible', utils.slugify('The Bible')) @override_settings(OSCAR_SLUG_BLACKLIST=['the', 'bible']) def test_uses_blacklist_doesnt_reduce_to_nothing(self): self.assertEqual('bible', utils.slugify('The Bible'))
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
from django.core.exceptions import ValidationError from django.contrib.flatpages.models import FlatPage from django.test import TestCase, override_settings from django.utils.translation import activate from oscar.core.validators import ExtendedURLValidator, URLDoesNotExistValidator class TestExtendedURLValidator(TestCase): def setUp(self): self.validator = ExtendedURLValidator() def test_validates_local_url(self): try: self.validator('/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validates_local_url_with_query_strings(self): try: self.validator('/?q=test') # Query strings shouldn't affect validation except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_raises_validation_error_for_missing_urls(self): with self.assertRaises(ValidationError): self.validator('/invalid/') def test_validates_urls_missing_preceding_slash(self): try: self.validator('catalogue/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_raises_validation_error_for_urls_without_trailing_slash(self): with self.assertRaises(ValidationError): self.validator('/catalogue') # Missing the / is bad def test_validates_flatpages_urls(self): FlatPage.objects.create(title='test page', url='/test/page/') try: self.validator('/test/page/') except ValidationError: self.fail('ExtendedURLValidator raises ValidationError' 'unexpectedly!') @override_settings( LANGUAGES=( ('de', 'German'), ('en-gb', 'British English'), ) ) class TestExtendedURLValidatorForLocalePrefixURLS(TestCase): def setUp(self): self.validator = ExtendedURLValidator() def test_validate_same_locals(self): """ Current locale is default ("en-gb"), URL has locale prefix of default and current locale ("en-gb"). """ try: self.validator('/en-gb/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_prefix_locale_is_non_default(self): """ Current locale is default ("en-gb"), URL has locale prefix of non-default locale ("de"). """ try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_locale_is_non_default(self): """ Current locale is non-default ("de"), URL has locale prefix of default locale ("en-gb"). """ activate('de') try: self.validator('/en-gb/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_and_prefix_locales_are_non_default_and_same(self): """ Current locale is non-default ("de"), URL has locale prefix of non-default locale ("de"). """ activate('de') try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_and_prefix_locales_are_non_default_and_different(self): """ Current locale is non-default ("it"), URL has locale prefix of non-default locale ("de"). """ activate('it') try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') class TestURLDoesNotExistValidator(TestCase): def setUp(self): self.validator = URLDoesNotExistValidator() def test_raises_exception_for_local_urls(self): self.assertRaises(ValidationError, self.validator, '/') def test_raises_exception_for_flatpages(self): FlatPage.objects.create(title='test page', url='/test/page/') self.assertRaises(ValidationError, self.validator, '/test/page/')
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
import pytest from oscar.views import handler403, handler404, handler500 @pytest.mark.django_db def test_handler403_response_status(rf): request = rf.get('/') response = handler403(request, exception=None) assert response.status_code == 403 @pytest.mark.django_db def test_handler404_response_status(rf): request = rf.get('/') response = handler404(request, exception=None) assert response.status_code == 404 @pytest.mark.django_db def test_handler500_response_status(rf): request = rf.get('/') response = handler500(request) assert response.status_code == 500
I need integration test for this code # -*- coding: utf-8 -*- from django import forms from oscar.core.loading import get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['class'] = 'instruction-mini'
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
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 # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# -*- 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 # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
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 # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# -*- 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 # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
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 # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
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 # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# coding=utf-8 from django.db import IntegrityError from django.test import TestCase from django.core.exceptions import ValidationError from oscar.apps.catalogue.models import (Product, ProductClass, ProductAttribute, AttributeOption, ProductRecommendation) from oscar.test import factories class ProductTests(TestCase): def setUp(self): self.product_class, _ = ProductClass.objects.get_or_create( name='Clothing') class ProductCreationTests(ProductTests): def setUp(self): super().setUp() ProductAttribute.objects.create(product_class=self.product_class, name='Number of pages', code='num_pages', type='integer') Product.ENABLE_ATTRIBUTE_BINDING = True def tearDown(self): Product.ENABLE_ATTRIBUTE_BINDING = False def test_create_products_with_attributes(self): product = Product(upc='1234', product_class=self.product_class, title='testing') product.attr.num_pages = 100 product.save() def test_none_upc_is_represented_as_empty_string(self): product = Product(product_class=self.product_class, title='testing', upc=None) product.save() product.refresh_from_db() self.assertEqual(product.upc, '') def test_upc_uniqueness_enforced(self): Product.objects.create(product_class=self.product_class, title='testing', upc='bah') self.assertRaises(IntegrityError, Product.objects.create, product_class=self.product_class, title='testing', upc='bah') def test_allow_two_products_without_upc(self): for x in range(2): Product.objects.create(product_class=self.product_class, title='testing', upc=None) class TopLevelProductTests(ProductTests): def test_top_level_products_must_have_titles(self): product = Product(product_class=self.product_class) self.assertRaises(ValidationError, product.clean) def test_top_level_products_must_have_product_class(self): product = Product(title="Kopfhörer") self.assertRaises(ValidationError, product.clean) def test_top_level_products_are_part_of_browsable_set(self): product = Product.objects.create( product_class=self.product_class, title="Kopfhörer") self.assertEqual(set([product]), set(Product.browsable.all())) class ChildProductTests(ProductTests): def setUp(self): super().setUp() self.parent = Product.objects.create( title="Parent product", product_class=self.product_class, structure=Product.PARENT, is_discountable=False) def test_child_products_dont_need_titles(self): Product.objects.create( parent=self.parent, structure=Product.CHILD) def test_child_products_dont_need_a_product_class(self): Product.objects.create(parent=self.parent, structure=Product.CHILD) def test_child_products_inherit_fields(self): p = Product.objects.create( parent=self.parent, structure=Product.CHILD, is_discountable=True) self.assertEqual("Parent product", p.get_title()) self.assertEqual("Clothing", p.get_product_class().name) self.assertEqual(False, p.get_is_discountable()) def test_child_products_are_not_part_of_browsable_set(self): Product.objects.create( product_class=self.product_class, parent=self.parent, structure=Product.CHILD) self.assertEqual(set([self.parent]), set(Product.browsable.all())) class TestAChildProduct(TestCase): def setUp(self): clothing = ProductClass.objects.create( name='Clothing', requires_shipping=True) self.parent = clothing.products.create( title="Parent", structure=Product.PARENT) self.child = self.parent.children.create(structure=Product.CHILD) def test_delegates_requires_shipping_logic(self): self.assertTrue(self.child.is_shipping_required) class ProductAttributeCreationTests(TestCase): def test_validating_option_attribute(self): option_group = factories.AttributeOptionGroupFactory() option_1 = factories.AttributeOptionFactory(group=option_group) option_2 = factories.AttributeOptionFactory(group=option_group) pa = factories.ProductAttribute( type='option', option_group=option_group) self.assertRaises(ValidationError, pa.validate_value, 'invalid') pa.validate_value(option_1) pa.validate_value(option_2) invalid_option = AttributeOption(option='invalid option') self.assertRaises( ValidationError, pa.validate_value, invalid_option) def test_entity_attributes(self): unrelated_object = factories.PartnerFactory() attribute = factories.ProductAttributeFactory(type='entity') attribute_value = factories.ProductAttributeValueFactory( attribute=attribute, value_entity=unrelated_object) self.assertEqual(attribute_value.value, unrelated_object) class ProductRecommendationTests(ProductTests): def setUp(self): super().setUp() self.primary_product = Product.objects.create( upc='1234', product_class=self.product_class, title='Primary Product' ) def test_recommended_products_ordering(self): secondary_products = [] for i in range(5): secondary_products.append(Product.objects.create( upc='secondary%s' % i, product_class=self.product_class, title='Secondary Product #%s' % i )) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[3], ranking=5) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[1], ranking=2) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[2], ranking=4) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[4], ranking=1) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[0], ranking=3) recommended_products = [ secondary_products[3], secondary_products[2], secondary_products[0], secondary_products[1], secondary_products[4] ] self.assertEqual(self.primary_product.sorted_recommended_products, recommended_products)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.test import TestCase from oscar.apps.catalogue import models class TestProductClassModel(TestCase): def test_slug_is_auto_created(self): books = models.ProductClass.objects.create( name="Book", ) self.assertEqual('book', books.slug) def test_has_attribute_for_whether_shipping_is_required(self): models.ProductClass.objects.create( name="Download", requires_shipping=False, )
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
import os import tempfile from unittest import mock from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import TestCase, override_settings from oscar.apps.catalogue.abstract_models import MissingProductImage from oscar.test import factories class TestProductImages(TestCase): def test_images_are_in_consecutive_order(self): product = factories.create_product() for i in range(4): factories.create_product_image(product=product, display_order=i) product.images.all()[2].delete() for idx, im in enumerate(product.images.all()): self.assertEqual(im.display_order, idx) def test_variant_images(self): parent = factories.ProductFactory(structure='parent') variant = factories.create_product(parent=parent) factories.create_product_image(product=variant, caption='Variant Image') all_images = variant.get_all_images() self.assertEquals(all_images.count(), 1) product_image = all_images.first() self.assertEquals(product_image.caption, 'Variant Image') def test_variant_images_fallback_to_parent(self): parent = factories.ProductFactory(structure='parent') variant = factories.create_product(parent=parent) factories.create_product_image(product=parent, caption='Parent Product Image') all_images = variant.get_all_images() self.assertEquals(all_images.count(), 1) product_image = all_images.first() self.assertEquals(product_image.caption, 'Parent Product Image') class TestMissingProductImage(StaticLiveServerTestCase): TEMP_MEDIA_ROOT = tempfile.mkdtemp() @override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT) @mock.patch('oscar.apps.catalogue.abstract_models.find') def test_symlink_creates_directories(self, mock_find): # Create a fake empty file to symlink img = tempfile.NamedTemporaryFile(delete=False) img.close() mock_find.return_value = img.name # Initialise the class with a nested path path = 'image/path.jpg' MissingProductImage(path) # Check that the directory exists image_path = os.path.join(self.TEMP_MEDIA_ROOT, path) self.assertTrue(os.path.exists(image_path)) # Clean up for f in [image_path, img.name]: os.unlink(f) for d in [os.path.join(self.TEMP_MEDIA_ROOT, 'image'), self.TEMP_MEDIA_ROOT]: os.rmdir(d) @mock.patch('oscar.apps.catalogue.abstract_models.MissingProductImage.symlink_missing_image') def test_no_symlink_when_no_media_root(self, mock_symlink): MissingProductImage() self.assertEqual(mock_symlink.call_count, 0)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.test import TestCase from django.test.utils import override_settings from oscar.apps.catalogue.search_handlers import ( get_product_search_handler_class, ) class TestSearchHandler(object): pass class TestProductSearchHandlerSetting(TestCase): def test_product_search_handler_setting(self): """ Test that the `OSCAR_PRODUCT_SEARCH_HANDLER` setting, when set, dictates the return value of the `get_product_search_handler_class` function. """ handler_override = 'tests.integration.catalogue.test_product_search_handler_setting.TestSearchHandler' with override_settings(OSCAR_PRODUCT_SEARCH_HANDLER=handler_override): handler_class = get_product_search_handler_class() self.assertEqual(handler_class, TestSearchHandler)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.test import TestCase from oscar.apps.catalogue.reviews import forms from oscar.test.factories import UserFactory, create_product class TestReviewForm(TestCase): def test_cleans_title(self): product = create_product() reviewer = UserFactory() data = { 'title': ' This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } form = forms.ProductReviewForm( product=product, user=reviewer, data=data) assert form.is_valid() review = form.save() assert review.title == "This product is lovely" def test_validates_empty_data_correctly(self): form = forms.ProductReviewForm(product=None, user=None, data={}) assert form.is_valid() is False def test_validates_correctly(self): data = { 'title': 'This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } form = forms.ProductReviewForm(product=None, user=None, data=data) assert form.is_valid() class TestVoteForm(TestCase): def setUp(self): self.product = create_product() self.reviewer = UserFactory() self.voter = UserFactory() self.review = self.product.reviews.create( title='This is nice', score=3, body="This is the body", user=self.reviewer) def test_allows_real_users_to_vote(self): form = forms.VoteForm(self.review, self.voter, data={'delta': 1}) self.assertTrue(form.is_valid()) def test_prevents_users_from_voting_more_than_once(self): self.review.vote_up(self.voter) form = forms.VoteForm(self.review, self.voter, data={'delta': 1}) self.assertFalse(form.is_valid()) self.assertTrue(len(form.errors['__all__']) > 0) def test_prevents_users_voting_on_their_own_reviews(self): form = forms.VoteForm(self.review, self.reviewer, data={'delta': 1}) self.assertFalse(form.is_valid()) self.assertTrue(len(form.errors['__all__']) > 0)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.test import TestCase from django.core.exceptions import ValidationError from oscar.core.compat import get_user_model from oscar.apps.catalogue.reviews import models from oscar.test.factories import create_product from oscar.test.factories import UserFactory User = get_user_model() class TestAnAnonymousReview(TestCase): def setUp(self): self.product = create_product() self.data = { 'product': self.product, 'title': 'This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } def review(self, **kwargs): if kwargs: data = self.data.copy() data.update(kwargs) else: data = self.data return models.ProductReview(**data) def test_can_be_created(self): review = self.review() review.full_clean() def test_requires_a_title(self): review = self.review(title="") self.assertRaises(ValidationError, review.full_clean) def test_requires_a_body(self): review = self.review(body="") self.assertRaises(ValidationError, review.full_clean) def test_requires_a_name(self): review = self.review(name="") self.assertRaises(ValidationError, review.full_clean) def test_requires_an_email_address(self): review = self.review(email="") self.assertRaises(ValidationError, review.full_clean) def test_requires_non_whitespace_title(self): review = self.review(title=" ") self.assertRaises(ValidationError, review.full_clean) def test_starts_with_no_votes(self): review = self.review() review.save() self.assertFalse(review.has_votes) self.assertEqual(0, review.num_up_votes) self.assertEqual(0, review.num_down_votes) def test_has_reviewer_name_property(self): review = self.review(name="Dave") self.assertEqual("Dave", review.reviewer_name) def test_review_moderate_setting_false(self): with self.settings(OSCAR_MODERATE_REVIEWS=False): review = self.review() self.assertEqual(1, review.status) def test_review_moderate_setting_true(self): with self.settings(OSCAR_MODERATE_REVIEWS=True): review = self.review() self.assertEqual(0, review.status) class TestAUserReview(TestCase): def setUp(self): self.product = create_product() self.user = UserFactory(first_name="Tom", last_name="Thumb") self.data = { 'product': self.product, 'title': 'This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'user': self.user } def review(self, **kwargs): if kwargs: data = self.data.copy() data.update(kwargs) else: data = self.data return models.ProductReview(**data) def test_can_be_created(self): review = self.review() review.full_clean() def test_requires_a_title(self): review = self.review(title="") self.assertRaises(ValidationError, review.full_clean) def test_requires_a_body(self): review = self.review(body="") self.assertRaises(ValidationError, review.full_clean) def test_has_reviewer_name_property(self): review = self.review() self.assertEqual("Tom Thumb", review.reviewer_name) def test_num_approved_reviews(self): review = self.review() review.save() self.assertEqual(self.product.num_approved_reviews, 1) self.assertEqual(self.product.reviews.approved().first(), review) def test_review_moderate_setting_false(self): with self.settings(OSCAR_MODERATE_REVIEWS=False): review = self.review() self.assertEqual(1, review.status) def test_review_moderate_setting_true(self): with self.settings(OSCAR_MODERATE_REVIEWS=True): review = self.review() self.assertEqual(0, review.status) class TestVotingOnAReview(TestCase): def setUp(self): self.product = create_product() self.user = UserFactory() self.voter = UserFactory() self.review = self.product.reviews.create( title='This is nice', score=3, body="This is the body", user=self.user) def test_updates_totals_for_upvote(self): self.review.vote_up(self.voter) self.assertTrue(self.review.has_votes) self.assertEqual(1, self.review.total_votes) self.assertEqual(1, self.review.delta_votes) def test_updates_totals_for_downvote(self): self.review.vote_down(self.voter) self.assertTrue(self.review.has_votes) self.assertEqual(1, self.review.total_votes) self.assertEqual(-1, self.review.delta_votes) def test_is_permitted_for_normal_user(self): is_allowed, reason = self.review.can_user_vote(self.voter) self.assertTrue(is_allowed, reason) def test_is_not_permitted_for_reviewer(self): is_allowed, reason = self.review.can_user_vote(self.user) self.assertFalse(is_allowed, reason) def test_is_not_permitted_for_previous_voter(self): self.review.vote_up(self.voter) is_allowed, reason = self.review.can_user_vote(self.voter) self.assertFalse(is_allowed, reason)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from decimal import Decimal as D from unittest import mock from django.test import TestCase, override_settings from django.conf import settings from oscar.apps.basket import forms, formsets from oscar.apps.offer.utils import Applicator from oscar.core.loading import get_model from oscar.test import factories from oscar.test.basket import add_product from oscar.test.factories import ( BenefitFactory, ConditionalOfferFactory, ConditionFactory, RangeFactory) Line = get_model('basket', 'Line') class TestBasketLineForm(TestCase): def setUp(self): self.applicator = Applicator() rng = RangeFactory(includes_all_products=True) self.condition = ConditionFactory( range=rng, type=ConditionFactory._meta.model.VALUE, value=D('100'), proxy_class=None) self.benefit = BenefitFactory( range=rng, type=BenefitFactory._meta.model.FIXED, value=D('10'), max_affected_items=1) self.basket = factories.create_basket() self.line = self.basket.all_lines()[0] def mock_availability_return_value(self, is_available, reason=''): policy = self.line.purchase_info.availability policy.is_purchase_permitted = mock.MagicMock( return_value=(is_available, reason)) def build_form(self, quantity=None): if quantity is None: quantity = self.line.quantity return forms.BasketLineForm( strategy=self.basket.strategy, data={'quantity': quantity}, instance=self.line) def test_enforces_availability_policy_for_valid_quantities(self): self.mock_availability_return_value(True) form = self.build_form() self.assertTrue(form.is_valid()) def test_enforces_availability_policy_for_invalid_quantities(self): self.mock_availability_return_value(False, "Some reason") form = self.build_form() self.assertFalse(form.is_valid()) self.assertEqual( form.errors['quantity'], ['Some reason']) def test_skips_availability_policy_for_zero_quantities(self): self.mock_availability_return_value(True) form = self.build_form(quantity=0) self.assertTrue(form.is_valid()) def test_enforces_max_line_quantity_for_new_product(self): invalid_qty = settings.OSCAR_MAX_BASKET_QUANTITY_THRESHOLD + 1 form = self.build_form(quantity=invalid_qty) self.assertFalse(form.is_valid()) @override_settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=10) def test_enforce_max_line_quantity_for_existing_product(self): self.basket.flush() product = factories.create_product(num_in_stock=20) add_product(self.basket, D('100'), 4, product) self.line = self.basket.all_lines()[0] form = self.build_form(quantity=6) self.assertTrue(form.is_valid()) form.save() form = self.build_form(quantity=11) self.assertFalse(form.is_valid()) def test_line_quantity_max_attribute_per_num_available(self): self.basket.flush() product = factories.create_product(num_in_stock=20) add_product(self.basket, D('100'), 4, product) self.line = self.basket.all_lines()[0] form = self.build_form() self.assertIn('max="20"', str(form['quantity'])) @override_settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=10) def test_line_quantity_max_attribute_per_basket_threshold(self): self.basket.flush() product = factories.create_product(num_in_stock=20) add_product(self.basket, D('100'), 4, product) self.line = self.basket.all_lines()[0] form = self.build_form() self.assertIn('max="6"', str(form['quantity'])) def test_basketline_formset_ordering(self): # when we use a unordered queryset in the Basketlineformset, the # discounts will be lost because django will query the database # again to enforce ordered results add_product(self.basket, D('100'), 5) offer = ConditionalOfferFactory( pk=1, condition=self.condition, benefit=self.benefit) # now we force an unordered queryset so we can see that our discounts # will disappear due to a new ordering query (see django/forms/model.py) default_line_ordering = Line._meta.ordering Line._meta.ordering = [] self.basket._lines = self.basket.lines.all() self.applicator.apply_offers(self.basket, [offer]) formset = formsets.BasketLineFormSet( strategy=self.basket.strategy, queryset=self.basket.all_lines()) # the discount is in all_lines(): self.assertTrue(self.basket.all_lines()[0].has_discount) # but not in the formset self.assertFalse(formset.forms[0].instance.has_discount) # Restore the ordering on the line Line._meta.ordering = default_line_ordering # clear the cached lines and apply the offer again self.basket._lines = None self.applicator.apply_offers(self.basket, [offer]) formset = formsets.BasketLineFormSet( strategy=self.basket.strategy, queryset=self.basket.all_lines()) self.assertTrue(formset.forms[0].instance.has_discount) class TestAddToBasketForm(TestCase): def test_allows_a_product_quantity_to_be_increased(self): basket = factories.create_basket() product = basket.all_lines()[0].product # Add more of the same product data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertTrue(form.is_valid()) def test_checks_whether_passed_product_id_matches_a_real_product(self): basket = factories.create_basket() product = basket.all_lines()[0].product # Add more of the same product data = {'quantity': -1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) def test_checks_if_purchase_is_permitted(self): basket = factories.BasketFactory() product = factories.ProductFactory() # Build a 4-level mock monster so we can force the return value of # whether the product is available to buy. This is a serious code smell # and needs to be remedied. info = mock.Mock() info.availability = mock.Mock() info.availability.is_purchase_permitted = mock.Mock( return_value=(False, "Not on your nelly!")) basket.strategy.fetch_for_product = mock.Mock( return_value=info) data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) self.assertEqual('Not on your nelly!', form.errors['__all__'][0]) def test_mixed_currency_baskets_are_not_permitted(self): # Ensure basket is one currency basket = mock.Mock() basket.currency = 'GBP' basket.num_items = 1 # Ensure new product has different currency info = mock.Mock() info.price.currency = 'EUR' basket.strategy.fetch_for_product = mock.Mock( return_value=info) product = factories.ProductFactory() data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) def test_cannot_add_a_product_without_price(self): basket = factories.BasketFactory() product = factories.create_product(price=None) data = {'quantity': 1} form = forms.AddToBasketForm( basket=basket, product=product, data=data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors['__all__'][0], 'This product cannot be added to the basket because a price ' 'could not be determined for it.', )
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from django.contrib.auth.models import AnonymousUser from oscar.apps.basket import middleware class TestBasketMiddleware(TestCase): @staticmethod def get_response_for_test(request): return HttpResponse() def setUp(self): self.middleware = middleware.BasketMiddleware(self.get_response_for_test) self.request = RequestFactory().get('/') self.request.user = AnonymousUser() self.middleware(self.request) def test_basket_is_attached_to_request(self): self.assertTrue(hasattr(self.request, 'basket')) def test_strategy_is_attached_to_basket(self): self.assertTrue(hasattr(self.request.basket, 'strategy')) def test_strategy_is_attached_to_request(self): self.assertTrue(hasattr(self.request, 'strategy')) def test_get_cookie_basket_handles_invalid_signatures(self): request_factory = RequestFactory() request_factory.cookies['oscar_open_basket'] = '1:NOTAVALIDHASH' request = request_factory.get('/') request.cookies_to_delete = [] cookie_basket = self.middleware.get_cookie_basket("oscar_open_basket", request, None) self.assertEqual(None, cookie_basket) self.assertIn("oscar_open_basket", request.cookies_to_delete)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# -*- coding: utf-8 -*- from decimal import Decimal as D from django.test import TestCase from oscar.apps.basket.models import Basket from oscar.apps.catalogue.models import Option from oscar.apps.partner import availability, prices, strategy from oscar.test import factories from oscar.test.factories import ( BasketFactory, BasketLineAttributeFactory, OptionFactory, ProductFactory) class TestANewBasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() def test_has_zero_lines(self): self.assertEqual(0, self.basket.num_lines) def test_has_zero_items(self): self.assertEqual(0, self.basket.num_items) def test_doesnt_contain_vouchers(self): self.assertFalse(self.basket.contains_a_voucher) def test_can_be_edited(self): self.assertTrue(self.basket.can_be_edited) def test_is_empty(self): self.assertTrue(self.basket.is_empty) def test_is_not_submitted(self): self.assertFalse(self.basket.is_submitted) def test_has_no_applied_offers(self): self.assertEqual({}, self.basket.applied_offers()) class TestBasketLine(TestCase): def test_description(self): basket = BasketFactory() product = ProductFactory(title="A product") basket.add_product(product) line = basket.lines.first() self.assertEqual(line.description, "A product") def test_description_with_attributes(self): basket = BasketFactory() product = ProductFactory(title="A product") basket.add_product(product) line = basket.lines.first() BasketLineAttributeFactory( line=line, value='\u2603', option__name='with') self.assertEqual(line.description, "A product (with = '\u2603')") def test_create_line_reference(self): basket = BasketFactory() product = ProductFactory(title="A product") option = OptionFactory(name="product_option", code="product_option") option_product = ProductFactory(title='Asunción') options = [{'option': option, 'value': option_product}] basket.add_product(product, options=options) def test_basket_lines_queryset_is_ordered(self): # This is needed to make sure a formset is not performing the query # again with an order_by clause (losing all calculated discounts) basket = BasketFactory() product = ProductFactory(title="A product") another_product = ProductFactory(title="Another product") basket.add_product(product) basket.add_product(another_product) queryset = basket.all_lines() self.assertTrue(queryset.ordered) def test_line_tax_for_zero_tax_strategies(self): basket = Basket() basket.strategy = strategy.Default() product = factories.create_product() # Tax for the default strategy will be 0 factories.create_stockrecord( product, price_excl_tax=D('75.00'), num_in_stock=10) basket.add(product, 1) self.assertEqual(basket.lines.first().line_tax, D('0')) def test_line_tax_for_unknown_tax_strategies(self): class UnknownTaxStrategy(strategy.Default): """ A test strategy where the tax is not known """ def pricing_policy(self, product, stockrecord): return prices.FixedPrice('GBP', stockrecord.price_excl_tax, tax=None) basket = Basket() basket.strategy = UnknownTaxStrategy() product = factories.create_product() factories.create_stockrecord(product, num_in_stock=10) basket.add(product, 1) self.assertEqual(basket.lines.first().line_tax, None) class TestAddingAProductToABasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() self.product = factories.create_product() self.record = factories.create_stockrecord( currency='GBP', product=self.product, price_excl_tax=D('10.00')) self.purchase_info = factories.create_purchase_info(self.record) self.basket.add(self.product) def test_creates_a_line(self): self.assertEqual(1, self.basket.num_lines) def test_sets_line_prices(self): line = self.basket.lines.all()[0] self.assertEqual(line.price_incl_tax, self.purchase_info.price.incl_tax) self.assertEqual(line.price_excl_tax, self.purchase_info.price.excl_tax) def test_adding_negative_quantity(self): self.assertEqual(1, self.basket.num_lines) self.basket.add(self.product, quantity=4) self.assertEqual(5, self.basket.line_quantity(self.product, self.record)) self.basket.add(self.product, quantity=-10) self.assertEqual(0, self.basket.line_quantity(self.product, self.record)) def test_means_another_currency_product_cannot_be_added(self): product = factories.create_product() factories.create_stockrecord( currency='USD', product=product, price_excl_tax=D('20.00')) with self.assertRaises(ValueError): self.basket.add(product) def test_cannot_add_a_product_without_price(self): product = factories.create_product(price=None) with self.assertRaises(ValueError): self.basket.add(product) class TestANonEmptyBasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() self.product = factories.create_product() self.record = factories.create_stockrecord( self.product, price_excl_tax=D('10.00')) self.purchase_info = factories.create_purchase_info(self.record) self.basket.add(self.product, 10) def test_can_be_flushed(self): self.basket.flush() self.assertEqual(self.basket.num_items, 0) def test_returns_correct_product_quantity(self): self.assertEqual(10, self.basket.product_quantity( self.product)) def test_returns_correct_line_quantity_for_existing_product_and_stockrecord(self): self.assertEqual(10, self.basket.line_quantity( self.product, self.record)) def test_returns_zero_line_quantity_for_alternative_stockrecord(self): record = factories.create_stockrecord( self.product, price_excl_tax=D('5.00')) self.assertEqual(0, self.basket.line_quantity( self.product, record)) def test_returns_zero_line_quantity_for_missing_product_and_stockrecord(self): product = factories.create_product() record = factories.create_stockrecord( product, price_excl_tax=D('5.00')) self.assertEqual(0, self.basket.line_quantity( product, record)) def test_returns_correct_quantity_for_existing_product_and_stockrecord_and_options(self): product = factories.create_product() record = factories.create_stockrecord( product, price_excl_tax=D('5.00')) option = Option.objects.create(name="Message") options = [{"option": option, "value": "2"}] self.basket.add(product, options=options) self.assertEqual(0, self.basket.line_quantity( product, record)) self.assertEqual(1, self.basket.line_quantity( product, record, options)) def test_total_sums_product_totals(self): product = factories.create_product() factories.create_stockrecord( product, price_excl_tax=D('5.00')) self.basket.add(product, 1) self.assertEqual(self.basket.total_excl_tax, 105) def test_totals_for_free_products(self): basket = Basket() basket.strategy = strategy.Default() # Add a zero-priced product to the basket product = factories.create_product() factories.create_stockrecord( product, price_excl_tax=D('0.00'), num_in_stock=10) basket.add(product, 1) self.assertEqual(basket.lines.count(), 1) self.assertEqual(basket.total_excl_tax, 0) self.assertEqual(basket.total_incl_tax, 0) def test_basket_prices_calculation_for_unavailable_pricing(self): new_product = factories.create_product() factories.create_stockrecord( new_product, price_excl_tax=D('5.00')) self.basket.add(new_product, 1) class UnavailableProductStrategy(strategy.Default): """ A test strategy that makes a specific product unavailable """ def availability_policy(self, product, stockrecord): if product == new_product: return availability.Unavailable() return super().availability_policy(product, stockrecord) def pricing_policy(self, product, stockrecord): if product == new_product: return prices.Unavailable() return super().pricing_policy(product, stockrecord) self.basket.strategy = UnavailableProductStrategy() line = self.basket.all_lines()[1] self.assertEqual(line.get_warning(), "'D\xf9\uff4d\u03fb\u03d2 title' is no longer available") self.assertIsNone(line.line_price_excl_tax) self.assertIsNone(line.line_price_incl_tax) self.assertIsNone(line.line_price_excl_tax_incl_discounts) self.assertIsNone(line.line_price_incl_tax_incl_discounts) self.assertIsNone(line.line_tax) self.assertEqual(self.basket.total_excl_tax, 100) self.assertEqual(self.basket.total_incl_tax, 100) self.assertEqual(self.basket.total_excl_tax_excl_discounts, 100) self.assertEqual(self.basket.total_incl_tax_excl_discounts, 100) def test_max_allowed_quantity(self): self.basket.add_product(self.product, quantity=3) # max allowed here is 7 (20-10+3) with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=20): max_allowed, basket_threshold = self.basket.max_allowed_quantity() self.assertEqual(max_allowed, 7) self.assertEqual(basket_threshold, 20) # but we can also completely disable the threshold with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=None): max_allowed, basket_threshold = self.basket.max_allowed_quantity() self.assertEqual(max_allowed, None) self.assertEqual(basket_threshold, None) def test_is_quantity_allowed(self): with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=20): # 7 or below is possible allowed, message = self.basket.is_quantity_allowed(qty=7) self.assertTrue(allowed) self.assertIsNone(message) # but above it's not allowed, message = self.basket.is_quantity_allowed(qty=11) self.assertFalse(allowed) self.assertIsNotNone(message) with self.settings(OSCAR_MAX_BASKET_QUANTITY_THRESHOLD=None): # with the treshold disabled all quantities are possible allowed, message = self.basket.is_quantity_allowed(qty=7) self.assertTrue(allowed) self.assertIsNone(message) allowed, message = self.basket.is_quantity_allowed(qty=5000) self.assertTrue(allowed) self.assertIsNone(message) class TestMergingTwoBaskets(TestCase): def setUp(self): self.product = factories.create_product() self.record = factories.create_stockrecord( self.product, price_excl_tax=D('10.00')) self.purchase_info = factories.create_purchase_info(self.record) self.main_basket = Basket() self.main_basket.strategy = strategy.Default() self.main_basket.add(self.product, quantity=2) self.merge_basket = Basket() self.merge_basket.strategy = strategy.Default() self.merge_basket.add(self.product, quantity=1) self.main_basket.merge(self.merge_basket) def test_doesnt_sum_quantities(self): self.assertEqual(1, self.main_basket.num_lines) def test_changes_status_of_merge_basket(self): self.assertEqual(Basket.MERGED, self.merge_basket.status) class TestASubmittedBasket(TestCase): def setUp(self): self.basket = Basket() self.basket.strategy = strategy.Default() self.basket.submit() def test_has_correct_status(self): self.assertTrue(self.basket.is_submitted) def test_can_be_edited(self): self.assertFalse(self.basket.can_be_edited) class TestMergingAVoucherBasket(TestCase): def test_transfers_vouchers_to_new_basket(self): baskets = [factories.BasketFactory(), factories.BasketFactory()] voucher = factories.VoucherFactory() baskets[0].vouchers.add(voucher) baskets[1].merge(baskets[0]) self.assertEqual(1, baskets[1].vouchers.all().count())
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
import datetime from django.test import TestCase from oscar.apps.basket.reports import ( OpenBasketReportGenerator, SubmittedBasketReportGenerator) class TestBasketReports(TestCase): def test_open_report_doesnt_error(self): data = { 'start_date': datetime.date(2012, 5, 1), 'end_date': datetime.date(2012, 5, 17), 'formatter': 'CSV' } generator = OpenBasketReportGenerator(**data) generator.generate() def test_submitted_report_doesnt_error(self): data = { 'start_date': datetime.date(2012, 5, 1), 'end_date': datetime.date(2012, 5, 17), 'formatter': 'CSV' } generator = SubmittedBasketReportGenerator(**data) generator.generate()
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
import pytest from oscar.test.factories import ( BasketFactory, ConditionalOfferFactory, ProductFactory) @pytest.fixture def filled_basket(): basket = BasketFactory() product1 = ProductFactory() product2 = ProductFactory() basket.add_product(product1, quantity=10) basket.add_product(product2, quantity=20) return basket @pytest.mark.django_db class TestLineOfferConsumer(object): def test_consumed_no_offer(self, filled_basket): for line in filled_basket.all_lines(): assert line.consumer.consumed() == 0 def test_consumed_with_offer(self, filled_basket): offer1 = ConditionalOfferFactory(name='offer1') offer2 = ConditionalOfferFactory(name='offer2') offer1.exclusive = False offer2.exclusive = False for line in filled_basket.all_lines(): assert line.consumer.consumed(offer1) == 0 assert line.consumer.consumed(offer2) == 0 line1 = filled_basket.all_lines()[0] line2 = filled_basket.all_lines()[1] line1.consumer.consume(1, offer1) assert line1.consumer.consumed() == 1 assert line1.consumer.consumed(offer1) == 1 assert line1.consumer.consumed(offer2) == 0 line1.consumer.consume(9, offer1) assert line1.consumer.consumed() == line1.quantity assert line1.consumer.consumed(offer1) == line1.quantity assert line1.consumer.consumed(offer2) == 0 line1.consumer.consume(99, offer1) assert line1.consumer.consumed(offer1) == line1.quantity assert line1.consumer.consumed(offer2) == 0 line1.consumer.consume(1, offer2) line2.consumer.consume(1, offer2) assert line1.consumer.consumed(offer2) == 1 assert line2.consumer.consumed(offer2) == 1 def test_consume(self, filled_basket): line = filled_basket.all_lines()[0] line.consume(1) assert line.quantity_with_discount == 1 line.consume(99) assert line.quantity_with_discount == 10 def test_consumed_with_exclusive_offer(self, filled_basket): offer1 = ConditionalOfferFactory(name='offer1') offer2 = ConditionalOfferFactory(name='offer2') offer3 = ConditionalOfferFactory(name='offer3') offer1.exclusive = True offer2.exclusive = False offer3.exclusive = False for line in filled_basket.all_lines(): assert line.consumer.consumed(offer1) == 0 assert line.consumer.consumed(offer2) == 0 line1 = filled_basket.all_lines()[0] line2 = filled_basket.all_lines()[1] line1.consumer.consume(1, offer1) assert line1.is_available_for_offer_discount(offer2) is True line1.consumer.consume(99, offer1) assert line1.is_available_for_offer_discount(offer2) is False line2.consumer.consume(1, offer2) assert line2.is_available_for_offer_discount(offer1) is True line2.consumer.consume(99, offer2) assert line2.is_available_for_offer_discount(offer1) is False assert line2.is_available_for_offer_discount(offer3) is True
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.contrib.messages import get_messages from django.test import TestCase from django.urls import reverse from oscar.apps.basket import views from oscar.test import factories from tests.fixtures import RequestFactory class TestVoucherAddView(TestCase): def test_get(self): request = RequestFactory().get('/') view = views.VoucherAddView.as_view() response = view(request) self.assertEqual(response.status_code, 302) def _get_voucher_message(self, request): return '\n'.join(str(m.message) for m in get_messages(request)) def test_post_valid(self): voucher = factories.VoucherFactory() self.assertTrue(voucher.is_active()) data = { 'code': voucher.code } request = RequestFactory().post('/', data=data) request.basket.save() view = views.VoucherAddView.as_view() response = view(request) self.assertEqual(response.status_code, 302) voucher = voucher.__class__.objects.get(pk=voucher.pk) self.assertEqual(voucher.num_basket_additions, 1, msg=self._get_voucher_message(request)) def test_post_valid_from_set(self): voucherset = factories.VoucherSetFactory() voucher = voucherset.vouchers.first() self.assertTrue(voucher.is_active()) data = { 'code': voucher.code } request = RequestFactory().post('/', data=data) request.basket.save() view = views.VoucherAddView.as_view() response = view(request) self.assertEqual(response.status_code, 302) voucher = voucher.__class__.objects.get(pk=voucher.pk) self.assertEqual(voucher.num_basket_additions, 1, msg=self._get_voucher_message(request)) self.assertEqual(voucherset.num_basket_additions, 1) class TestVoucherRemoveView(TestCase): def test_post_valid(self): voucher = factories.VoucherFactory(num_basket_additions=5) data = { 'code': voucher.code } request = RequestFactory().post('/', data=data) request.basket.save() request.basket.vouchers.add(voucher) view = views.VoucherRemoveView.as_view() response = view(request, pk=voucher.pk) self.assertEqual(response.status_code, 302) voucher = voucher.__class__.objects.get(pk=voucher.pk) self.assertEqual(voucher.num_basket_additions, 4) def test_post_with_missing_voucher(self): """ If the voucher is missing, verify the view queues a message and redirects. """ pk = '12345' view = views.VoucherRemoveView.as_view() request = RequestFactory().post('/') request.basket.save() response = view(request, pk=pk) self.assertEqual(response.status_code, 302) actual = list(get_messages(request))[-1].message expected = "No voucher found with id '{}'".format(pk) self.assertEqual(actual, expected) class TestBasketSummaryView(TestCase): def setUp(self): self.url = reverse('basket:summary') self.country = factories.CountryFactory() self.user = factories.UserFactory() def test_default_shipping_address(self): user_address = factories.UserAddressFactory( country=self.country, user=self.user, is_default_for_shipping=True ) request = RequestFactory().get(self.url, user=self.user) view = views.BasketView(request=request) self.assertEquals(view.get_default_shipping_address(), user_address) def test_default_shipping_address_for_anonymous_user(self): request = RequestFactory().get(self.url) view = views.BasketView(request=request) self.assertIsNone(view.get_default_shipping_address())
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from decimal import Decimal as D from unittest import mock from django.test import TestCase from oscar.apps.checkout import calculators from oscar.core import prices class TestOrderTotalCalculator(TestCase): def setUp(self): self.calculator = calculators.OrderTotalCalculator() def test_returns_correct_totals_when_tax_is_not_known(self): basket = mock.Mock() basket.total_excl_tax = D('10.00') basket.is_tax_known = False shipping_charge = prices.Price( currency=basket.currency, excl_tax=D('5.00')) total = self.calculator.calculate(basket, shipping_charge) self.assertIsInstance(total, prices.Price) self.assertEqual(D('10.00') + D('5.00'), total.excl_tax) self.assertFalse(total.is_tax_known) def test_returns_correct_totals_when_tax_is_known(self): basket = mock.Mock() basket.total_excl_tax = D('10.00') basket.total_incl_tax = D('12.00') basket.is_tax_known = True shipping_charge = prices.Price( currency=basket.currency, excl_tax=D('5.00'), tax=D('0.50')) total = self.calculator.calculate(basket, shipping_charge) self.assertIsInstance(total, prices.Price) self.assertEqual(D('10.00') + D('5.00'), total.excl_tax) self.assertTrue(total.is_tax_known) self.assertEqual(D('12.00') + D('5.50'), total.incl_tax) self.assertEqual(D('2.00') + D('0.50'), total.tax)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings from oscar.apps.address.models import Country from oscar.apps.checkout.forms import ShippingAddressForm from oscar.test.factories import CountryFactory class AnotherShippingAddressForm(ShippingAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' }, 'another_phone_number': { 'required': False, 'help_text': 'Another phone number help text', 'max_length': 32, 'label': 'Another phone number' }, } class TestShippingAddressForm(TestCase): minimal_data = { 'first_name': 'Bärry', 'last_name': 'Chuckle', 'line1': '1 King St', 'line4': 'Gothám', 'postcode': 'N1 7RR' } def setUp(self): CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) def test_removes_country_field(self): self.assertTrue('country' not in ShippingAddressForm().fields) def test_keeps_country_field(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) self.assertTrue('country' in ShippingAddressForm().fields) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('last_name', 'postcode')) def test_required_fields_validated(self): form = ShippingAddressForm() self.assertTrue(form.fields['last_name'].required) self.assertTrue(form.fields['postcode'].required) self.assertFalse(form.fields['first_name'].required) self.assertFalse(form.fields['line2'].required) self.assertFalse(form.fields['line3'].required) self.assertFalse(form.fields['line4'].required) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('phone_number',)) def test_required_phone_number_validated(self): # This needs a separate test because of the logic in PhoneNumberMixin form = ShippingAddressForm() self.assertTrue(form.fields['phone_number'].required) # Tests where the country field is hidden def test_is_valid_without_phone_number(self): self.assertTrue(ShippingAddressForm(self.minimal_data).is_valid()) def test_only_accepts_british_local_phone_number(self): data = self.minimal_data.copy() data['phone_number'] = '07 914721389' # local UK number self.assertTrue(ShippingAddressForm(data).is_valid()) data['phone_number'] = '0176 968 426 71' # local German number self.assertFalse(ShippingAddressForm(data).is_valid()) def test_only_accepts_british_local_phone_numbers(self): data = self.minimal_data.copy() # Both numbers are British local numbers data['phone_number'] = '07 914721389' data['another_phone_number'] = '0344493 0787' # British Airways self.assertTrue(AnotherShippingAddressForm(data).is_valid()) # Both numbers are local German numbers data['phone_number'] = '0176 968 426 71' data['another_phone_number'] = '07032 15 49225' # IBM Germany self.assertFalse(AnotherShippingAddressForm(data).is_valid()) # One number is British number, another is German number data['phone_number'] = '07 914721389' data['another_phone_number'] = '0176 968 426 71' self.assertFalse(AnotherShippingAddressForm(data).is_valid()) # As previous case, but numbers are reversed data['phone_number'] = '0176 968 426 71' data['another_phone_number'] = '07 914721389' self.assertFalse(AnotherShippingAddressForm(data).is_valid()) def test_is_valid_with_international_phone_number(self): data = self.minimal_data.copy() data['phone_number'] = '+49 176 968426 71' form = ShippingAddressForm(data) self.assertTrue(form.is_valid()) def test_is_valid_with_international_phone_numbers(self): data = self.minimal_data.copy() data['phone_number'] = '+49 176 968426 71' data['another_phone_number'] = '+49-1805-426452' form = AnotherShippingAddressForm(data) self.assertTrue(form.is_valid()) # Tests where the country field exists def test_needs_country_data(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) self.assertFalse(ShippingAddressForm(self.minimal_data).is_valid()) data = self.minimal_data.copy() data['country'] = Country.objects.get(iso_3166_1_a2='GB').pk self.assertTrue(ShippingAddressForm(data).is_valid()) def test_only_accepts_local_phone_number_when_country_matches(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) data = self.minimal_data.copy() data['phone_number'] = '07 914721389' # local UK number data['country'] = Country.objects.get(iso_3166_1_a2='DE').pk self.assertFalse(ShippingAddressForm(data).is_valid()) data['country'] = Country.objects.get(iso_3166_1_a2='GB').pk self.assertTrue(ShippingAddressForm(data).is_valid()) def test_only_accepts_local_phone_numbers_when_country_matches(self): CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) data = self.minimal_data.copy() # Local UK numbers data['phone_number'] = '07 914721389' data['another_phone_number'] = '0344493 0787' data['country'] = Country.objects.get(iso_3166_1_a2='DE').pk self.assertFalse(ShippingAddressForm(data).is_valid()) data['country'] = Country.objects.get(iso_3166_1_a2='GB').pk self.assertTrue(ShippingAddressForm(data).is_valid()) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('phone_number',)) def test_local_phone_number_invalid_without_country(self): # Add another country, so we have two. CountryFactory(iso_3166_1_a2='DE', is_shipping_country=True) data = self.minimal_data.copy() data['phone_number'] = '07 914721389' # User hasn't selected a country. Because there are multiple country # choices we should not accept the local number. form = ShippingAddressForm(data) self.assertFalse(form.is_valid()) self.assertIn('phone_number', form.errors)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from decimal import Decimal as D from unittest import mock from django.http import HttpRequest from django.test import TestCase from django.test.utils import override_settings from oscar.apps.checkout.calculators import OrderTotalCalculator from oscar.apps.checkout.mixins import CheckoutSessionMixin, OrderPlacementMixin from oscar.apps.checkout.exceptions import FailedPreCondition from oscar.core.loading import get_model from oscar.test import factories from oscar.test.basket import add_product from oscar.test.utils import RequestFactory from oscar.apps.shipping.methods import FixedPrice, Free Order = get_model('order', 'Order') class TestOrderPlacementMixin(TestCase): def test_returns_none_when_no_shipping_address_passed_to_creation_method(self): address = OrderPlacementMixin().create_shipping_address( user=mock.Mock(), shipping_address=None) self.assertEqual(address, None) def test_update_address_book(self): basket = factories.create_basket(empty=True) user = factories.UserFactory() add_product(basket, D('12.00')) shipping_method = FixedPrice(D('5.00'), D('5.00')) billing_address = factories.BillingAddressFactory(line1='1 Boardwalk Place', line2='Trafalgar Way', line3='Tower Hamlets', line4='London') shipping_address = factories.ShippingAddressFactory(line1='Knightsbridge', line2='159', line4='London') shipping_charge = shipping_method.calculate(basket) order_total = OrderTotalCalculator().calculate(basket, shipping_charge) order_submission_data = {'user': user, 'order_number': '12345', 'basket': basket, 'shipping_address': shipping_address, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'billing_address': billing_address, 'order_total': order_total} OrderPlacementMixin().place_order(**order_submission_data) self.assertEqual(user.addresses.filter(hash=billing_address.generate_hash()).count(), 1) self.assertEqual(user.addresses.filter(hash=shipping_address.generate_hash()).count(), 1) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 1) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 1) order_submission_data['order_number'] = '12346' OrderPlacementMixin().place_order(**order_submission_data) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 2) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 2) order_submission_data.pop('billing_address', None) order_submission_data['order_number'] = '123457' OrderPlacementMixin().place_order(**order_submission_data) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 2) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 3) shipping_address.line2 = '160' order_submission_data['billing_address'] = billing_address order_submission_data['order_number'] = '123458' OrderPlacementMixin().place_order(**order_submission_data) user_billing_address = user.addresses.get(hash=billing_address.generate_hash()) user_shipping_address = user.addresses.get(hash=shipping_address.generate_hash()) self.assertEqual(user_billing_address.num_orders_as_billing_address, 3) self.assertEqual(user_shipping_address.num_orders_as_shipping_address, 1) @override_settings(SITE_ID='') def test_multi_site(self): basket = factories.create_basket(empty=True) site1 = factories.SiteFactory() site2 = factories.SiteFactory() request = HttpRequest() request.META['SERVER_PORT'] = 80 request.META['SERVER_NAME'] = site1.domain user = factories.UserFactory() add_product(basket, D('12.00')) shipping_method = Free() shipping_charge = shipping_method.calculate(basket) order_total = OrderTotalCalculator().calculate(basket, shipping_charge) billing_address = factories.BillingAddressFactory() shipping_address = factories.ShippingAddressFactory() order_submission_data = {'user': user, 'order_number': '12345', 'basket': basket, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'order_total': order_total, 'billing_address': billing_address, 'shipping_address': shipping_address, 'request': request} OrderPlacementMixin().place_order(**order_submission_data) order1 = Order.objects.get(number='12345') self.assertEqual(order1.site, site1) add_product(basket, D('12.00')) request.META['SERVER_NAME'] = site2.domain order_submission_data['order_number'] = '12346' order_submission_data['request'] = request OrderPlacementMixin().place_order(**order_submission_data) order2 = Order.objects.get(number='12346') self.assertEqual(order2.site, site2) def test_multiple_payment_events(self): basket = factories.create_basket(empty=True) user = factories.UserFactory() add_product(basket, D('100.00')) order_placement = OrderPlacementMixin() order_placement.add_payment_event('Gift Card Payment', D('10')) order_placement.add_payment_event('Credit Card Payment', D('90')) shipping_method = Free() shipping_charge = shipping_method.calculate(basket) order_total = OrderTotalCalculator().calculate(basket, shipping_charge) billing_address = factories.BillingAddressFactory() shipping_address = factories.ShippingAddressFactory() order_submission_data = {'user': user, 'order_number': '12345', 'basket': basket, 'shipping_method': shipping_method, 'shipping_charge': shipping_charge, 'order_total': order_total, 'billing_address': billing_address, 'shipping_address': shipping_address} order_placement.place_order(**order_submission_data) order1 = Order.objects.get(number='12345') self.assertEqual(order1.payment_events.count(), 2) event1 = order1.payment_events.all()[0] event2 = order1.payment_events.all()[1] self.assertEqual(event1.event_type.name, 'Credit Card Payment') self.assertEqual(event1.amount, D('90')) self.assertEqual(event1.lines.count(), 1) self.assertEqual(event2.event_type.name, 'Gift Card Payment') self.assertEqual(event2.amount, D('10')) self.assertEqual(event2.lines.count(), 1) class TestCheckoutSessionMixin(TestCase): def setUp(self): self.request = RequestFactory().get('/') self.product = factories.create_product(num_in_stock=10) self.stock_record = self.product.stockrecords.first() def add_product_to_basket(self, product, quantity=1): self.request.basket.add_product(product, quantity=quantity) self.assertEqual(len(self.request.basket.all_lines()), 1) self.assertEqual(self.request.basket.all_lines()[0].product, product) def test_check_basket_is_valid_no_stock_available(self): self.add_product_to_basket(self.product) CheckoutSessionMixin().check_basket_is_valid(self.request) self.stock_record.allocate(10) self.stock_record.save() with self.assertRaises(FailedPreCondition): CheckoutSessionMixin().check_basket_is_valid(self.request) def test_check_basket_is_valid_stock_exceeded(self): self.add_product_to_basket(self.product) CheckoutSessionMixin().check_basket_is_valid(self.request) self.request.basket.add_product(self.product, quantity=11) with self.assertRaises(FailedPreCondition): CheckoutSessionMixin().check_basket_is_valid(self.request)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from unittest import mock from django.test import TestCase from django.test.client import RequestFactory from django.contrib.sessions.middleware import SessionMiddleware from oscar.apps.checkout.utils import CheckoutSessionData class TestCheckoutSession(TestCase): """ oscar.apps.checkout.utils.CheckoutSessionData """ def setUp(self): request = RequestFactory().get('/') SessionMiddleware().process_request(request) self.session_data = CheckoutSessionData(request) def test_allows_data_to_be_written_and_read_out(self): self.session_data._set('namespace', 'key', 'value') self.assertEqual('value', self.session_data._get('namespace', 'key')) def test_allows_set_data_can_be_unset(self): self.session_data._set('namespace', 'key', 'value') self.session_data._unset('namespace', 'key') self.assertIsNone(self.session_data._get('namespace', 'key')) def test_stores_guest_email(self): self.session_data.set_guest_email('a@a.com') self.assertEqual('a@a.com', self.session_data.get_guest_email()) def test_allows_a_namespace_to_be_flushed(self): self.session_data._set('ns', 'a', 1) self.session_data._set('ns', 'b', 2) self.session_data._flush_namespace('ns') self.assertIsNone(self.session_data._get('ns', 'a')) self.assertIsNone(self.session_data._get('ns', 'b')) def test_allows_bill_to_user_address(self): address = mock.Mock() address.id = 1 self.session_data.bill_to_user_address(address) self.assertEqual(1, self.session_data.billing_user_address_id())
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse from oscar.test.factories import OrderFactory class ThankYouViewTestCase(TestCase): @override_settings(OSCAR_ALLOW_ANON_CHECKOUT=True) def test_analytics_event_triggered_only_on_first_view(self): order = OrderFactory() session = self.client.session # Put the order ID in the session, mimicking a completed order, # so that we can reach the thank you page. session['checkout_order_id'] = order.pk session.save() r1 = self.client.get(reverse('checkout:thank-you'), follow=True) self.assertTrue(r1.context['send_analytics_event']) # Request the view a second time r2 = self.client.get(reverse('checkout:thank-you'), follow=True) self.assertFalse(r2.context['send_analytics_event'])
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# coding=utf-8 """ AutoSlugField taken from django-extensions at 15d3eb305957cee4768dd86e44df1bdad341a10e Uses Oscar's slugify function instead of Django's Copyright (c) 2007 Michael Trier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from django.db import models from django.test import TestCase from django.test.utils import override_settings from oscar.core.loading import get_model SluggedTestModel = get_model('model_tests_app', 'sluggedtestmodel') ChildSluggedTestModel = get_model('model_tests_app', 'childsluggedtestmodel') CustomSluggedTestModel = get_model('model_tests_app', 'CustomSluggedTestModel') class AutoSlugFieldTest(TestCase): def tearDown(self): super().tearDown() SluggedTestModel.objects.all().delete() def test_auto_create_slug(self): m = SluggedTestModel(title='foo') m.save() self.assertEqual(m.slug, 'foo') def test_auto_create_next_slug(self): m = SluggedTestModel(title='foo') m.save() m = SluggedTestModel(title='foo') m.save() self.assertEqual(m.slug, 'foo-2') def test_auto_create_slug_with_number(self): m = SluggedTestModel(title='foo 2012') m.save() self.assertEqual(m.slug, 'foo-2012') def test_auto_update_slug_with_number(self): m = SluggedTestModel(title='foo 2012') m.save() m.save() self.assertEqual(m.slug, 'foo-2012') def test_auto_create_unicode_slug(self): with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): m = SluggedTestModel(title='Château Margaux 1960') m.save() self.assertEqual(m.slug, 'château-margaux-1960') def test_auto_create_next_unicode_slug(self): with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): m1 = SluggedTestModel(title='Château Margaux 1960') m1.save() m2 = SluggedTestModel(title='Château Margaux 1960') m2.save() self.assertEqual(m2.slug, 'château-margaux-1960-2') def test_switch_to_unicode_slug(self): m = SluggedTestModel(title='Château Margaux 1960') m.save() self.assertEqual(m.slug, 'chateau-margaux-1960') with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): m = SluggedTestModel(title='Château Margaux 1960') m.save() self.assertEqual(m.slug, 'château-margaux-1960') def test_autoslugfield_allow_unicode_kwargs_precedence(self): from oscar.models.fields import AutoSlugField with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): autoslug_field = AutoSlugField(populate_from='title', allow_unicode=False) self.assertFalse(autoslug_field.allow_unicode) autoslug_field = AutoSlugField(populate_from='title') self.assertTrue(autoslug_field.allow_unicode) def test_update_slug(self): m = SluggedTestModel(title='foo') m.save() self.assertEqual(m.slug, 'foo') # update m instance without using `save' SluggedTestModel.objects.filter(pk=m.pk).update(slug='foo-2012') # update m instance with new data from the db m = SluggedTestModel.objects.get(pk=m.pk) self.assertEqual(m.slug, 'foo-2012') m.save() self.assertEqual(m.title, 'foo') self.assertEqual(m.slug, 'foo-2012') # Check slug is not overwrite m.title = 'bar' m.save() self.assertEqual(m.title, 'bar') self.assertEqual(m.slug, 'foo-2012') def test_simple_slug_source(self): m = SluggedTestModel(title='-foo') m.save() self.assertEqual(m.slug, 'foo') n = SluggedTestModel(title='-foo') n.save() self.assertEqual(n.slug, 'foo-2') n.save() self.assertEqual(n.slug, 'foo-2') def test_empty_slug_source(self): # regression test m = SluggedTestModel(title='') m.save() self.assertEqual(m.slug, '-2') n = SluggedTestModel(title='') n.save() self.assertEqual(n.slug, '-3') n.save() self.assertEqual(n.slug, '-3') def test_inheritance_creates_next_slug(self): m = SluggedTestModel(title='foo') m.save() n = ChildSluggedTestModel(title='foo') n.save() self.assertEqual(n.slug, 'foo-2') o = SluggedTestModel(title='foo') o.save() self.assertEqual(o.slug, 'foo-3') def test_separator_and_uppercase_options(self): m = CustomSluggedTestModel(title="Password reset") m.save() self.assertEqual(m.slug, 'PASSWORD_RESET') m = CustomSluggedTestModel(title="Password reset") m.save() self.assertEqual(m.slug, 'PASSWORD_RESET_2') def test_migration(self): """ Tests making migrations with Django 1.7+'s migration framework """ import oscar from django.db import migrations from django.db.migrations.writer import MigrationWriter from oscar.models.fields import AutoSlugField fields = { 'autoslugfield': AutoSlugField(populate_from='otherfield'), } migration = type(str("Migration"), (migrations.Migration,), { "operations": [ migrations.CreateModel("MyModel", tuple(fields.items()), {'populate_from': 'otherfield'}, (models.Model,)), ], }) writer = MigrationWriter(migration) output = writer.as_string() if isinstance(output, str): output = output.encode('utf-8') # We don't test the output formatting - that's too fragile. # Just make sure it runs for now, and that things look alright. context = { 'migrations': migrations, 'oscar': oscar, } result = self.safe_exec(output, context=context) self.assertIn("Migration", result) def safe_exec(self, string, value=None, context=None): loc = {} g = globals() g.update(context) try: exec(string, g, loc) except Exception as e: if value: self.fail("Could not exec %r (from value %r): %s" % ( string.strip(), value, e)) else: self.fail("Could not exec %r: %s" % (string.strip(), e)) return loc
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# -*- coding: utf-8 -*- import codecs import datetime import io import os from tempfile import NamedTemporaryFile from django.utils.encoding import smart_text from django.test import TestCase, override_settings from oscar.core.compat import UnicodeCSVWriter, existing_user_fields class unicodeobj(object): def __init__(self, s): self.s = s def __str__(self): return self.s class TestExistingUserFields(TestCase): def test_order(self): fields = existing_user_fields(['email', 'first_name', 'last_name']) self.assertEqual(fields, ['email', 'first_name', 'last_name']) class TestUnicodeCSVWriter(TestCase): def test_can_write_different_values(self): writer = UnicodeCSVWriter(open_file=io.StringIO()) s = 'ünįcodē' rows = [[s, unicodeobj(s), 123, datetime.date.today()], ] writer.writerows(rows) self.assertRaises(TypeError, writer.writerows, [object()]) def test_context_manager(self): tmp_file = NamedTemporaryFile() with UnicodeCSVWriter(filename=tmp_file.name) as writer: s = 'ünįcodē' rows = [[s, unicodeobj(s), 123, datetime.date.today()], ] writer.writerows(rows) def test_csv_write_output(self): tmp_file = NamedTemporaryFile(delete=False) with UnicodeCSVWriter(filename=tmp_file.name) as writer: s = 'ünįcodē' row = [s, 123, 'foo-bar'] writer.writerows([row]) with open(tmp_file.name, 'r') as read_file: content = smart_text(read_file.read(), encoding='utf-8').strip() self.assertEqual(content, 'ünįcodē,123,foo-bar') # Clean up os.unlink(tmp_file.name) @override_settings(OSCAR_CSV_INCLUDE_BOM=True) def test_bom_write_with_open_file(self): csv_file = NamedTemporaryFile(delete=False) with open(csv_file.name, 'w') as open_file: writer = UnicodeCSVWriter(open_file=open_file, encoding="utf-8") s = 'ünįcodē' row = [s, 123, datetime.date.today()] writer.writerows([row]) with open(csv_file.name, 'rb') as read_file: self.assertTrue(read_file.read().startswith(codecs.BOM_UTF8)) # Clean up os.unlink(csv_file.name) @override_settings(OSCAR_CSV_INCLUDE_BOM=True) def test_bom_write_with_filename(self): csv_file = NamedTemporaryFile(delete=False) with UnicodeCSVWriter(filename=csv_file.name, encoding="utf-8") as writer: s = 'ünįcodē' row = [s, 123, datetime.date.today()] writer.writerows([row]) with open(csv_file.name, 'rb') as read_file: self.assertTrue(read_file.read().startswith(codecs.BOM_UTF8)) # Clean up os.unlink(csv_file.name) @override_settings(OSCAR_CSV_INCLUDE_BOM=True) def test_bom_not_written_for_other_encodings(self): csv_file = NamedTemporaryFile(delete=False) with UnicodeCSVWriter(filename=csv_file.name, encoding="ascii") as writer: s = 'boring ascii' row = [s, 123, datetime.date.today()] writer.writerows([row]) with open(csv_file.name, 'rb') as read_file: self.assertFalse(read_file.read().startswith(codecs.BOM_UTF8)) # Clean up os.unlink(csv_file.name)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
import pytest from django.conf import settings from django.test import TestCase from oscar.core import customisation VALID_FOLDER_PATH = 'tests/_site/apps' class TestUtilities(TestCase): def test_subfolder_extraction(self): folders = list(customisation.subfolders('/var/www/eggs')) self.assertEqual(folders, ['/var', '/var/www', '/var/www/eggs']) def test_raises_exception_for_nonexistant_app_label(): with pytest.raises(ValueError): customisation.fork_app('sillytown', 'somefolder') def test_raises_exception_if_app_has_already_been_forked(): # We piggyback on another test which means a custom app is already in # the settings we use for the test suite. We just check that's still # the case here. assert 'tests._site.apps.partner' in settings.INSTALLED_APPS with pytest.raises(ValueError): customisation.fork_app('partner', VALID_FOLDER_PATH) def test_creates_new_folder(tmpdir): path = tmpdir.mkdir('fork') customisation.fork_app('order', str(path)) path.join('order').ensure_dir() def test_creates_init_file(tmpdir): path = tmpdir.mkdir('fork') customisation.fork_app('order', str(path)) path.join('order').join('__init__.py').ensure() def test_handles_dashboard_app(tmpdir): # Dashboard apps are fiddly as they aren't identified by a single app # label. path = tmpdir.mkdir('fork') customisation.fork_app('dashboard.catalogue', str(path)) # Check __init__.py created (and supporting folders) path.join('dashboard').join('catalogue').join('__init__.py').ensure() def test_creates_models_and_admin_file(tmpdir): path = tmpdir.mkdir('fork') customisation.fork_app('order', str(path)) for module, expected_string in [ ('models', 'from oscar.apps.order.models import *'), ('admin', 'from oscar.apps.order.admin import *'), ('config', 'OrderConfig') ]: filepath = path.join('order').join('%s.py' % module) filepath.ensure() contents = filepath.read() assert expected_string in contents def test_copies_in_migrations_when_needed(tmpdir): path = tmpdir.mkdir('fork') for app, has_models in [('order', True), ('search', False)]: customisation.fork_app(app, str(path)) native_migration_path = path.join(app).join('migrations') assert has_models == native_migration_path.check() def test_dashboard_app_config(tmpdir, monkeypatch): path = tmpdir.mkdir('fork') customisation.fork_app('dashboard', str(path)) path.join('__init__.py').write('') monkeypatch.syspath_prepend(str(tmpdir)) config_module = __import__( '%s.dashboard.config' % path.basename, fromlist=['DashboardConfig'] ) assert hasattr(config_module, 'DashboardConfig')
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
import warnings from django.contrib.auth.models import AnonymousUser, Permission from django.test import TestCase from oscar.core.decorators import deprecated from oscar.test import factories from oscar.views.decorators import check_permissions class TestPermissionsDecorator(TestCase): def test_empty_permissions_passes(self): user = factories.UserFactory.build() self.assertTrue(check_permissions(user, [])) def test_properties_are_checked(self): staff_user = factories.UserFactory.build(is_staff=True) non_staff_user = factories.UserFactory.build(is_staff=False) self.assertTrue(check_permissions(staff_user, ['is_staff'])) self.assertFalse(check_permissions(non_staff_user, ['is_staff'])) def test_methods_are_checked(self): anonymous_user = AnonymousUser() known_user = factories.UserFactory.build() self.assertTrue(check_permissions(anonymous_user, ['is_anonymous'])) self.assertFalse(check_permissions(known_user, ['is_anonymous'])) def test_permissions_are_checked(self): user_with_perm = factories.UserFactory() user_without_perm = factories.UserFactory() perm = Permission.objects.get( content_type__app_label='address', codename='add_country') user_with_perm.user_permissions.add(perm) self.assertTrue( check_permissions(user_with_perm, ['address.add_country'])) self.assertFalse( check_permissions(user_without_perm, ['address.add_country'])) class TestDeprecatedDecorator(TestCase): def test_decorate_function(self): @deprecated def func(): return True with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") self.assertTrue(func()) assert len(caught) == 1 assert issubclass(caught[0].category, DeprecationWarning) def test_decorate_class(self): class Cls(object): val = False def __init__(self): self.val = True Deprecated = deprecated(Cls) # noqa with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") obj = Deprecated() self.assertTrue(obj.val) assert len(caught) == 1 assert issubclass(caught[0].category, DeprecationWarning) def test_subclass_decorated(self): class Cls(object): val = False def __init__(self): self.val = True Deprecated = deprecated(Cls) # noqa class SubCls(Deprecated): pass with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") obj = SubCls() self.assertTrue(obj.val) assert len(caught) == 1 assert issubclass(caught[0].category, DeprecationWarning)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from os.path import dirname import sys from django.test import override_settings, TestCase from django.conf import settings import oscar from oscar.core.loading import ( get_model, AppNotFoundError, get_classes, get_class, get_class_loader, ClassNotFoundError) from tests import temporary_python_path from tests._site.loader import DummyClass class TestClassLoading(TestCase): """ Oscar's class loading utilities """ def test_load_oscar_classes_correctly(self): Product, Category = get_classes('catalogue.models', ('Product', 'Category')) self.assertEqual('oscar.apps.catalogue.models', Product.__module__) self.assertEqual('oscar.apps.catalogue.models', Category.__module__) def test_load_oscar_class_correctly(self): Product = get_class('catalogue.models', 'Product') self.assertEqual('oscar.apps.catalogue.models', Product.__module__) def test_load_oscar_class_from_dashboard_subapp(self): ReportForm = get_class('dashboard.reports.forms', 'ReportForm') self.assertEqual('oscar.apps.dashboard.reports.forms', ReportForm.__module__) def test_raise_exception_when_bad_appname_used(self): with self.assertRaises(AppNotFoundError): get_classes('fridge.models', ('Product', 'Category')) def test_raise_exception_when_bad_classname_used(self): with self.assertRaises(ClassNotFoundError): get_class('catalogue.models', 'Monkey') def test_raise_importerror_if_app_raises_importerror(self): """ This tests that Oscar doesn't fall back to using the Oscar catalogue app if the overriding app throws an ImportError. """ apps = list(settings.INSTALLED_APPS) apps[apps.index('oscar.apps.catalogue')] = 'tests._site.import_error_app.catalogue' with override_settings(INSTALLED_APPS=apps): with self.assertRaises(ImportError): get_class('catalogue.app', 'CatalogueApplication') class ClassLoadingWithLocalOverrideTests(TestCase): def setUp(self): self.installed_apps = list(settings.INSTALLED_APPS) self.installed_apps[self.installed_apps.index('oscar.apps.shipping')] = 'tests._site.shipping' def test_loading_class_defined_in_local_module(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Free,) = get_classes('shipping.methods', ('Free',)) self.assertEqual('tests._site.shipping.methods', Free.__module__) def test_loading_class_which_is_not_defined_in_local_module(self): with override_settings(INSTALLED_APPS=self.installed_apps): (FixedPrice,) = get_classes('shipping.methods', ('FixedPrice',)) self.assertEqual('oscar.apps.shipping.methods', FixedPrice.__module__) def test_loading_class_from_module_not_defined_in_local_app(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Repository,) = get_classes('shipping.repository', ('Repository',)) self.assertEqual('oscar.apps.shipping.repository', Repository.__module__) def test_loading_classes_defined_in_both_local_and_oscar_modules(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Free, FixedPrice) = get_classes('shipping.methods', ('Free', 'FixedPrice')) self.assertEqual('tests._site.shipping.methods', Free.__module__) self.assertEqual('oscar.apps.shipping.methods', FixedPrice.__module__) def test_loading_classes_with_root_app(self): import tests._site.shipping path = dirname(dirname(tests._site.shipping.__file__)) with temporary_python_path([path]): self.installed_apps[ self.installed_apps.index('tests._site.shipping')] = 'shipping' with override_settings(INSTALLED_APPS=self.installed_apps): (Free,) = get_classes('shipping.methods', ('Free',)) self.assertEqual('shipping.methods', Free.__module__) def test_overriding_view_is_possible_without_overriding_app(self): from oscar.apps.customer.app import application, CustomerApplication # If test fails, it's helpful to know if it's caused by order of # execution self.assertEqual(CustomerApplication().summary_view.__module__, 'tests._site.apps.customer.views') self.assertEqual(application.summary_view.__module__, 'tests._site.apps.customer.views') class ClassLoadingWithLocalOverrideWithMultipleSegmentsTests(TestCase): def setUp(self): self.installed_apps = list(settings.INSTALLED_APPS) self.installed_apps[self.installed_apps.index('oscar.apps.shipping')] = 'tests._site.apps.shipping' def test_loading_class_defined_in_local_module(self): with override_settings(INSTALLED_APPS=self.installed_apps): (Free,) = get_classes('shipping.methods', ('Free',)) self.assertEqual('tests._site.apps.shipping.methods', Free.__module__) class TestGetCoreAppsFunction(TestCase): """ oscar.get_core_apps function """ def test_returns_core_apps_when_no_overrides_specified(self): apps = oscar.get_core_apps() self.assertEqual(oscar.OSCAR_CORE_APPS, apps) def test_uses_non_dashboard_override_when_specified(self): apps = oscar.get_core_apps(overrides=['apps.shipping']) self.assertTrue('apps.shipping' in apps) self.assertTrue('oscar.apps.shipping' not in apps) def test_uses_dashboard_override_when_specified(self): apps = oscar.get_core_apps(overrides=['apps.dashboard.catalogue']) self.assertTrue('apps.dashboard.catalogue' in apps) self.assertTrue('oscar.apps.dashboard.catalogue' not in apps) self.assertTrue('oscar.apps.catalogue' in apps) class TestOverridingCoreApps(TestCase): def test_means_the_overriding_model_is_registered_first(self): klass = get_model('partner', 'StockRecord') self.assertEqual( 'tests._site.apps.partner.models', klass.__module__) class TestAppLabelsForModels(TestCase): def test_all_oscar_models_have_app_labels(self): from django.apps import apps models = apps.get_models() missing = [] for model in models: # Ignore non-Oscar models if 'oscar' not in repr(model): continue # Don't know how to get the actual model's Meta class. But if # the parent doesn't have a Meta class, it's doesn't have an # base in Oscar anyway and is not intended to be overridden abstract_model = model.__base__ meta_class = getattr(abstract_model, 'Meta', None) if meta_class is None: continue if not hasattr(meta_class, 'app_label'): missing.append(model) if missing: self.fail("Those models don't have an app_label set: %s" % missing) class TestDynamicLoadingOn3rdPartyApps(TestCase): core_app_prefix = 'thirdparty_package.apps' def setUp(self): self.installed_apps = list(settings.INSTALLED_APPS) sys.path.append('./tests/_site/') def tearDown(self): sys.path.remove('./tests/_site/') def test_load_core_3rd_party_class_correctly(self): self.installed_apps.append('thirdparty_package.apps.myapp') with override_settings(INSTALLED_APPS=self.installed_apps): Cow, Goat = get_classes('myapp.models', ('Cow', 'Goat'), self.core_app_prefix) self.assertEqual('thirdparty_package.apps.myapp.models', Cow.__module__) self.assertEqual('thirdparty_package.apps.myapp.models', Goat.__module__) def test_load_overriden_3rd_party_class_correctly(self): self.installed_apps.append('apps.myapp') with override_settings(INSTALLED_APPS=self.installed_apps): Cow, Goat = get_classes('myapp.models', ('Cow', 'Goat'), self.core_app_prefix) self.assertEqual('thirdparty_package.apps.myapp.models', Cow.__module__) self.assertEqual('apps.myapp.models', Goat.__module__) class OverriddenClassLoadingTestCase(TestCase): def test_non_override_class_loader(self): from oscar.apps.catalogue.views import ProductDetailView View = get_class('catalogue.views', 'ProductDetailView') self.assertEqual(View, ProductDetailView) @override_settings(OSCAR_DYNAMIC_CLASS_LOADER='tests._site.loader.custom_class_loader') def test_override_class_loader(self): # Clear lru cache for the class loader get_class_loader.cache_clear() View = get_class('catalogue.views', 'ProductDetailView') self.assertEqual(View, DummyClass) # Clear lru cache for the class loader again get_class_loader.cache_clear()
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django import forms from django.test import TestCase, override_settings from oscar.apps.address.forms import AbstractAddressForm from oscar.apps.address.models import UserAddress from oscar.apps.order.models import ShippingAddress from oscar.forms.mixins import PhoneNumberMixin from oscar.test.factories import CountryFactory class PhoneNumberMixinTestCase(TestCase): def test_mixin_adds_phone_number_field(self): class TestForm(PhoneNumberMixin, forms.Form): pass form = TestForm() self.assertIn('phone_number', form.fields) def test_mixin_adds_all_phone_number_fields(self): class TestForm(PhoneNumberMixin, forms.Form): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' }, 'another_phone_number': { 'required': False, 'help_text': 'Another phone number help text', 'max_length': 32, 'label': 'Another phone number' }, 'one_more_phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'One more phone number' }, } form = TestForm() self.assertIn('phone_number', form.fields) self.assertIn('another_phone_number', form.fields) self.assertIn('one_more_phone_number', form.fields) field = form.fields['another_phone_number'] self.assertEqual(field.help_text, 'Another phone number help text') def test_mixin_retains_existing_field_properties(self): class TestForm(PhoneNumberMixin, forms.ModelForm): class Meta: model = UserAddress fields = ['country', 'phone_number'] # Override default label and help text labels = {'phone_number': 'Special number'} help_texts = {'phone_number': 'Special help text'} form = TestForm() field = form.fields['phone_number'] self.assertEqual(field.label, 'Special number') self.assertEqual(field.help_text, 'Special help text') @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=('phone_number',)) def test_required_empty_field_raises_validation_error(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': True, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['phone_number'], ['This field is required.']) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=[]) def test_optional_empty_field_validates(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertTrue(form.is_valid()) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=[]) def test_invalid_number_fails_validation(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '123456', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['phone_number'], ['This is not a valid local phone format for UNITED KINGDOM.']) @override_settings(OSCAR_REQUIRED_ADDRESS_FIELDS=[]) def test_valid_number_passes_validation(self): class TestForm(PhoneNumberMixin, AbstractAddressForm): phone_number_fields = { 'phone_number': { 'required': False, 'help_text': '', 'max_length': 32, 'label': 'Phone number' } } class Meta: model = ShippingAddress fields = ['country', 'phone_number', 'postcode'] CountryFactory(iso_3166_1_a2='GB', is_shipping_country=True) form = TestForm(data={'phone_number': '02089001234', 'country': 'GB', 'postcode': 'WW1 2BB'}) self.assertTrue(form.is_valid())
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from oscar.models.fields import NullCharField class NullCharFieldTest(TestCase): def test_from_db_value_converts_null_to_string(self): field = NullCharField() self.assertEqual('', field.from_db_value(None, expression=None, connection=None, context=None)) def test_get_prep_value_converts_empty_string_to_null(self): field = NullCharField() self.assertEqual(None, field.get_prep_value('')) def test_raises_exception_for_invalid_null_blank_combo(self): with self.assertRaises(ImproperlyConfigured): NullCharField(null=True, blank=False) with self.assertRaises(ImproperlyConfigured): NullCharField(null=False, blank=True) with self.assertRaises(ImproperlyConfigured): NullCharField(null=False, blank=False)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from decimal import Decimal as D from itertools import product from django.test import TestCase from oscar.core.prices import Price class TestPriceObject(TestCase): def test_can_be_instantiated_with_tax_amount(self): price = Price('USD', D('10.00'), tax=D('2.00')) self.assertTrue(price.is_tax_known) self.assertEqual(D('12.00'), price.incl_tax) def test_can_have_tax_set_later(self): price = Price('USD', D('10.00')) price.tax = D('2.00') self.assertEqual(D('12.00'), price.incl_tax) def test_price_equals_reflexivity(self): for price in ( Price(currency='USD', excl_tax=D('10.00')), Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')), Price(currency='USD', excl_tax=D('10.00'), incl_tax=D('12.00')), ): self.assertEqual(price, price) def test_price_equals_formats(self): price1 = Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')) price2 = Price(currency='USD', excl_tax=D('10.00'), incl_tax=D('12.00')) self.assertEqual(price1, price2) def test_price_equals_currency_matters(self): price1 = Price(currency='EUR', excl_tax=D('10.00'), tax=D('2.00')) price2 = Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')) self.assertNotEqual(price1, price2) def test_price_equals_transitivity(self): prices = ( Price(currency='EUR', excl_tax=D('10.00'), tax=D('2.00')), Price(currency='USD', excl_tax=D('10.00'), tax=D('2.00')), Price(currency='USD', excl_tax=D('10.00'), incl_tax=D('12.00')), Price(currency='USD', excl_tax=D('10.00'), tax=D('8.00')) ) prices_product = product(prices, prices) for price1, price2 in prices_product: self.assertEqual(price1 == price2, price2 == price1)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings class SlugFieldTest(TestCase): def test_slugfield_allow_unicode_kwargs_precedence(self): from oscar.models.fields.slugfield import SlugField with override_settings(OSCAR_SLUG_ALLOW_UNICODE=True): slug_field = SlugField(allow_unicode=False) self.assertFalse(slug_field.allow_unicode) slug_field = SlugField() self.assertTrue(slug_field.allow_unicode)
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# coding=utf-8 from django.test import TestCase from django.test.utils import override_settings from oscar.core import utils def sluggish(value, allow_unicode=False): return value.upper() class TestSlugify(TestCase): def test_default_unicode_to_ascii(self): self.assertEqual('konig-der-straxdfe', utils.slugify('König der Straße')) self.assertEqual('not-fancy', utils.slugify('Not fancy')) self.assertEqual('u4e01u4e02-u4e03u4e04u4e05', utils.slugify('丁丂 七丄丅')) @override_settings(OSCAR_SLUG_ALLOW_UNICODE=True) def test_allow_unicode(self): self.assertEqual('könig-der-straße', utils.slugify('König der Straße')) self.assertEqual('丁丂-七丄丅', utils.slugify('丁丂 七丄丅')) self.assertEqual('not-fancy', utils.slugify('Not fancy')) @override_settings(OSCAR_SLUG_FUNCTION='tests.integration.core.test_utils.sluggish') def test_custom_slugifier(self): self.assertEqual('HAM AND EGGS', utils.slugify('Ham and eggs')) @override_settings(OSCAR_SLUG_MAP={'c++': 'cpp'}) def test_uses_custom_mappings(self): self.assertEqual('cpp', utils.slugify('c++')) @override_settings(OSCAR_SLUG_BLACKLIST=['the']) def test_uses_blacklist(self): self.assertEqual('bible', utils.slugify('The Bible')) @override_settings(OSCAR_SLUG_BLACKLIST=['the', 'bible']) def test_uses_blacklist_doesnt_reduce_to_nothing(self): self.assertEqual('bible', utils.slugify('The Bible'))
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
from django.core.exceptions import ValidationError from django.contrib.flatpages.models import FlatPage from django.test import TestCase, override_settings from django.utils.translation import activate from oscar.core.validators import ExtendedURLValidator, URLDoesNotExistValidator class TestExtendedURLValidator(TestCase): def setUp(self): self.validator = ExtendedURLValidator() def test_validates_local_url(self): try: self.validator('/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validates_local_url_with_query_strings(self): try: self.validator('/?q=test') # Query strings shouldn't affect validation except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_raises_validation_error_for_missing_urls(self): with self.assertRaises(ValidationError): self.validator('/invalid/') def test_validates_urls_missing_preceding_slash(self): try: self.validator('catalogue/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_raises_validation_error_for_urls_without_trailing_slash(self): with self.assertRaises(ValidationError): self.validator('/catalogue') # Missing the / is bad def test_validates_flatpages_urls(self): FlatPage.objects.create(title='test page', url='/test/page/') try: self.validator('/test/page/') except ValidationError: self.fail('ExtendedURLValidator raises ValidationError' 'unexpectedly!') @override_settings( LANGUAGES=( ('de', 'German'), ('en-gb', 'British English'), ) ) class TestExtendedURLValidatorForLocalePrefixURLS(TestCase): def setUp(self): self.validator = ExtendedURLValidator() def test_validate_same_locals(self): """ Current locale is default ("en-gb"), URL has locale prefix of default and current locale ("en-gb"). """ try: self.validator('/en-gb/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_prefix_locale_is_non_default(self): """ Current locale is default ("en-gb"), URL has locale prefix of non-default locale ("de"). """ try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_locale_is_non_default(self): """ Current locale is non-default ("de"), URL has locale prefix of default locale ("en-gb"). """ activate('de') try: self.validator('/en-gb/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_and_prefix_locales_are_non_default_and_same(self): """ Current locale is non-default ("de"), URL has locale prefix of non-default locale ("de"). """ activate('de') try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') def test_validate_current_and_prefix_locales_are_non_default_and_different(self): """ Current locale is non-default ("it"), URL has locale prefix of non-default locale ("de"). """ activate('it') try: self.validator('/de/test/') except ValidationError: self.fail('ExtendedURLValidator raised ValidationError' 'unexpectedly!') class TestURLDoesNotExistValidator(TestCase): def setUp(self): self.validator = URLDoesNotExistValidator() def test_raises_exception_for_local_urls(self): self.assertRaises(ValidationError, self.validator, '/') def test_raises_exception_for_flatpages(self): FlatPage.objects.create(title='test page', url='/test/page/') self.assertRaises(ValidationError, self.validator, '/test/page/')
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
import pytest from oscar.views import handler403, handler404, handler500 @pytest.mark.django_db def test_handler403_response_status(rf): request = rf.get('/') response = handler403(request, exception=None) assert response.status_code == 403 @pytest.mark.django_db def test_handler404_response_status(rf): request = rf.get('/') response = handler404(request, exception=None) assert response.status_code == 404 @pytest.mark.django_db def test_handler500_response_status(rf): request = rf.get('/') response = handler500(request) assert response.status_code == 500
I need integration test for this code # -*- coding: utf-8 -*- from django.forms.models import inlineformset_factory from oscar.core.loading import get_class, get_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') WishListLineForm = get_class('wishlists.forms', 'WishListLineForm') LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
I need integration test for this code # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
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 # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
# -*- 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 # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
I need integration test for this code # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
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 # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
# -*- 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 # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
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 # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
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 # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
# coding=utf-8 from django.db import IntegrityError from django.test import TestCase from django.core.exceptions import ValidationError from oscar.apps.catalogue.models import (Product, ProductClass, ProductAttribute, AttributeOption, ProductRecommendation) from oscar.test import factories class ProductTests(TestCase): def setUp(self): self.product_class, _ = ProductClass.objects.get_or_create( name='Clothing') class ProductCreationTests(ProductTests): def setUp(self): super().setUp() ProductAttribute.objects.create(product_class=self.product_class, name='Number of pages', code='num_pages', type='integer') Product.ENABLE_ATTRIBUTE_BINDING = True def tearDown(self): Product.ENABLE_ATTRIBUTE_BINDING = False def test_create_products_with_attributes(self): product = Product(upc='1234', product_class=self.product_class, title='testing') product.attr.num_pages = 100 product.save() def test_none_upc_is_represented_as_empty_string(self): product = Product(product_class=self.product_class, title='testing', upc=None) product.save() product.refresh_from_db() self.assertEqual(product.upc, '') def test_upc_uniqueness_enforced(self): Product.objects.create(product_class=self.product_class, title='testing', upc='bah') self.assertRaises(IntegrityError, Product.objects.create, product_class=self.product_class, title='testing', upc='bah') def test_allow_two_products_without_upc(self): for x in range(2): Product.objects.create(product_class=self.product_class, title='testing', upc=None) class TopLevelProductTests(ProductTests): def test_top_level_products_must_have_titles(self): product = Product(product_class=self.product_class) self.assertRaises(ValidationError, product.clean) def test_top_level_products_must_have_product_class(self): product = Product(title="Kopfhörer") self.assertRaises(ValidationError, product.clean) def test_top_level_products_are_part_of_browsable_set(self): product = Product.objects.create( product_class=self.product_class, title="Kopfhörer") self.assertEqual(set([product]), set(Product.browsable.all())) class ChildProductTests(ProductTests): def setUp(self): super().setUp() self.parent = Product.objects.create( title="Parent product", product_class=self.product_class, structure=Product.PARENT, is_discountable=False) def test_child_products_dont_need_titles(self): Product.objects.create( parent=self.parent, structure=Product.CHILD) def test_child_products_dont_need_a_product_class(self): Product.objects.create(parent=self.parent, structure=Product.CHILD) def test_child_products_inherit_fields(self): p = Product.objects.create( parent=self.parent, structure=Product.CHILD, is_discountable=True) self.assertEqual("Parent product", p.get_title()) self.assertEqual("Clothing", p.get_product_class().name) self.assertEqual(False, p.get_is_discountable()) def test_child_products_are_not_part_of_browsable_set(self): Product.objects.create( product_class=self.product_class, parent=self.parent, structure=Product.CHILD) self.assertEqual(set([self.parent]), set(Product.browsable.all())) class TestAChildProduct(TestCase): def setUp(self): clothing = ProductClass.objects.create( name='Clothing', requires_shipping=True) self.parent = clothing.products.create( title="Parent", structure=Product.PARENT) self.child = self.parent.children.create(structure=Product.CHILD) def test_delegates_requires_shipping_logic(self): self.assertTrue(self.child.is_shipping_required) class ProductAttributeCreationTests(TestCase): def test_validating_option_attribute(self): option_group = factories.AttributeOptionGroupFactory() option_1 = factories.AttributeOptionFactory(group=option_group) option_2 = factories.AttributeOptionFactory(group=option_group) pa = factories.ProductAttribute( type='option', option_group=option_group) self.assertRaises(ValidationError, pa.validate_value, 'invalid') pa.validate_value(option_1) pa.validate_value(option_2) invalid_option = AttributeOption(option='invalid option') self.assertRaises( ValidationError, pa.validate_value, invalid_option) def test_entity_attributes(self): unrelated_object = factories.PartnerFactory() attribute = factories.ProductAttributeFactory(type='entity') attribute_value = factories.ProductAttributeValueFactory( attribute=attribute, value_entity=unrelated_object) self.assertEqual(attribute_value.value, unrelated_object) class ProductRecommendationTests(ProductTests): def setUp(self): super().setUp() self.primary_product = Product.objects.create( upc='1234', product_class=self.product_class, title='Primary Product' ) def test_recommended_products_ordering(self): secondary_products = [] for i in range(5): secondary_products.append(Product.objects.create( upc='secondary%s' % i, product_class=self.product_class, title='Secondary Product #%s' % i )) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[3], ranking=5) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[1], ranking=2) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[2], ranking=4) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[4], ranking=1) ProductRecommendation.objects.create( primary=self.primary_product, recommendation=secondary_products[0], ranking=3) recommended_products = [ secondary_products[3], secondary_products[2], secondary_products[0], secondary_products[1], secondary_products[4] ] self.assertEqual(self.primary_product.sorted_recommended_products, recommended_products)
I need integration test for this code # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
from django.test import TestCase from oscar.apps.catalogue import models class TestProductClassModel(TestCase): def test_slug_is_auto_created(self): books = models.ProductClass.objects.create( name="Book", ) self.assertEqual('book', books.slug) def test_has_attribute_for_whether_shipping_is_required(self): models.ProductClass.objects.create( name="Download", requires_shipping=False, )
I need integration test for this code # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
import os import tempfile from unittest import mock from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import TestCase, override_settings from oscar.apps.catalogue.abstract_models import MissingProductImage from oscar.test import factories class TestProductImages(TestCase): def test_images_are_in_consecutive_order(self): product = factories.create_product() for i in range(4): factories.create_product_image(product=product, display_order=i) product.images.all()[2].delete() for idx, im in enumerate(product.images.all()): self.assertEqual(im.display_order, idx) def test_variant_images(self): parent = factories.ProductFactory(structure='parent') variant = factories.create_product(parent=parent) factories.create_product_image(product=variant, caption='Variant Image') all_images = variant.get_all_images() self.assertEquals(all_images.count(), 1) product_image = all_images.first() self.assertEquals(product_image.caption, 'Variant Image') def test_variant_images_fallback_to_parent(self): parent = factories.ProductFactory(structure='parent') variant = factories.create_product(parent=parent) factories.create_product_image(product=parent, caption='Parent Product Image') all_images = variant.get_all_images() self.assertEquals(all_images.count(), 1) product_image = all_images.first() self.assertEquals(product_image.caption, 'Parent Product Image') class TestMissingProductImage(StaticLiveServerTestCase): TEMP_MEDIA_ROOT = tempfile.mkdtemp() @override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT) @mock.patch('oscar.apps.catalogue.abstract_models.find') def test_symlink_creates_directories(self, mock_find): # Create a fake empty file to symlink img = tempfile.NamedTemporaryFile(delete=False) img.close() mock_find.return_value = img.name # Initialise the class with a nested path path = 'image/path.jpg' MissingProductImage(path) # Check that the directory exists image_path = os.path.join(self.TEMP_MEDIA_ROOT, path) self.assertTrue(os.path.exists(image_path)) # Clean up for f in [image_path, img.name]: os.unlink(f) for d in [os.path.join(self.TEMP_MEDIA_ROOT, 'image'), self.TEMP_MEDIA_ROOT]: os.rmdir(d) @mock.patch('oscar.apps.catalogue.abstract_models.MissingProductImage.symlink_missing_image') def test_no_symlink_when_no_media_root(self, mock_symlink): MissingProductImage() self.assertEqual(mock_symlink.call_count, 0)
I need integration test for this code # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
from django.test import TestCase from django.test.utils import override_settings from oscar.apps.catalogue.search_handlers import ( get_product_search_handler_class, ) class TestSearchHandler(object): pass class TestProductSearchHandlerSetting(TestCase): def test_product_search_handler_setting(self): """ Test that the `OSCAR_PRODUCT_SEARCH_HANDLER` setting, when set, dictates the return value of the `get_product_search_handler_class` function. """ handler_override = 'tests.integration.catalogue.test_product_search_handler_setting.TestSearchHandler' with override_settings(OSCAR_PRODUCT_SEARCH_HANDLER=handler_override): handler_class = get_product_search_handler_class() self.assertEqual(handler_class, TestSearchHandler)
I need integration test for this code # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
I need integration test for this code # -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
from django.test import TestCase from oscar.apps.catalogue.reviews import forms from oscar.test.factories import UserFactory, create_product class TestReviewForm(TestCase): def test_cleans_title(self): product = create_product() reviewer = UserFactory() data = { 'title': ' This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } form = forms.ProductReviewForm( product=product, user=reviewer, data=data) assert form.is_valid() review = form.save() assert review.title == "This product is lovely" def test_validates_empty_data_correctly(self): form = forms.ProductReviewForm(product=None, user=None, data={}) assert form.is_valid() is False def test_validates_correctly(self): data = { 'title': 'This product is lovely', 'body': 'I really like this cheese', 'score': 0, 'name': 'JR Hartley', 'email': 'hartley@example.com' } form = forms.ProductReviewForm(product=None, user=None, data=data) assert form.is_valid() class TestVoteForm(TestCase): def setUp(self): self.product = create_product() self.reviewer = UserFactory() self.voter = UserFactory() self.review = self.product.reviews.create( title='This is nice', score=3, body="This is the body", user=self.reviewer) def test_allows_real_users_to_vote(self): form = forms.VoteForm(self.review, self.voter, data={'delta': 1}) self.assertTrue(form.is_valid()) def test_prevents_users_from_voting_more_than_once(self): self.review.vote_up(self.voter) form = forms.VoteForm(self.review, self.voter, data={'delta': 1}) self.assertFalse(form.is_valid()) self.assertTrue(len(form.errors['__all__']) > 0) def test_prevents_users_voting_on_their_own_reviews(self): form = forms.VoteForm(self.review, self.reviewer, data={'delta': 1}) self.assertFalse(form.is_valid()) self.assertTrue(len(form.errors['__all__']) > 0)