def test_long_cache_keys_shortened(self): cache_settings = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(TOP_DIR, 'test.cache'), } } long_key_string = "X" * 251 with override_settings(CACHES=cache_settings): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") # memcached limits key length to 250 cache.set(long_key_string, "hello cached world") self.assertEqual(len(w), 1) self.assertIsInstance(w[0].message, CacheKeyWarning) # Activate optional cache key length checker cache_settings['default']['KEY_FUNCTION'] = 'mainsite.utils.filter_cache_key' with override_settings(CACHES=cache_settings): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") # memcached limits key length to 250 cache.set(long_key_string, "hello cached world") self.assertEqual(len(w), 0) retrieved = cache.get(long_key_string) self.assertEqual(retrieved, "hello cached world")
def test_setting_instance_check(self): with override_settings(RECAPTCHA_PROXY="not a dict"): with self.assertRaises(ImproperlyConfigured) as error: reload(captcha) self.assertEqual(error.exception.args, ( "Setting RECAPTCHA_PROXY is not of type", dict) ) with override_settings(RECAPTCHA_VERIFY_REQUEST_TIMEOUT="not an int"): with self.assertRaises(ImproperlyConfigured) as error: reload(captcha) self.assertEqual(error.exception.args, ( "Setting RECAPTCHA_VERIFY_REQUEST_TIMEOUT is not of type", int) ) with override_settings(RECAPTCHA_DOMAIN=1): with self.assertRaises(ImproperlyConfigured) as error: reload(captcha) self.assertEqual(error.exception.args, ( "Setting RECAPTCHA_DOMAIN is not of type", str) ) with override_settings(RECAPTCHA_PUBLIC_KEY=1): with self.assertRaises(ImproperlyConfigured) as error: reload(captcha) self.assertEqual(error.exception.args, ( "Setting RECAPTCHA_PUBLIC_KEY is not of type", str) ) with override_settings(RECAPTCHA_PRIVATE_KEY=1): with self.assertRaises(ImproperlyConfigured) as error: reload(captcha) self.assertEqual(error.exception.args, ( "Setting RECAPTCHA_PRIVATE_KEY is not of type", str) )
def test_is_extendable(self): """ Tests that the XFrameOptionsMiddleware method that determines the X-Frame-Options header value can be overridden based on something in the request or response. """ class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware): # This is just an example for testing purposes... def get_xframe_options_value(self, request, response): if getattr(request, "sameorigin", False): return "SAMEORIGIN" if getattr(response, "sameorigin", False): return "SAMEORIGIN" return "DENY" with override_settings(X_FRAME_OPTIONS="DENY"): response = HttpResponse() response.sameorigin = True r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r["X-Frame-Options"], "SAMEORIGIN") request = HttpRequest() request.sameorigin = True r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse()) self.assertEqual(r["X-Frame-Options"], "SAMEORIGIN") with override_settings(X_FRAME_OPTIONS="SAMEORIGIN"): r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r["X-Frame-Options"], "DENY")
def test_resolver_translation(self): with override_settings(USE_SUBDOMAIN=False): url = resolve_path(project=self.translation, filename='index.html') self.assertEqual(url, '/docs/pip/ja/latest/') with override_settings(USE_SUBDOMAIN=True): url = resolve_path(project=self.translation, filename='index.html') self.assertEqual(url, '/ja/latest/')
def test_resolver_subdomain(self): with override_settings(USE_SUBDOMAIN=False): url = resolve_path(project=self.pip, filename='index.html') self.assertEqual(url, '/docs/pip/en/latest/') with override_settings(USE_SUBDOMAIN=True): url = resolve_path(project=self.pip, filename='index.html') self.assertEqual(url, '/en/latest/')
def test_resolver_private_project(self): with override_settings(USE_SUBDOMAIN=False): url = resolve(project=self.pip, private=True) self.assertEqual(url, 'http://readthedocs.org/docs/pip/en/latest/') with override_settings(USE_SUBDOMAIN=True): url = resolve(project=self.pip, private=True) self.assertEqual(url, 'http://pip.readthedocs.org/en/latest/')
def test_resolver_translation(self): with override_settings(USE_SUBDOMAIN=False): url = resolve(project=self.translation) self.assertEqual(url, 'http://readthedocs.org/docs/pip/ja/latest/') with override_settings(USE_SUBDOMAIN=True): url = resolve(project=self.translation) self.assertEqual(url, 'http://pip.readthedocs.org/ja/latest/')
def test_create_new_basket(admin_user): with override_settings(**REQUIRED_SETTINGS): shop = factories.get_default_shop() shop2 = create_shop("foobar") client = _get_client(admin_user) response = client.post("/api/shuup/basket/new/", { "shop": shop2.pk }) assert response.status_code == status.HTTP_201_CREATED basket_data = json.loads(response.content.decode("utf-8")) basket = Basket.objects.first() assert basket.key == basket_data['uuid'].split("-")[1] assert basket.shop == shop2 admin_contact = get_person_contact(admin_user) assert basket.customer == admin_contact assert basket.orderer == admin_contact assert basket.creator == admin_user # invalid shop response = client.post("/api/shuup/basket/new/", data={"shop": 1000}) assert response.status_code == status.HTTP_400_BAD_REQUEST # no shop in multishop mode response = client.post("/api/shuup/basket/new/") assert response.status_code == status.HTTP_400_BAD_REQUEST # no shop in single shop mode with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=False): response = client.post("/api/shuup/basket/new/") assert response.status_code == status.HTTP_201_CREATED basket_data = json.loads(response.content.decode("utf-8")) basket = Basket.objects.all()[1] assert basket.key == basket_data['uuid'].split("-")[1] assert basket.shop == shop assert basket.customer == admin_contact assert basket.orderer == admin_contact assert basket.creator == admin_user person = factories.create_random_person() response = client.post("/api/shuup/basket/new/", data={"customer": person.pk}) assert response.status_code == status.HTTP_201_CREATED basket_data = json.loads(response.content.decode("utf-8")) basket = Basket.objects.all()[2] assert basket.key == basket_data['uuid'].split("-")[1] assert basket.shop == shop assert basket.creator == admin_user assert basket.customer.pk == person.pk assert basket.orderer.pk == person.pk assert basket.creator.pk == admin_user.pk # Try to fetch the basket as the customer user = factories.UserFactory() person.user = user person.save() response = client.get("/api/shuup/basket/{}/".format(basket_data['uuid'])) assert response.status_code == 200 customer_basket_data = json.loads(response.content.decode("utf-8")) assert basket.key == customer_basket_data['key'] # Still same basket as before assert customer_basket_data['customer']['id'] == person.pk # Still same customer as before
def test_home_country_in_address(): with override("fi"): finnish_address = MutableAddress(country="FI") with override_settings(SHUUP_ADDRESS_HOME_COUNTRY="US"): assert "Suomi" in str(finnish_address), "When home is not Finland, Finland appears in address string" with override_settings(SHUUP_ADDRESS_HOME_COUNTRY="FI"): assert "Suomi" not in str(finnish_address), "When home is Finland, Finland does not appear in address string"
def test_limit(self): with transaction.atomic(): runtime = timezone.now() Task.objects.create(name=TEST_TASK_PATH, tags=['foo', 'bar']) RateLimitRun.objects.bulk_create([ RateLimitRun(tag='foo', created_at=runtime), RateLimitRun(tag='bar', created_at=runtime), RateLimitRun(tag='bar', created_at=runtime) ]) t1 = Task.objects.create(name=TEST_TASK_PATH, tags=['bar', 'spam']) t2 = Task.objects.create(name=TEST_TASK_PATH, tags=['foo']) with transaction.atomic(): with override_settings(ROBUST_RATE_LIMIT={ 'foo': (1, timedelta(minutes=1)), 'bar': (10, timedelta(minutes=1)) }): self.assertSequenceEqual(Task.objects.next(limit=10), [t1]) with transaction.atomic(): with override_settings(ROBUST_RATE_LIMIT={ 'foo': (3, timedelta(minutes=1)), 'bar': (2, timedelta(minutes=1)) }): self.assertSequenceEqual(Task.objects.next(limit=10), [t2])
def test_bower_get_rc_file(): """Tests that the .bowerrc file is discoverable and usable as a JSON object""" with override_settings(BOWER_RC_FILE='/path/to/rc'): assert_equal(bower.get_bower_rc_path(), '/path/to/rc') with override_settings(): assert_equal(bower.get_bower_rc_path(), os.getcwd() + '/.bowerrc')
def test_get_resource_name(): view = APIView() context = {'view': view} with override_settings(JSON_API_FORMAT_TYPES=None): assert 'APIViews' == utils.get_resource_name(context), 'not formatted' context = {'view': view} with override_settings(JSON_API_FORMAT_TYPES='dasherize'): assert 'api-views' == utils.get_resource_name(context), 'derived from view' view.model = get_user_model() assert 'users' == utils.get_resource_name(context), 'derived from view model' view.resource_name = 'custom' assert 'custom' == utils.get_resource_name(context), 'manually set on view' view.response = Response(status=403) assert 'errors' == utils.get_resource_name(context), 'handles 4xx error' view.response = Response(status=500) assert 'errors' == utils.get_resource_name(context), 'handles 500 error' view = GenericAPIView() view.serializer_class = ResourceSerializer context = {'view': view} assert 'users' == utils.get_resource_name(context), 'derived from serializer' view.serializer_class.Meta.resource_name = 'rcustom' assert 'rcustom' == utils.get_resource_name(context), 'set on serializer' view = GenericAPIView() view.serializer_class = NonModelResourceSerializer context = {'view': view} assert 'users' == utils.get_resource_name(context), 'derived from non-model serializer'
def test_coupon_creation_for_supplier(rf, admin_user): """ To make things little bit more simple let's use only english as a language. """ shop = get_default_shop() supplier = Supplier.objects.create(identifier=admin_user.username) another_superuser = create_random_user(is_superuser=True, is_staff=True) supplier2 = Supplier.objects.create(identifier=another_superuser.username) supplier_provider = "shuup.testing.supplier_provider.UsernameSupplierProvider" with override_settings(LANGUAGES=[("en", "en")]): with override_settings(SHUUP_ADMIN_SUPPLIER_PROVIDER_SPEC=supplier_provider): view = CouponEditView.as_view() data = { "code": "OK", "active": True, "shop": shop.pk } coupons_before = Coupon.objects.count() request = apply_request_middleware(rf.post("/", data=data), user=admin_user) assert get_supplier(request) == supplier response = view(request, pk=None) assert response.status_code in [200, 302] assert Coupon.objects.count() == (coupons_before + 1) new_coupon = Coupon.objects.filter(supplier=supplier).first() assert new_coupon # Another superuser shouldn't see this campaign request = apply_request_middleware(rf.post("/", data=data), user=another_superuser) assert get_supplier(request) == supplier2 with pytest.raises(Http404): response = view(request, pk=new_coupon.pk)
def test_resolver_public_domain_overrides(self): with override_settings(USE_SUBDOMAIN=False): url = resolve(project=self.pip, private=True) self.assertEqual(url, 'http://readthedocs.org/docs/pip/en/latest/') url = resolve(project=self.pip, private=False) self.assertEqual(url, 'http://readthedocs.org/docs/pip/en/latest/') with override_settings(USE_SUBDOMAIN=True): url = resolve(project=self.pip, private=True) self.assertEqual( url, 'http://pip.public.readthedocs.org/en/latest/') url = resolve(project=self.pip, private=False) self.assertEqual( url, 'http://pip.public.readthedocs.org/en/latest/') # Domain overrides PUBLIC_DOMAIN self.domain = fixture.get( Domain, domain='docs.foobar.com', project=self.pip, canonical=True, ) with override_settings(USE_SUBDOMAIN=True): url = resolve(project=self.pip, private=True) self.assertEqual(url, 'http://docs.foobar.com/en/latest/') url = resolve(project=self.pip, private=False) self.assertEqual(url, 'http://docs.foobar.com/en/latest/') with override_settings(USE_SUBDOMAIN=False): url = resolve(project=self.pip, private=True) self.assertEqual(url, 'http://docs.foobar.com/en/latest/') url = resolve(project=self.pip, private=False) self.assertEqual(url, 'http://docs.foobar.com/en/latest/')
def test_load_balanced_read_apps(self, mock): load_balanced_apps = { 'users': [ ('users_db1', 5), ] } with override_settings( LOAD_BALANCED_APPS=load_balanced_apps, DATABASES = { 'default': _get_db_config('default'), 'users_db1': _get_db_config('users_db1')}): manager = ConnectionManager() self.assertEqual( manager.get_load_balanced_read_db_alais('users', default="default_option"), 'users_db1' ) with override_settings(LOAD_BALANCED_APPS=load_balanced_apps): # load_balanced_db should be part of settings.DATABASES with self.assertRaises(AssertionError): ConnectionManager().get_load_balanced_read_db_alais('users') # If `LOAD_BALANCED_APPS` is not set for an app, it should point to default kwarg manager = ConnectionManager() self.assertEqual( manager.get_load_balanced_read_db_alais('users', default='default_option'), 'default_option' )
def test_read_load_balancing(self, *args): reporting_dbs = { 'ucr': { 'WRITE': 'ucr', 'READ': [('ucr', 8), ('other', 1), ('default', 1)] }, } with override_settings(REPORTING_DATABASES=reporting_dbs): manager = ConnectionManager() self.assertEqual(manager.db_connection_map, { 'default': 'postgresql+psycopg2://:@localhost:5432/default', 'ucr': 'postgresql+psycopg2://:@localhost:5432/ucr', 'other': 'postgresql+psycopg2://:@localhost:5432/other' }) # test that load balancing works with a 10% margin for randomness total_requests = 10000 randomness_margin = total_requests * 0.1 total_weighting = sum(db[1] for db in reporting_dbs['ucr']['READ']) expected = { alias: weight * total_requests // total_weighting for alias, weight in reporting_dbs['ucr']['READ'] } balanced = Counter(manager.get_load_balanced_read_db_alais('ucr') for i in range(total_requests)) for db, requests in balanced.items(): self.assertAlmostEqual(requests, expected[db], delta=randomness_margin) with override_settings(REPORTING_DATABASES={'default': 'default'}): manager = ConnectionManager() self.assertEqual( ['default', 'default', 'default'], [manager.get_load_balanced_read_db_alais('default') for i in range(3)] )
def test_domain_resolver_translation(self): with override_settings(USE_SUBDOMAIN=False): url = resolve_domain(project=self.translation) self.assertEqual(url, 'readthedocs.org') with override_settings(USE_SUBDOMAIN=True): url = resolve_domain(project=self.translation) self.assertEqual(url, 'pip.readthedocs.org')
def test_override_settings_nested(self): """ override_settings uses the actual _wrapped attribute at runtime, not when it was instantiated. """ with self.assertRaises(AttributeError): getattr(settings, 'TEST') with self.assertRaises(AttributeError): getattr(settings, 'TEST2') inner = override_settings(TEST2='override') with override_settings(TEST='override'): self.assertEqual('override', settings.TEST) with inner: self.assertEqual('override', settings.TEST) self.assertEqual('override', settings.TEST2) # inner's __exit__ should have restored the settings of the outer # context manager, not those when the class was instantiated self.assertEqual('override', settings.TEST) with self.assertRaises(AttributeError): getattr(settings, 'TEST2') with self.assertRaises(AttributeError): getattr(settings, 'TEST') with self.assertRaises(AttributeError): getattr(settings, 'TEST2')
def test_resolver_subproject_single_version(self): self.subproject.single_version = True with override_settings(USE_SUBDOMAIN=False): url = resolve_path(project=self.subproject, filename='index.html') self.assertEqual(url, '/docs/pip/projects/sub/') with override_settings(USE_SUBDOMAIN=True): url = resolve_path(project=self.subproject, filename='index.html') self.assertEqual(url, '/projects/sub/')
def test_resolver_single_version(self): self.pip.single_version = True with override_settings(USE_SUBDOMAIN=False): url = resolve(project=self.pip) self.assertEqual(url, 'http://readthedocs.org/docs/pip/') with override_settings(USE_SUBDOMAIN=True): url = resolve(project=self.pip) self.assertEqual(url, 'http://pip.readthedocs.org/')
def test_product_categories(settings): with override_settings(SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES=True): shop_product = get_default_shop_product() shop_product.categories.clear() shop_product.primary_category = None shop_product.save() assert not shop_product.primary_category assert not shop_product.categories.count() category_one = CategoryFactory() category_two = CategoryFactory() shop_product.categories = Category.objects.all() assert shop_product.primary_category # this was automatically populated assert shop_product.primary_category.pk == category_one.pk # it's the first one also shop_product.categories.clear() shop_product.primary_category = category_one shop_product.save() assert shop_product.primary_category == category_one assert category_one in shop_product.categories.all() # test removing shop_product.categories.remove(category_one) shop_product.refresh_from_db() assert not shop_product.categories.exists() shop_product.categories.add(category_one) category_one.soft_delete() assert not shop_product.categories.exists() with override_settings(SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES=False): shop_product.categories.clear() shop_product.primary_category = None shop_product.save() assert not shop_product.primary_category assert not shop_product.categories.count() category_one = CategoryFactory() category_two = CategoryFactory() shop_product.categories = Category.objects.all() assert not shop_product.primary_category # this was NOT automatically populated shop_product.categories.clear() shop_product.primary_category = category_one shop_product.save() assert shop_product.primary_category == category_one assert category_one not in shop_product.categories.all()
def test_settings(self): # test old Django configuration template_dirs = ['a', 'b'] with override_settings(TEMPLATES=[{'BACKEND': '1'}], TEMPLATE_DIRS=template_dirs): self.assertListEqual(get_template_dirs(), template_dirs) # test Django > 1.8 with override_settings(TEMPLATES=[{'BACKEND': '1', 'DIRS': template_dirs}]): self.assertListEqual(get_template_dirs(), template_dirs)
def test_resolver_force_language(self): with override_settings(USE_SUBDOMAIN=False): url = resolve_path( project=self.pip, filename='index.html', language='cz') self.assertEqual(url, '/docs/pip/cz/latest/') with override_settings(USE_SUBDOMAIN=True): url = resolve_path( project=self.pip, filename='index.html', language='cz') self.assertEqual(url, '/cz/latest/')
def test_resolver_force_version(self): with override_settings(USE_SUBDOMAIN=False): url = resolve_path( project=self.pip, filename='index.html', version_slug='foo') self.assertEqual(url, '/docs/pip/en/foo/') with override_settings(USE_SUBDOMAIN=True): url = resolve_path( project=self.pip, filename='index.html', version_slug='foo') self.assertEqual(url, '/en/foo/')
def test_resolver_subproject(self): with override_settings(USE_SUBDOMAIN=False): url = resolve(project=self.subproject) self.assertEqual( url, 'http://readthedocs.org/docs/pip/projects/sub/ja/latest/') with override_settings(USE_SUBDOMAIN=True): url = resolve(project=self.subproject) self.assertEqual( url, 'http://pip.readthedocs.org/projects/sub/ja/latest/')
def test_not_called_on_update(self, patient_query, subscribe): with override_settings(GLOSS_ENABLED=False): episode = self.patient.create_episode() with override_settings(GLOSS_ENABLED=True): episode.save() self.assertFalse(patient_query.called) self.assertFalse(subscribe.called)
def test_resolver_force_single_version(self): self.pip.single_version = False with override_settings(USE_SUBDOMAIN=False): url = resolve_path( project=self.pip, filename='index.html', single_version=True) self.assertEqual(url, '/docs/pip/') with override_settings(USE_SUBDOMAIN=True): url = resolve_path( project=self.pip, filename='index.html', single_version=True) self.assertEqual(url, '/')
def test_bower_get_executable(): """Tests that the get_bower_cmd() finds the path to the bower executable""" # Verify django settings override option with override_settings(BOWER_CMD='/override/path'): assert_equal(bower.get_bower_executable_path(), '/override/path') with override_settings(): with mock.patch('django_collectstatic_bower.bower.which') as which: which.return_value = '/discovered/path' assert_equal(bower.get_bower_executable_path(), '/discovered/path')
def test_create_model4(self): """ Test multiple routers. """ with override_settings(DATABASE_ROUTERS=[AgnosticRouter(), AgnosticRouter()]): self._test_create_model("test_mltdb_crmo4", should_run=True) with override_settings(DATABASE_ROUTERS=[MigrateNothingRouter(), MigrateEverythingRouter()]): self._test_create_model("test_mltdb_crmo4", should_run=False) with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter(), MigrateNothingRouter()]): self._test_create_model("test_mltdb_crmo4", should_run=True)
def test_404_response(self): command = runserver.Command() handler = command.get_handler(use_static_handler=True, insecure_serving=True) missing_static_file = os.path.join(settings.STATIC_URL, 'unknown.css') req = RequestFactory().get(missing_static_file) with override_settings(DEBUG=False): response = handler.get_response(req) self.assertEqual(response.status_code, 404) with override_settings(DEBUG=True): response = handler.get_response(req) self.assertEqual(response.status_code, 404)
def test_browser_checkout_vertical(browser, live_server, settings): with override_settings(SHUUP_CHECKOUT_VIEW_SPEC=("shuup.front.views.checkout:SinglePageCheckoutView")): # initialize product_name = "Test Product" get_default_shop() pm = get_default_payment_method() sm = get_default_shipping_method() product = create_orderable_product(product_name, "test-123", price=100) OrderStatus.objects.create( identifier="initial", role=OrderStatusRole.INITIAL, name="initial", default=True ) # initialize test and go to front page browser = initialize_front_browser_test(browser, live_server) # check that front page actually loaded wait_until_condition(browser, lambda x: x.is_text_present("Welcome to Default!")) wait_until_condition(browser, lambda x: x.is_text_present("Newest Products")) wait_until_condition(browser, lambda x: x.is_text_present(product_name)) click_element(browser, "#product-%s" % product.pk) # open product from product list click_element(browser, "#add-to-cart-button-%s" % product.pk) # add product to basket wait_until_appeared(browser, ".cover-wrap") wait_until_disappeared(browser, ".cover-wrap") click_element(browser, "#navigation-basket-partial") # open upper basket navigation menu click_element(browser, "a[href='/basket/']") # click the link to basket in dropdown wait_until_condition(browser, lambda x: x.is_text_present("Shopping cart")) # we are in basket page wait_until_condition(browser, lambda x: x.is_text_present(product_name)) # product is in basket click_element(browser, "a[href='/checkout/']") # click link that leads to checkout wait_until_appeared(browser, "h4.panel-title") customer_name = "Test Tester" customer_street = "Test Street" customer_city = "Test City" customer_region = "CA" customer_country = "US" # Fill all necessary information browser.fill("billing-name", customer_name) browser.fill("billing-street", customer_street) browser.fill("billing-city", customer_city) browser.select("billing-country", customer_country) wait_until_appeared(browser, "select[name='billing-region_code']") browser.select("billing-region_code", customer_region) click_element(browser, "#addresses button[type='submit']") wait_until_condition(browser, lambda x: x.is_text_present("This field is required.")) # Fill the errors browser.fill("shipping-name", customer_name) browser.fill("shipping-street", customer_street) browser.fill("shipping-city", customer_city) browser.select("shipping-country", customer_country) click_element(browser, "#addresses button[type='submit']") wait_until_condition(browser, lambda x: x.is_text_present("Shipping & Payment")) wait_until_condition(browser, lambda x: x.is_text_present(sm.name)) # shipping method name is present wait_until_condition(browser, lambda x: x.is_text_present(pm.name)) # payment method name is present click_element(browser, ".btn.btn-primary.btn-lg.pull-right") # click "continue" on methods page wait_until_condition(browser, lambda x: x.is_text_present("Confirmation")) # we are indeed in confirmation page # See that all expected texts are present wait_until_condition(browser, lambda x: x.is_text_present(product_name)) wait_until_condition(browser, lambda x: x.is_text_present(sm.name)) wait_until_condition(browser, lambda x: x.is_text_present(pm.name)) wait_until_condition(browser, lambda x: x.is_text_present("Delivery")) wait_until_condition(browser, lambda x: x.is_text_present("Billing")) # check that user information is available wait_until_condition(browser, lambda x: x.is_text_present(customer_name)) wait_until_condition(browser, lambda x: x.is_text_present(customer_street)) wait_until_condition(browser, lambda x: x.is_text_present(customer_city)) wait_until_condition(browser, lambda x: x.is_text_present("United States")) browser.execute_script('document.getElementById("id_accept_terms").checked=true') # click accept terms click_element(browser, ".btn.btn-primary.btn-lg") # click "place order" wait_until_condition(browser, lambda x: x.is_text_present("Thank you for your order!")) # order succeeded
def test_fuzzy_compiling(self): with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]): call_command('compilemessages', locale=[self.LOCALE], fuzzy=True, stdout=StringIO()) with translation.override(self.LOCALE): self.assertEqual(ugettext('Lenin'), force_text('Ленин')) self.assertEqual(ugettext('Vodka'), force_text('Водка'))
def test_naturaltime(self): class naive(datetime.tzinfo): def utcoffset(self, dt): return None test_list = [ 'test', now, now - datetime.timedelta(microseconds=1), now - datetime.timedelta(seconds=1), now - datetime.timedelta(seconds=30), now - datetime.timedelta(minutes=1, seconds=30), now - datetime.timedelta(minutes=2), now - datetime.timedelta(hours=1, minutes=30, seconds=30), now - datetime.timedelta(hours=23, minutes=50, seconds=50), now - datetime.timedelta(days=1), now - datetime.timedelta(days=500), now + datetime.timedelta(seconds=1), now + datetime.timedelta(seconds=30), now + datetime.timedelta(minutes=1, seconds=30), now + datetime.timedelta(minutes=2), now + datetime.timedelta(hours=1, minutes=30, seconds=30), now + datetime.timedelta(hours=23, minutes=50, seconds=50), now + datetime.timedelta(days=1), now + datetime.timedelta(days=2, hours=6), now + datetime.timedelta(days=500), now.replace(tzinfo=naive()), now.replace(tzinfo=utc), ] result_list = [ 'test', 'now', 'now', 'a second ago', '30\xa0seconds ago', 'a minute ago', '2\xa0minutes ago', 'an hour ago', '23\xa0hours ago', '1\xa0day ago', '1\xa0year, 4\xa0months ago', 'a second from now', '30\xa0seconds from now', 'a minute from now', '2\xa0minutes from now', 'an hour from now', '23\xa0hours from now', '1\xa0day from now', '2\xa0days, 6\xa0hours from now', '1\xa0year, 4\xa0months from now', 'now', 'now', ] # Because of the DST change, 2 days and 6 hours after the chosen # date in naive arithmetic is only 2 days and 5 hours after in # aware arithmetic. result_list_with_tz_support = result_list[:] assert result_list_with_tz_support[ -4] == '2\xa0days, 6\xa0hours from now' result_list_with_tz_support[-4] == '2\xa0days, 5\xa0hours from now' orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: with translation.override('en'): self.humanize_tester(test_list, result_list, 'naturaltime') with override_settings(USE_TZ=True): self.humanize_tester(test_list, result_list_with_tz_support, 'naturaltime') finally: humanize.datetime = orig_humanize_datetime
def test_ok_views(self): # we only test ta participation from course.auth import make_sign_in_key # make sign in key for a user u = factories.UserFactory(first_name="foo", last_name="bar", status=constants.user_status.unconfirmed) sign_in_key = make_sign_in_key(u) u.sign_in_key = sign_in_key u.save() self.c.force_login(self.ta_participation.user) my_session = factories.FlowSessionFactory( participation=self.ta_participation, flow_id=self.flow_id) with override_settings(RELATE_SIGN_IN_BY_USERNAME_ENABLED=True): for url, args, kwargs, code_or_redirect in [ ("relate-sign_in_choice", [], {}, 200), ("relate-sign_in_by_email", [], {}, 200), ("relate-sign_in_stage2_with_token", [u.pk, sign_in_key], {}, "/"), ("relate-sign_in_by_user_pw", [], {}, 200), ("relate-impersonate", [], {}, 200), # because not we are testing get, while stop_impersonating view # doesn't allow get, if it return 403 instead of 302 # we think it passed test. ("relate-stop_impersonating", [], {}, 403), ("relate-check_in_for_exam", [], {}, 200), ("relate-list_available_exams", [], {}, 200), ("relate-view_start_flow", [], { "course_identifier": self.course.identifier, "flow_id": self.flow_id }, 200), ("relate-view_resume_flow", [], { "course_identifier": self.course.identifier, "flow_session_id": my_session.pk }, self.get_page_url_by_ordinal(0, flow_session_id=my_session.pk)), ("relate-user_profile", [], {}, 200), ("relate-logout", [], {}, "/"), ("relate-set_pretend_facilities", [], {}, 200), ]: with self.subTest(url=url): if "sign_in" in url: switch_to = None else: switch_to = self.ta_participation.user with self.temporarily_switch_to_user(switch_to): resp = self.c.get( reverse(url, args=args, kwargs=kwargs)) try: code = int(code_or_redirect) self.assertEqual(resp.status_code, code) except ValueError: self.assertRedirects(resp, code_or_redirect, fetch_redirect_response=False)
def test_html_export_full(event, other_event, slot, canceled_talk): from django.core.management import call_command from django.conf import settings import os.path event.primary_color = '#111111' event.save() other_event.primary_color = '#222222' other_event.save() with override_settings(COMPRESS_ENABLED=True, COMPRESS_OFFLINE=True): call_command('rebuild') regenerate_css(event.pk) regenerate_css(other_event.pk) event = Event.objects.get(slug=event.slug) assert event.settings.agenda_css_file call_command('export_schedule_html', event.slug, '--zip') paths = [ 'static/common/img/logo.svg', f'media/test/{event.settings.agenda_css_file.split("/")[-1]}', 'test/schedule/index.html', 'test/schedule/export/schedule.json', 'test/schedule/export/schedule.xcal', 'test/schedule/export/schedule.xml', 'test/schedule/export/schedule.ics', *[ f'test/speaker/{speaker.code}/index.html' for speaker in slot.submission.speakers.all() ], f'test/talk/{slot.submission.code}/index.html', f'test/talk/{slot.submission.code}.ics', ] for path in paths: full_path = os.path.join(settings.HTMLEXPORT_ROOT, 'test', path) assert os.path.exists(full_path) for path in glob(os.path.join(settings.HTMLEXPORT_ROOT, 'test/media/*')): assert event.slug in path assert other_event.slug not in path full_path = os.path.join(settings.HTMLEXPORT_ROOT, 'test.zip') assert os.path.exists(full_path) # views and templates are the same for export and online viewing, so a naive test is enough here talk_html = open( os.path.join( settings.HTMLEXPORT_ROOT, 'test', f'test/talk/{slot.submission.code}/index.html', )).read() assert talk_html.count(slot.submission.title) >= 2 speaker = slot.submission.speakers.all()[0] speaker_html = open( os.path.join(settings.HTMLEXPORT_ROOT, 'test', f'test/speaker/{speaker.code}/index.html')).read() assert speaker.name in speaker_html schedule_html = open( os.path.join(settings.HTMLEXPORT_ROOT, 'test', f'test/schedule/index.html')).read() assert 'Contact us' in schedule_html # locale assert canceled_talk.submission.title not in schedule_html schedule_json = json.load( open( os.path.join(settings.HTMLEXPORT_ROOT, f'test/test/schedule/export/schedule.json'))) assert schedule_json['schedule']['conference']['title'] == event.name schedule_ics = open( os.path.join(settings.HTMLEXPORT_ROOT, f'test/test/schedule/export/schedule.ics')).read() assert slot.submission.code in schedule_ics assert canceled_talk.submission.code not in schedule_ics schedule_xcal = open( os.path.join(settings.HTMLEXPORT_ROOT, f'test/test/schedule/export/schedule.xcal')).read() assert event.slug in schedule_xcal assert speaker.name in schedule_xcal schedule_xml = open( os.path.join(settings.HTMLEXPORT_ROOT, f'test/test/schedule/export/schedule.xml')).read() assert slot.submission.title in schedule_xml assert canceled_talk.submission.frab_slug not in schedule_xml assert str(canceled_talk.submission.uuid) not in schedule_xml talk_ics = open( os.path.join(settings.HTMLEXPORT_ROOT, f'test/test/talk/{slot.submission.code}.ics')).read() assert slot.submission.title in talk_ics
def __setattr__(self, attr, value): from django.test import override_settings override = override_settings(**{attr: value}) override.enable() self._to_restore.append(override)
def test_alert_limit_notification(rf, admin_user): with override_settings( CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() supplier = get_simple_supplier() shop = get_default_shop() product = create_product("simple-test-product", shop, supplier) sc = StockCount.objects.get(supplier=supplier, product=product) sc.alert_limit = 10 sc.save() # nothing in cache cache_key = AlertLimitReached.cache_key_fmt % (supplier.pk, product.pk) assert cache.get(cache_key) is None # put 11 units in stock supplier.adjust_stock(product.pk, +11) # still nothing in cache cache_key = AlertLimitReached.cache_key_fmt % (supplier.pk, product.pk) assert cache.get(cache_key) is None event = AlertLimitReached(product=product, supplier=supplier) assert event.variable_values["dispatched_last_24hs"] is False # stock should be 6, lower then the alert limit supplier.adjust_stock(product.pk, -5) last_run = cache.get(cache_key) assert last_run is not None event = AlertLimitReached(product=product, supplier=supplier) assert event.variable_values["dispatched_last_24hs"] is True # stock should be 1, lower then the alert limit supplier.adjust_stock(product.pk, -5) # test whether that runs inside a minute event = AlertLimitReached(product=product, supplier=supplier) event.run(shop) # not updated, not ran assert cache.get(cache_key) == last_run last_run -= 1000 cache.set(cache_key, last_run) event = AlertLimitReached(product=product, supplier=supplier) event.run(shop) # last run should be updated assert cache.get(cache_key) != last_run event = AlertLimitReached(product=product, supplier=supplier, supplier_email="*****@*****.**", shop_email="*****@*****.**") assert event.variable_values["dispatched_last_24hs"] is True # fake we have a cache with more than 24hrs cache.set(cache_key, time() - (24 * 60 * 60 * 2)) event = AlertLimitReached(product=product, supplier=supplier) assert event.variable_values["dispatched_last_24hs"] is False
def test_order_flow_with_multiple_suppliers(): cache.clear() shop = factories.get_default_shop() factories.create_default_order_statuses() factories.get_default_payment_method() factories.get_default_shipping_method() n_orders_pre = Order.objects.count() product = factories.create_product("sku", shop=shop, default_price=30) shop_product = product.get_shop_instance(shop) # Activate show supplier info for front assert ThemeSettings.objects.count() == 1 theme_settings = ThemeSettings.objects.first() theme_settings.update_settings({"show_supplier_info": True}) supplier_data = [ ("Johnny Inc", 30), ("Mike Inc", 10), ("Simon Inc", 20), ] for name, product_price in supplier_data: supplier = Supplier.objects.create(name=name) shop_product.suppliers.add(supplier) SupplierPrice.objects.create(supplier=supplier, shop=shop, product=product, amount_value=product_price) strategy = "E-Commerce.testing.supplier_pricing.supplier_strategy:CheapestSupplierPriceSupplierStrategy" with override_settings(E-Commerce_PRICING_MODULE="supplier_pricing", E-Commerce_SHOP_PRODUCT_SUPPLIERS_STRATEGY=strategy): # Ok so cheapest price should be default supplier expected_supplier = shop_product.get_supplier() assert expected_supplier.name == "Mike Inc" with override_current_theme_class(ClassicGrayTheme, shop): # Ensure settings is refreshed from DB c = SmartClient() # Case 1: use default supplier _add_to_basket(c, product.pk, 2) order = _complete_checkout(c, n_orders_pre + 1) assert order product_lines = order.lines.products() assert len(product_lines) == 1 assert product_lines[0].supplier.pk == expected_supplier.pk assert product_lines[0].base_unit_price_value == decimal.Decimal("10") # Case 2: force supplier to Johnny Inc johnny_supplier = Supplier.objects.filter(name="Johnny Inc").first() _add_to_basket(c, product.pk, 3, johnny_supplier) order = _complete_checkout(c, n_orders_pre + 2) assert order product_lines = order.lines.products() assert len(product_lines) == 1 assert product_lines[0].supplier.pk == johnny_supplier.pk assert product_lines[0].base_unit_price_value == decimal.Decimal("30") # Case 3: order 2 pcs from Mike and 3 pcs from Simon Inc mike_supplier = Supplier.objects.filter(name="Mike Inc").first() _add_to_basket(c, product.pk, 2, mike_supplier) simon_supplier = Supplier.objects.filter(name="Simon Inc").first() _add_to_basket(c, product.pk, 3, simon_supplier) order = _complete_checkout(c, n_orders_pre + 3) assert order assert order.taxful_total_price_value == decimal.Decimal("80") # Math: 2x10e + 3x20e product_lines = order.lines.products() assert len(product_lines) == 2 mikes_line = [line for line in product_lines if line.supplier.pk == mike_supplier.pk][0] assert mikes_line assert mikes_line.quantity == 2 assert mikes_line.base_unit_price_value == decimal.Decimal("10") simon_line = [line for line in product_lines if line.supplier.pk == simon_supplier.pk][0] assert simon_line assert simon_line.quantity == 3 assert simon_line.base_unit_price_value == decimal.Decimal("20")
def test_parler_language_code(setting_key, value, should_raise): kwargs = {setting_key: value} with override_settings(**kwargs): if should_raise: with pytest.raises(MissingSettingException): apps.get_app_config("shuup").ready()
def override_plugin_settings(**kwargs): plugin_settings = copy.deepcopy(settings.WALDUR_VMWARE) plugin_settings.update(kwargs) return override_settings(WALDUR_VMWARE=plugin_settings)
def test_do_service_m12(self): res = self.client.get(self.gb_m12.get_absolute_url()) self.assertContains( res, '<option selected value="2017-01-01">Sunday 1 January 2017</option>' ) groupings = res.context_data['timetable'].groupings outbound_stops = [str(row.part.stop) for row in groupings[0].rows] inbound_stops = [str(row.part.stop) for row in groupings[1].rows] self.assertEqual(outbound_stops, [ 'Belgravia Victoria Coach Station', '049004705400', 'Rugby ASDA', 'Fosse Park ASDA', 'Loughborough Holywell Way', 'Nottingham Broad Marsh Bus Station', 'Meadowhall Interchange', 'Leeds City Centre York Street', 'Bradford City Centre Hall Ings', 'Huddersfield Town Centre Market Street', 'Leeds City Centre Bus Stn', 'Shudehill Interchange', 'Middlesbrough Bus Station Express Lounge', 'Sunderland Interchange', 'Newcastle upon Tyne John Dobson Street', ]) self.assertEqual(inbound_stops, [ 'Huddersfield Town Centre Market Street', 'Bradford City Centre Interchange', 'Newcastle upon Tyne John Dobson Street', 'Sunderland Interchange', 'Middlesbrough Bus Station Express Lounge', 'Leeds City Centre Bus Stn', 'Shudehill Interchange', 'Leeds City Centre York Street', 'Meadowhall Interchange', 'Nottingham Broad Marsh Bus Station', 'Loughborough Holywell Way', 'Fosse Park ASDA', 'Rugby ASDA', '049004705400', 'Victoria Coach Station Arrivals' ]) with override_settings(TNDS_DIR='this is not a directory'): # should not be cached (because dummy cache) with override_settings( CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache' } }): res = self.client.get(self.gb_m12.get_absolute_url()) self.assertIsNone(res.context_data['timetable']) # should be cached res = self.client.get(self.gb_m12.get_absolute_url()) self.assertEqual('2017-01-01', str(res.context_data['timetable'].date)) # should be cached (even though different date) res = self.client.get(self.gb_m12.get_absolute_url() + '?date=2017-01-02') self.assertEqual('2017-01-02', str(res.context_data['timetable'].date))
self.assertEqual(response.template_name, ('tests/test_views_list/listviewtest/queue.html', 'viewflow/flow/queue.html')) class ListViewTestFlow(Flow): start1 = flow.StartFunction().Next(this.test_task) start2 = flow.Start(lambda request: None).Permission( 'auth.start_flow_perm').Next(this.test_task) start3 = flow.Start(lambda request: None).Next(this.test_task) test_task = flow.View(lambda request: None).Next(this.end) end = flow.End() urlpatterns = [ url( r'^test/', include(viewset.FlowViewSet(ListViewTestFlow).urls, namespace='listviewtest')) ] try: from django.test import override_settings Test = override_settings(ROOT_URLCONF=__name__)(Test) except ImportError: """ django 1.6 """ Test.urls = __name__
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_anon_disabling(): with override_settings(SHUUP_ALLOW_ANONYMOUS_ORDERS=False): with pytest.raises(ValidationError): order = create_empty_order() order.save()
def test_discount_admin_list_view(rf, admin_user): with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True): for x in range(3): _test_discount_list_view(rf, x) # Superuser gets same data as shop staff shop = Shop.objects.exclude( identifier=factories.DEFAULT_IDENTIFIER).order_by("?").first() request = apply_request_middleware(rf.get( "/", {"jq": json.dumps({ "perPage": 100, "page": 1 })}), user=admin_user, shop=shop) set_shop(request, shop) view_instance = DiscountListView() view_instance.request = request data = json.loads(view_instance.get(request).content.decode("UTF-8")) assert len(data["items"]) == 4 # In active 3 discounts to see that those are filtered out payload = { "action": "archive_discounts", "values": [ discount.pk for discount in Discount.objects.filter( shops=shop).order_by("?")[:3] ] } archive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop) set_shop(archive_request, shop) archive_request._body = json.dumps(payload).encode("UTF-8") view = DiscountListView.as_view() response = view(request=archive_request) if hasattr(response, "render"): response.render() assert response.status_code == 200 assert Discount.objects.available(shop).count() == 1 data = json.loads(view_instance.get(request).content.decode("UTF-8")) assert len(data["items"]) == 1 # Archived list should now show 3 results archived_view_instance = ArchivedDiscountListView() archived_view_instance.request = request data = json.loads( archived_view_instance.get(request).content.decode("UTF-8")) assert len(data["items"]) == 3 # Make sure rendering this archived discounts list works view_func = ArchivedDiscountListView.as_view() request = apply_request_middleware(rf.get("/"), user=admin_user, shop=shop) set_shop(request, shop) response = view_func(request) if hasattr(response, "render"): response.render() assert response.status_code == 200 # Unarchive all discounts payload = {"action": "unarchive_discounts", "values": "all"} unarchive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop) set_shop(unarchive_request, shop) unarchive_request._body = json.dumps(payload).encode("UTF-8") view = ArchivedDiscountListView.as_view() response = view(request=unarchive_request) if hasattr(response, "render"): response.render() assert response.status_code == 200 assert Discount.objects.available(shop).count() == 4 # Re-archive all discounts payload = {"action": "archive_discounts", "values": "all"} archive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop) set_shop(archive_request, shop) archive_request._body = json.dumps(payload).encode("UTF-8") view = DiscountListView.as_view() response = view(request=archive_request) if hasattr(response, "render"): response.render() assert response.status_code == 200 assert Discount.objects.available(shop).count() == 0 # Unarchive just one discount payload = { "action": "unarchive_discounts", "values": [ discount.pk for discount in Discount.objects.filter( shops=shop).order_by("?")[:1] ] } unarchive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop) set_shop(unarchive_request, shop) unarchive_request._body = json.dumps(payload).encode("UTF-8") view = ArchivedDiscountListView.as_view() response = view(request=unarchive_request) if hasattr(response, "render"): response.render() assert response.status_code == 200 assert Discount.objects.available(shop).count() == 1 # Delete one archived discount payload = { "action": "delete_discounts", "values": [ discount.pk for discount in Discount.objects.archived( shop).order_by("?")[:1] ] } delete_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop) set_shop(delete_request, shop) delete_request._body = json.dumps(payload).encode("UTF-8") view = ArchivedDiscountListView.as_view() response = view(request=delete_request) if hasattr(response, "render"): response.render() assert response.status_code == 200 assert Discount.objects.filter(shops=shop).count() == 3 # Delete all for this shop only payload = {"action": "delete_discounts", "values": "all"} delete_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop) set_shop(delete_request, shop) delete_request._body = json.dumps(payload).encode("UTF-8") view = ArchivedDiscountListView.as_view() response = view(request=delete_request) if hasattr(response, "render"): response.render() assert response.status_code == 200 assert Discount.objects.filter(shops=shop).count( ) == 1 # Since only archived can be deleted with mass action assert Discount.objects.available(shop).count() == 1 assert Discount.objects.archived(shop).count() == 0 assert Discount.objects.count() == 9
def test_override(self): self.assertFalse(settings.is_overridden('ALLOWED_HOSTS')) with override_settings(ALLOWED_HOSTS=[]): self.assertTrue(settings.is_overridden('ALLOWED_HOSTS'))
def setUpClass(cls): # Override settings cls.settings_override = override_settings(**TEST_SETTINGS) cls.settings_override.enable() super(LiveServerBase, cls).setUpClass()
def test_happy_hour_prices_expiration(rf): with override_settings( CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_happy_hour_prices_bump', } }): happy_hour = init_test() # it is now: 2018-01-01 09:00 AM before_happy_hour = datetime.datetime(2018, 1, 1, 9, 0, tzinfo=pytz.UTC) # 09:00 AM inside_happy_hour = datetime.datetime(2018, 1, 1, 10, 30, tzinfo=pytz.UTC) # 10:30 AM after_happy_hours = datetime.datetime(2018, 1, 1, 11, 20, tzinfo=pytz.UTC) # 11:30 AM # Create condition from 10am to 11am hour_start = datetime.datetime(2018, 1, 1, 10, 0, tzinfo=pytz.UTC).time() # 10:00 AM hour_end = datetime.datetime(2018, 1, 1, 11, 0, tzinfo=pytz.UTC).time() # 11:00 AM set_valid_times_condition(happy_hour, hour_start, hour_end, str(before_happy_hour.weekday())) shop = happy_hour.shops.first() discount = happy_hour.discounts.first() product = discount.product shop_product = product.get_shop_instance(shop) assert shop_product.default_price_value == 10 assert discount.discounted_price_value == 6 def get_request(): return apply_request_middleware(rf.get("/")) price_template = engines["jinja2"].from_string("{{ product|price }}") is_discounted_template = engines["jinja2"].from_string( "{{ product|is_discounted }}") discount_percent_template = engines["jinja2"].from_string( "{{ product|discount_percent }}") # we start with time being before happy hour with patch("django.utils.timezone.now", new=lambda: before_happy_hour): # mock also time.time so the cache timeout will be calculated correctly with patch("time.time", new=lambda: to_timestamp(before_happy_hour)): # check that product price is still the orignal (€10.00) # run twice to make sure caches are being used for cache_test in range(2): context = dict(product=product, request=get_request()) assert price_template.render(context) == format_money( shop_product.default_price) assert is_discounted_template.render(context) == "False" assert discount_percent_template.render(context) == "0%" if cache_test == 1: assert get_cached_price_info( get_request(), product, 1, supplier=shop_product.get_supplier()) # now we are inside happy hour range with patch("django.utils.timezone.now", new=lambda: inside_happy_hour): # mock also time.time so the cache timeout will be calculated correctly with patch("time.time", new=lambda: to_timestamp(inside_happy_hour)): # check that product price is the discounted one (€6.00) # run twice to make sure caches are being used for cache_test in range(2): context = dict(product=product, request=get_request()) assert price_template.render(context) == format_money( shop.create_price(discount.discounted_price_value)) assert is_discounted_template.render(context) == "True" assert discount_percent_template.render(context) == "40%" if cache_test == 1: assert get_cached_price_info( get_request(), product, 1, supplier=shop_product.get_supplier()) # we change the discounted price from $6 to $7 # cached should be bumped discount.discounted_price_value = 7 discount.save() for cache_test in range(2): context = dict(product=product, request=get_request()) assert price_template.render(context) == format_money( shop.create_price(discount.discounted_price_value)) assert is_discounted_template.render(context) == "True" assert discount_percent_template.render(context) == "30%" if cache_test == 1: assert get_cached_price_info( get_request(), product, 1, supplier=shop_product.get_supplier()) # now we are inside happy hour range with patch("django.utils.timezone.now", new=lambda: after_happy_hours): # mock also time.time so the cache timeout will be calculated correctly with patch("time.time", new=lambda: to_timestamp(after_happy_hours)): # check that product price is the orignal (€10.00) # run twice to make sure caches are being used for cache_test in range(2): context = dict(product=product, request=get_request()) assert price_template.render(context) == format_money( shop_product.default_price) assert is_discounted_template.render(context) == "False" assert discount_percent_template.render(context) == "0%" if cache_test == 1: assert get_cached_price_info( get_request(), product, 1, supplier=shop_product.get_supplier())
def test_media_root_pathlib(self): with tempfile.TemporaryDirectory() as tmp_dir: with override_settings(MEDIA_ROOT=Path(tmp_dir)): with TemporaryUploadedFile('foo.txt', 'text/plain', 1, 'utf-8') as tmp_file: Document.objects.create(myfile=tmp_file) self.assertTrue(os.path.exists(os.path.join(tmp_dir, 'unused', 'foo.txt')))
def test_happy_hour(rf): happy_hour = init_test() discount = happy_hour.discounts.first() shop = discount.shops.first() assert Discount.objects.available().count() == 1 assert Discount.objects.available(shop).count() == 1 w_today = timezone.now().date().weekday() w_tomorrow = (timezone.now() + datetime.timedelta(days=1)).date().weekday() w_future = (timezone.now() + datetime.timedelta(days=2)).date().weekday() matching_days = ",".join(map(str, [w_today])) non_matching_days = ",".join(map(str, [w_tomorrow, w_future])) # Matching time range hour_start = (timezone.now() - datetime.timedelta(hours=2)).time() # 8:00 AM hour_end = (timezone.now() + datetime.timedelta(hours=2)).time() # 12:00 PM set_valid_times_condition(happy_hour, hour_start, hour_end, matching_days) assert Discount.objects.available().count() == 1 assert Discount.objects.available(shop).count() == 1 set_valid_times_condition(happy_hour, hour_start, hour_end, non_matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0 # Hour end shouldn't cause a match. Should be obvious that if the # merchant set start time 8:00 AM and end time 10:00 AM th campaign is no more # at 10:10 AM new_hour_start = (timezone.now() - datetime.timedelta(hours=2)).time() # 8:00 AM new_hour_end = timezone.now().time() # 10:00 PM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, non_matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0 # time in future shouldn't match new_hour_start = (timezone.now() + datetime.timedelta(hours=2)).time() # 12:00 PM new_hour_end = (timezone.now() + datetime.timedelta(hours=4)).time() # 14:00 PM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0 # time in past shouldn't match new_hour_start = (timezone.now() - datetime.timedelta(hours=3)).time() # 7:00 AM new_hour_end = (timezone.now() - datetime.timedelta(hours=2)).time() # 8:00 AM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0 # Special times (should match) new_hour_start = timezone.now().time() # 10:00 AM new_hour_end = (timezone.now() + datetime.timedelta(hours=14)).time() # 0:00 AM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, matching_days) assert Discount.objects.available().count() == 1 assert Discount.objects.available(shop).count() == 1 set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, non_matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0 # Special times (should not match) new_hour_start = (timezone.now() + datetime.timedelta(hours=2)).time() # 12:00 AM new_hour_end = (timezone.now() + datetime.timedelta(hours=14)).time() # 0:00 AM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0 # Lastly few timezone tests (LA it is monday and time is 2:00 AM.) with override_settings(TIME_ZONE="America/Los_Angeles"): # So the 10:00 AM shouldn't match at all new_hour_start = (timezone.now() - datetime.timedelta(hours=1)).time() # 9:00 AM new_hour_end = (timezone.now() + datetime.timedelta(hours=1)).time() # 11:00 AM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0 # Instead around 2:00 AM we will find a match new_hour_start = (timezone.now() - datetime.timedelta(hours=9)).time() # 1:00 AM new_hour_end = (timezone.now() - datetime.timedelta(hours=7)).time() # 3:00 AM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, matching_days) assert Discount.objects.available().count() == 1 assert Discount.objects.available(shop).count() == 1 # Make sure that the hour end doesn't cause match new_hour_start = (timezone.now() - datetime.timedelta(hours=9)).time() # 1:00 AM new_hour_end = (timezone.now() - datetime.timedelta(hours=8)).time() # 2:00 AM set_valid_times_condition(happy_hour, new_hour_start, new_hour_end, matching_days) assert Discount.objects.available().count() == 0 assert Discount.objects.available(shop).count() == 0
def _populate_applied_attribute(aa): if aa.attribute.type == AttributeType.BOOLEAN: aa.value = True aa.save() assert aa.value is True, "Truth works" assert aa.untranslated_string_value == "1", "Integer attributes save string representations" aa.value = not 42 # (but it could be something else) aa.save() assert aa.value is False, "Lies work" assert aa.untranslated_string_value == "0", "Integer attributes save string representations" aa.value = None aa.save() assert aa.value is None, "None works" assert aa.untranslated_string_value == "", "Boolean saves None" return if aa.attribute.type == AttributeType.INTEGER: aa.value = 320.51 aa.save() assert aa.value == 320, "Integer attributes get rounded down" assert aa.untranslated_string_value == "320", "Integer attributes save string representations" return if aa.attribute.type == AttributeType.DECIMAL: aa.value = Decimal("0.636") # Surface pressure of Mars aa.save() assert aa.value * 1000 == 636, "Decimals work like they should" assert aa.untranslated_string_value == "0.636", "Decimal attributes save string representations" return if aa.attribute.type == AttributeType.TIMEDELTA: aa.value = 86400 aa.save() assert aa.value.days == 1, "86,400 seconds is one day" assert aa.untranslated_string_value == "86400", "Timedeltas are seconds as strings" aa.value = datetime.timedelta(days=4) aa.save() assert aa.value.days == 4, "4 days remain as 4 days" assert aa.untranslated_string_value == "345600", "Timedeltas are still seconds as strings" return if aa.attribute.type == AttributeType.UNTRANSLATED_STRING: aa.value = "Dog Hello" aa.save() assert aa.value == "Dog Hello", "Untranslated strings work" assert aa.untranslated_string_value == "Dog Hello", "Untranslated strings work" return if aa.attribute.type == AttributeType.TRANSLATED_STRING: assert aa.attribute.is_translated with override_settings(LANGUAGES=[(x, x) for x in ("en", "fi", "ga", "ja")]): versions = { "en": "science fiction", "fi": "tieteiskirjallisuus", "ga": "ficsean eolaíochta", "ja": "空想科学小説", } for language_code, text in versions.items(): aa.set_current_language(language_code) aa.value = text aa.save() assert aa.value == text, "Translated strings work" for language_code, text in versions.items(): assert aa.safe_translation_getter( "translated_string_value", language_code=language_code) == text, ( "%s translation is safe" % language_code) aa.set_current_language("xx") assert aa.value == "", "untranslated version yields an empty string" return if aa.attribute.type == AttributeType.DATE: aa.value = "2014-01-01" assert aa.value == datetime.date(2014, 1, 1), "Date parsing works" assert aa.untranslated_string_value == "2014-01-01", "Dates are saved as strings" return if aa.attribute.type == AttributeType.DATETIME: with pytest.raises(TypeError): aa.value = "yesterday" dt = datetime.datetime(1997, 8, 12, 14) aa.value = dt assert aa.value.toordinal() == 729248, "Date assignment works" assert aa.value.time().hour == 14, "The clock still works" assert aa.untranslated_string_value == dt.isoformat( ), "Datetimes are saved as strings too" return raise NotImplementedError("Error! Not implemented: populating %s" % aa.attribute.type) # pragma: no cover
def test_get_default_timezone_utc(self): with override_settings(USE_TZ=True, TIME_ZONE='UTC'): self.assertIs(timezone.get_default_timezone(), timezone.utc)
def test_one_locale(self): with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]): call_command('compilemessages', locale=['hr'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE_HR))
def test_now(self): with override_settings(USE_TZ=True): self.assertTrue(timezone.is_aware(timezone.now())) with override_settings(USE_TZ=False): self.assertTrue(timezone.is_naive(timezone.now()))
def setUp(self): self.settings_override = override_settings( EMAIL_BACKEND=self.email_backend) self.settings_override.enable()
def test_discount_admin_delete_view(rf): with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True): for x in range(3): _test_exception_delete_view(rf, x)
def test_load_import_error(self): with override_settings(MIGRATION_MODULES={"migrations": "import_error_package"}): with self.assertRaises(ImportError): MigrationLoader(connection)
def test_order_refunds_with_multiple_suppliers(): shop = get_default_shop() supplier1 = Supplier.objects.create(identifier="1", name="supplier1") supplier1.shops.add(shop) supplier2 = Supplier.objects.create(identifier="2") supplier2.shops.add(shop) supplier3 = Supplier.objects.create(identifier="3", name="s") supplier3.shops.add(shop) product1 = create_product("sku1", shop=shop, default_price=10) shop_product1 = product1.get_shop_instance(shop=shop) shop_product1.suppliers = [supplier1, supplier2, supplier3] product2 = create_product("sku2", shop=shop, default_price=10) shop_product2 = product1.get_shop_instance(shop=shop) shop_product2.suppliers = [supplier1, supplier2] product3 = create_product("sku3", shop=shop, default_price=10, shipping_mode=ShippingMode.NOT_SHIPPED) shop_product3 = product1.get_shop_instance(shop=shop) shop_product3.suppliers = [supplier3] product_quantities = { supplier1: { product1: 5, product2: 6 }, supplier2: { product1: 3, product2: 13 }, supplier3: { product1: 1, product3: 50 } } def get_quantity(supplier, product): return product_quantities[supplier.pk][product.pk] order = create_empty_order(shop=shop) order.full_clean() order.save() for supplier, product_data in six.iteritems(product_quantities): for product, quantity in six.iteritems(product_data): add_product_to_order(order, supplier, product, quantity, 5) # Lines without quantity shouldn't affect refunds other_line = OrderLine(order=order, type=OrderLineType.OTHER, text="This random line for textual information", quantity=0) other_line.save() order.lines.add(other_line) order.cache_prices() order.create_payment(order.taxful_total_price) assert order.is_paid() # All supplier should be able to refund the order assert order.can_create_refund() assert order.can_create_refund(supplier1) assert order.can_create_refund(supplier2) assert order.can_create_refund(supplier3) assert order.get_total_unrefunded_amount(supplier1).value == Decimal( "55") # 11 * 5 assert order.get_total_unrefunded_quantity(supplier1) == Decimal( "11") # 5 x product1 and 6 x product2 with pytest.raises(RefundExceedsAmountException): order.create_refund([{ "line": "amount", "quantity": 1, "amount": order.shop.create_price(60) }], supplier=supplier1) # Supplier 1 refunds the order order.create_refund(_get_refund_data(order, supplier1)) assert order.get_total_refunded_amount(supplier1).value == Decimal( "55") # 11 * 5 assert order.get_total_unrefunded_amount(supplier1).value == Decimal("0") assert not order.can_create_refund(supplier1) assert order.can_create_refund() assert order.can_create_refund(supplier2) assert order.can_create_refund(supplier3) assert order.get_total_unrefunded_amount(supplier2).value == Decimal( "80") # 16 * 5 assert order.get_total_unrefunded_quantity(supplier2) == Decimal( "16") # 3 x product1 and 13 x product2 with pytest.raises(RefundExceedsAmountException): order.create_refund([{ "line": "amount", "quantity": 1, "amount": order.shop.create_price(81) }], supplier=supplier2) # Supplier 2 refunds the order order.create_refund(_get_refund_data(order, supplier2)) assert order.get_total_refunded_amount(supplier2).value == Decimal( "80") # 11 * 5 assert order.get_total_unrefunded_amount(supplier2).value == Decimal("0") assert not order.can_create_refund(supplier1) assert not order.can_create_refund(supplier2) assert order.can_create_refund() assert order.can_create_refund(supplier3) assert order.get_total_unrefunded_amount(supplier3).value == Decimal( "255") # 51 * 5 assert order.get_total_unrefunded_quantity(supplier3) == Decimal( "51") # 3 x product1 and 13 x product2 with override_settings(SHUUP_ALLOW_ARBITRARY_REFUNDS=False): with pytest.raises(RefundArbitraryRefundsNotAllowedException): order.create_refund([{ "line": "amount", "quantity": 1, "amount": order.shop.create_price(200) }], supplier=supplier3) order.create_refund([{ "line": "amount", "quantity": 1, "amount": order.shop.create_price(200) }], supplier=supplier3) assert OrderLine.objects.filter(order=order, supplier=supplier3, type=OrderLineType.REFUND).exists() # Supplier 3 refunds the order order.create_refund(_get_refund_data(order, supplier3)) assert order.get_total_refunded_amount(supplier3).value == Decimal( "255") # 11 * 5 assert order.get_total_unrefunded_amount(supplier3).value == Decimal("0") assert not order.can_create_refund(supplier1) assert not order.can_create_refund(supplier2) assert not order.can_create_refund(supplier3) assert not order.can_create_refund()
from ..mails import DefaultLayout API_BASE_PATH = '/api/' User = get_user_model() integration_test = pytest.mark.skipif(os.environ.get('NO_INTEGRATION', None) == '1', reason='skip integration test') skip_ci_test = pytest.mark.skipif(os.environ.get('SKIP_CI_TEST', None) == '1', reason='skip ci test') ignore_external = override_settings( FIREBASE_SKIP=True, STRIPE_SKIP=True, EMAIL_SKIP=True, ROBUST_ALWAYS_EAGER=True, ) class JsonClient(Client): def _make_path(self, path): if not path.startswith('/api/'): return '{}{}'.format(API_BASE_PATH, path) return path def _json_request(self, method, path, data, secure=False, **extra): method = method.lower() assert method in { 'delete', 'get', 'head', 'options', 'patch', 'post', 'put' }
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__)