Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve test suite
Patryk Zawadzkid629135f843d
diff --git a/pytest.ini b/pytest.iniindex 4345aed91e..ea85c62c76 100644--- a/pytest.ini+++ b/pytest.ini@@ -1,2 +1,5 @@[pytest]-DJANGO_SETTINGS_MODULE=saleor.test_settings+norecursedirs =+ .*+ node_modules+DJANGO_SETTINGS_MODULE = saleor.test_settingsdiff --git a/saleor/cart/test_cart.py b/saleor/cart/test_cart.pyindex 16c0b5c3a7..0bdb812db7 100755--- a/saleor/cart/test_cart.py+++ b/saleor/cart/test_cart.py@@ -6,14 +6,14 @@ from django.test import TestCasefrom django.utils.encoding import smart_textfrom mock import MagicMockfrom prices import Price+import pytestfrom satchless.item import InsufficientStockfrom . import Cart, SessionCart-from .forms import AddToCartForm, ReplaceCartLineForm, ReplaceCartLineFormSet+from . import forms+from .forms import ReplaceCartLineForm, ReplaceCartLineFormSetfrom ..product.models import (ProductVariant, StockedProduct, PhysicalProduct)-__all__ = ['CartTest', 'BigShipCartFormTest']-class BigShip(ProductVariant, StockedProduct, PhysicalProduct):name = models.CharField(max_length=250)@@ -24,6 +24,10 @@ class BigShip(ProductVariant, StockedProduct, PhysicalProduct):def get_slug(self):return 'bigship'+ @property+ def product(self):+ return self+class ShipPhoto(ProductVariant, PhysicalProduct):name = models.CharField(max_length=250)@@ -31,154 +35,120 @@ class ShipPhoto(ProductVariant, PhysicalProduct):def get_slug(self):return 'bigship-photo'+ @property+ def product(self):+ return self+-class BigShipCartForm(AddToCartForm):+class AddToCartForm(forms.AddToCartForm):def get_variant(self, cleaned_data):return self.product+stock_product = BigShip(name='BigShip', stock=10,price=Price(10, currency='USD'), weight=Decimal(123))-stock_product.product = stock_product-digital_product = ShipPhoto(price=Price(10, currency='USD'))-digital_product.product = digital_product---class CartTest(TestCase):-- def test_check_quantity(self):- """- Stock limit works- """- cart = Cart(session_cart=MagicMock())-- def illegal():- cart.add(stock_product, 100)-- self.assertRaises(InsufficientStock, illegal)- self.assertFalse(cart)-- def test_add_adds_to_session_cart(self):- cart = Cart(session_cart=SessionCart())- cart.add(stock_product, 10)- self.assertEqual(cart.session_cart.count(), 10)- self.assertTrue(cart.session_cart.modified)- self.assertEqual(cart.session_cart[0].product,- smart_text(stock_product))---class BigShipCartFormTest(TestCase):-- def setUp(self):- self.cart = Cart(MagicMock())- self.post = {'quantity': 5}-- def test_quantity(self):- """- BigShipCartForm works with correct quantity value on empty cart- """- form = BigShipCartForm(- self.post, cart=self.cart, product=stock_product)- self.assertTrue(form.is_valid())- self.assertFalse(self.cart)- form.save()- product_quantity = self.cart.get_line(stock_product).quantity- self.assertEqual(product_quantity, 5, 'Bad quantity')-- def test_max_quantity(self):- """- BigShipCartForm works with correct product stock value- """- form = BigShipCartForm(- self.post, cart=self.cart, product=stock_product)- self.assertTrue(form.is_valid())- form.save()- form = BigShipCartForm(- self.post, cart=self.cart, product=stock_product)- self.assertTrue(form.is_valid())- form.save()- product_quantity = self.cart.get_line(stock_product).quantity- self.assertEqual(product_quantity, 10,- '%s is the bad quantity value' % (product_quantity,))-- def test_too_big_quantity(self):- """- BigShipCartForm works with not correct quantity value'- """- form = BigShipCartForm({'quantity': 15}, cart=self.cart,- product=stock_product)- self.assertFalse(form.is_valid())- self.assertFalse(self.cart)-- def test_clean_quantity_product(self):- """- Is BigShipCartForm works with not stocked product- """- cart = Cart(session_cart=MagicMock())- self.post['quantity'] = 999- form = BigShipCartForm(self.post, cart=cart, product=digital_product)- self.assertTrue(form.is_valid(), 'Form doesn\'t valitate')- self.assertFalse(cart, 'Cart isn\'t empty')- form.save()- self.assertTrue(cart, 'Cart is empty')---class ReplaceCartLineFormTest(TestCase):-- def setUp(self):- self.cart = Cart(session_cart=MagicMock())-- def test_quantity(self):- """- ReplaceCartLineForm works with correct quantity value- """- form = ReplaceCartLineForm({'quantity': 5}, cart=self.cart,- product=stock_product)- self.assertTrue(form.is_valid())- form.save()- form = ReplaceCartLineForm({'quantity': 5}, cart=self.cart,- product=stock_product)- self.assertTrue(form.is_valid())- form.save()- product_quantity = self.cart.get_line(stock_product).quantity- self.assertEqual(product_quantity, 5,- '%s is the bad quantity value' % (product_quantity,))-- def test_too_big_quantity(self):- """- Is ReplaceCartLineForm works with to big quantity value- """- form = ReplaceCartLineForm({'quantity': 15}, cart=self.cart,- product=stock_product)- self.assertFalse(form.is_valid())---class ReplaceCartLineFormSetTest(TestCase):-- def test_save(self):- post = {- 'form-TOTAL_FORMS': 2,- 'form-INITIAL_FORMS': 2,- 'form-0-quantity': 5,- 'form-1-quantity': 5}- cart = Cart(session_cart=MagicMock())- cart.add(stock_product, 5)- cart.add(digital_product, 100)- form = ReplaceCartLineFormSet(post, cart=cart)- self.assertTrue(form.is_valid())- form.save()- product_quantity = cart.get_line(stock_product).quantity- self.assertEqual(product_quantity, 5,- '%s is the bad quantity value' % (product_quantity,))---class SessionCartTest(TestCase):-- def test_sessioncart_get_price_per_item(self):- cart = Cart(SessionCart())- cart.add(stock_product, quantity=10)- cart_price = cart[0].get_price_per_item()- sessioncart_price = cart.session_cart[0].get_price_per_item()- self.assertTrue(isinstance(sessioncart_price, Price))- self.assertEqual(cart_price, sessioncart_price)-+non_stock_product = ShipPhoto(price=Price(10, currency='USD'))+++def test_cart_checks_quantity():+ cart = Cart(session_cart=MagicMock())+ with pytest.raises(InsufficientStock):+ cart.add(stock_product, 100)+ assert not cart+++def test_cart_add_adds_to_session_cart():+ cart = Cart(session_cart=SessionCart())+ cart.add(stock_product, 10)+ assert cart.session_cart.count() == 10+ assert cart.session_cart.modified+ assert cart.session_cart[0].product == smart_text(stock_product)+++def test_quantity_is_correctly_saved():+ cart = Cart(session_cart=MagicMock())+ data = {'quantity': 5}+ form = AddToCartForm(data, cart=cart, product=stock_product)+ assert form.is_valid()+ assert not cart+ form.save()+ product_quantity = cart.get_line(stock_product).quantity+ assert product_quantity == 5+++def test_multiple_actions_result_in_combined_quantity():+ cart = Cart(session_cart=MagicMock())+ data = {'quantity': 5}+ form = AddToCartForm(data, cart=cart, product=stock_product)+ assert form.is_valid()+ form.save()+ form = AddToCartForm(data, cart=cart, product=stock_product)+ assert form.is_valid()+ form.save()+ product_quantity = cart.get_line(stock_product).quantity+ assert product_quantity == 10+++def test_excessive_quantity_is_rejected():+ cart = Cart(session_cart=MagicMock())+ data = {'quantity': 15}+ form = AddToCartForm(data, cart=cart, product=stock_product)+ assert not form.is_valid()+ assert not cart+++def test_any_quantity_is_valid_for_non_stock_products():+ cart = Cart(session_cart=MagicMock())+ data = {'quantity': 999}+ form = AddToCartForm(data, cart=cart, product=non_stock_product)+ assert form.is_valid()+ assert not cart+ form.save()+ assert cart+++def test_replace_form_replaces_quantity():+ cart = Cart(session_cart=MagicMock())+ data = {'quantity': 5}+ form = ReplaceCartLineForm(data, cart=cart, product=stock_product)+ assert form.is_valid()+ form.save()+ product_quantity = cart.get_line(stock_product).quantity+ assert product_quantity == 5+ form = ReplaceCartLineForm(data, cart=cart, product=stock_product)+ assert form.is_valid()+ form.save()+ product_quantity = cart.get_line(stock_product).quantity+ assert product_quantity == 5+++def test_replace_form_rejects_excessive_quantity():+ cart = Cart(session_cart=MagicMock())+ data = {'quantity': 15}+ form = ReplaceCartLineForm(data, cart=cart, product=stock_product)+ assert not form.is_valid()+++def test_replace_formset_works():+ cart = Cart(session_cart=MagicMock())+ cart.add(stock_product, 5)+ cart.add(non_stock_product, 100)+ data = {+ 'form-TOTAL_FORMS': 2,+ 'form-INITIAL_FORMS': 2,+ 'form-0-quantity': 5,+ 'form-1-quantity': 5}+ form = ReplaceCartLineFormSet(data, cart=cart)+ assert form.is_valid()+ form.save()+ product_quantity = cart.get_line(stock_product).quantity+ assert product_quantity == 5+++def test_session_cart_returns_correct_prices():+ cart = Cart(session_cart=SessionCart())+ cart.add(stock_product, quantity=10)+ cart_price = cart[0].get_price_per_item()+ sessioncart_price = cart.session_cart[0].get_price_per_item()+ assert cart_price == sessioncart_pricediff --git a/saleor/checkout/test_checkout.py b/saleor/checkout/test_checkout.pyindex 50740c97d4..d12230cf6b 100644--- a/saleor/checkout/test_checkout.py+++ b/saleor/checkout/test_checkout.py@@ -1,8 +1,9 @@+from django.contrib.auth.models import AnonymousUserfrom django.test import TestCasefrom mock import MagicMock, patchfrom . import BillingAddressStep, ShippingStep-from ..checkout import Checkout, STORAGE_SESSION_KEY+from ..checkout import STORAGE_SESSION_KEYfrom ..checkout.steps import BaseAddressStepfrom ..userprofile.models import Address@@ -19,89 +20,76 @@ NEW_ADDRESS = {'company_name': 'Test'}-class TestBaseAddressStep(TestCase):+def test_base_address_step_works(rf):+ request = rf.post('/checkout/', NEW_ADDRESS)+ request.user = AnonymousUser()+ address = Address(**NEW_ADDRESS)+ step = BaseAddressStep(request, storage={}, address=address)+ assert step.forms_are_valid()+ assert step.address.first_name == 'Test'- def test_new_method(self):- '''- Test the BaseAddressStep managment form when method is set to 'new'- and user isn't authenticated.- '''- request = MagicMock()- request.user.is_authenticated.return_value = False- request.POST = NEW_ADDRESS.copy()- step = BaseAddressStep(request, {}, Address(**NEW_ADDRESS))- self.assertTrue(step.forms_are_valid(), "Forms don't validate.")- self.assertEqual(step.address.first_name, 'Test')+def test_billing_address_save_without_address(rf):+ data = dict(NEW_ADDRESS, email='[email protected]')+ request = rf.post('/checkout/', data)+ request.user = AnonymousUser()+ storage = {}+ step = BillingAddressStep(request, storage)+ assert step.process() is None+ assert isinstance(storage['address'], dict)+ assert storage['address']['first_name'] == 'Test'-class TestBillingAddressStep(TestCase):- def test_address_save_without_address(self):- request = MagicMock()- request.user.is_authenticated.return_value = False- request.POST = dict(NEW_ADDRESS, email='[email protected]')- storage = {}- step = BillingAddressStep(request, storage)- self.assertEquals(step.process(), None)- self.assertEqual(type(storage['address']), dict)- self.assertEqual(storage['address']['first_name'], 'Test')+def test_billing_address_save_with_address_in_checkout(rf):+ data = dict(NEW_ADDRESS, email='[email protected]')+ request = rf.post('/checkout/', data)+ request.user = AnonymousUser()+ storage = {'address': {}}+ step = BillingAddressStep(request, storage)+ assert step.forms_are_valid()- def test_address_save_with_address_in_checkout(self):- request = MagicMock()- request.user.is_authenticated.return_value = False- request.POST = dict(NEW_ADDRESS, email='[email protected]')- storage = {'address': {}}- step = BillingAddressStep(request, storage)- self.assertTrue(step.forms_are_valid(), "Forms don't validate.")+def test_shipping_step_save_without_address(rf):+ data = dict(NEW_ADDRESS, method='dummy_shipping')+ request = rf.post('/checkout/', data)+ request.user = AnonymousUser()+ request.session = {STORAGE_SESSION_KEY: {}}+ group = MagicMock()+ group.address = None+ storage = {'address': NEW_ADDRESS.copy()}+ step = ShippingStep(request, storage, group)+ assert step.forms_are_valid()+ step.save()+ assert isinstance(storage['address'], dict)-class TestShippingStep(TestCase):- @patch.object(Address, 'save')- def test_address_save_without_address(self, mock_save):- request = MagicMock()- request.user.is_authenticated.return_value = False- request.session = {}- request.POST = dict(NEW_ADDRESS, method='dummy_shipping')- request.session = {STORAGE_SESSION_KEY: {}}- group = MagicMock()- group.address = None- storage = {'address': NEW_ADDRESS}- step = ShippingStep(request, storage, group)- self.assertTrue(step.forms_are_valid(), "Forms don't validate.")- step.save()- self.assertEqual(mock_save.call_count, 0)- self.assertTrue(isinstance(storage['address'], dict),- 'dict expected')+def test_shipping_step_save_with_address_in_group(rf):+ data = dict(NEW_ADDRESS, method='dummy_shipping')+ request = rf.post('/checkout/', data)+ request.user = AnonymousUser()+ request.session = {}+ group = MagicMock()+ group.address = NEW_ADDRESS.copy()+ storage = {'address': NEW_ADDRESS.copy()}+ step = ShippingStep(request, storage, group)+ assert step.forms_are_valid()+ step.save()+ assert storage['address'] == NEW_ADDRESS- @patch.object(Address, 'save')- def test_address_save_with_address_in_group(self, mock_save):- request = MagicMock()- request.user.is_authenticated.return_value = False- request.session = {}- request.POST = dict(NEW_ADDRESS, method='dummy_shipping')- group = MagicMock()- group.address = NEW_ADDRESS- storage = {'address': NEW_ADDRESS}- step = ShippingStep(request, storage, group)- self.assertTrue(step.forms_are_valid(), "Forms don't validate.")- step.save()- self.assertEqual(mock_save.call_count, 0)- @patch.object(Address, 'save')- def test_address_save_with_address_in_checkout(self, mock_save):- request = MagicMock()- request.user.is_authenticated.return_value = False- request.session = {}- request.POST = dict(NEW_ADDRESS, method='dummy_shipping')- original_billing_address = {'first_name': 'Change',- 'last_name': 'Me',- 'id': 10}- group = MagicMock()- group.address = None- storage = {'address': original_billing_address}- step = ShippingStep(request, storage, group)- self.assertTrue(step.forms_are_valid(), "Forms don't validate.")- step.save()- self.assertEqual(mock_save.call_count, 0)- self.assertEqual(storage['address'], NEW_ADDRESS)+def test_shipping_step_save_with_address_in_checkout(rf):+ data = dict(NEW_ADDRESS, method='dummy_shipping')+ request = rf.post('/checkout/', data)+ request.user = AnonymousUser()+ request.session = {}+ group = MagicMock()+ group.address = None+ storage = {+ 'address': {+ 'first_name': 'Change',+ 'last_name': 'Me',+ 'id': 10}}+ step = ShippingStep(request, storage, group)+ assert step.forms_are_valid()+ step.save()+ assert storage['address'] == NEW_ADDRESSdiff --git a/saleor/registration/test_registration.py b/saleor/registration/test_registration.pyindex 66a69b5ee4..a8312b505f 100644--- a/saleor/registration/test_registration.py+++ b/saleor/registration/test_registration.py@@ -28,57 +28,48 @@ class SessionMock(Mock):pass-class LoginUrlsTestCase(TestCase):- """Tests login url generation."""-- def test_facebook_login_url(self):- """Facebook login url is properly generated"""- facebook_client = FacebookClient(local_host='localhost')- facebook_login_url = URL(facebook_client.get_login_uri())- query = facebook_login_url.query_params()- callback_url = URL(query['redirect_uri'][0])- func, _args, kwargs = resolve(callback_url.path())- self.assertEquals(func, oauth_callback)- self.assertEquals(kwargs['service'], FACEBOOK)- self.assertEqual(query['scope'][0], FacebookClient.scope)- self.assertEqual(query['client_id'][0], str(FacebookClient.client_id))-- def test_google_login_url(self):- """Google login url is properly generated"""- google_client = GoogleClient(local_host='local_host')- google_login_url = URL(google_client.get_login_uri())- params = google_login_url.query_params()- callback_url = URL(params['redirect_uri'][0])- func, _args, kwargs = resolve(callback_url.path())- self.assertEquals(func, oauth_callback)- self.assertEquals(kwargs['service'], GOOGLE)- self.assertTrue(params['scope'][0] in GoogleClient.scope)- self.assertEqual(params['client_id'][0], str(GoogleClient.client_id))---class ResponseParsingTestCase(TestCase):-- def setUp(self):- self.response = MagicMock()-- def test_parse_json(self):- """OAuth2 client is able to parse json response"""- self.response.headers = {'Content-Type': JSON_MIME_TYPE}- self.response.json.return_value = sentinel.json_content- content = parse_response(self.response)- self.assertEquals(content, sentinel.json_content)-- def test_parse_urlencoded(self):- """OAuth2 client is able to parse urlencoded response"""- self.response.headers = {'Content-Type': URLENCODED_MIME_TYPE}- self.response.text = 'key=value&multi=a&multi=b'- content = parse_response(self.response)- self.assertEquals(content, {'key': 'value', 'multi': ['a', 'b']})---class TestClient(OAuth2Client):+def test_facebook_login_url():+ facebook_client = FacebookClient(local_host='localhost')+ facebook_login_url = URL(facebook_client.get_login_uri())+ query = facebook_login_url.query_params()+ callback_url = URL(query['redirect_uri'][0])+ func, _args, kwargs = resolve(callback_url.path())+ assert func is oauth_callback+ assert kwargs['service'] == FACEBOOK+ assert query['scope'][0] == FacebookClient.scope+ assert query['client_id'][0] == str(FacebookClient.client_id)+++def test_google_login_url():+ google_client = GoogleClient(local_host='local_host')+ google_login_url = URL(google_client.get_login_uri())+ params = google_login_url.query_params()+ callback_url = URL(params['redirect_uri'][0])+ func, _args, kwargs = resolve(callback_url.path())+ assert func is oauth_callback+ assert kwargs['service'] == GOOGLE+ assert params['scope'][0] == GoogleClient.scope+ assert params['client_id'][0] == str(GoogleClient.client_id)+++def test_parse_json():+ response = MagicMock()+ response.headers = {'Content-Type': JSON_MIME_TYPE}+ response.json.return_value = sentinel.json_content+ content = parse_response(response)+ assert content == sentinel.json_content+++def test_parse_urlencoded():+ response = MagicMock()+ response.headers = {'Content-Type': URLENCODED_MIME_TYPE}+ response.text = 'key=value&multi=a&multi=b'+ content = parse_response(response)+ assert content == {'key': 'value', 'multi': ['a', 'b']}+++class Client(OAuth2Client):"""OAuth2Client configured for testing purposes."""-service = sentinel.serviceclient_id = sentinel.client_id@@ -124,12 +115,12 @@ class AccessTokenTestCase(BaseCommunicationTestCase):def test_token_is_obtained_on_construction(self):"""OAuth2 client asks for access token if interim code is available"""self.access_token_response.status_code = sentinel.ok- TestClient(local_host='http://localhost', code=sentinel.code)+ Client(local_host='http://localhost', code=sentinel.code)self.requests_mock.post.assert_called_once()def test_token_success(self):"""OAuth2 client properly obtains access token"""- client = TestClient(local_host='http://localhost')+ client = Client(local_host='http://localhost')self.access_token_response.status_code = sentinel.okaccess_token = client.get_access_token(code=sentinel.code)self.assertEquals(access_token, sentinel.access_token)@@ -145,7 +136,7 @@ class AccessTokenTestCase(BaseCommunicationTestCase):def test_token_failure(self):"""OAuth2 client properly reacts to access token fetch failure"""- client = TestClient(local_host='http://localhost')+ client = Client(local_host='http://localhost')self.access_token_response.status_code = sentinel.failself.assertRaises(ValueError, client.get_access_token,code=sentinel.code)@@ -162,7 +153,7 @@ class UserInfoTestCase(BaseCommunicationTestCase):def test_user_info_success(self):"""OAuth2 client properly fetches user info"""- client = TestClient(local_host='http://localhost')+ client = Client(local_host='http://localhost')self.parse_mock.return_value = sentinel.user_infoself.user_info_response.status_code = sentinel.okuser_info = client.get_user_info()@@ -170,7 +161,7 @@ class UserInfoTestCase(BaseCommunicationTestCase):def test_user_data_failure(self):"""OAuth2 client reacts well to user info fetch failure"""- client = TestClient(local_host='http://localhost')+ client = Client(local_host='http://localhost')self.assertRaises(ValueError, client.get_user_info)def test_google_user_data_email_not_verified(self):