def test_global_configurations(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_global_configurations', } }): cache.init_cache() shop = get_default_shop() configuration.set(None, "key1", {"data": "test1"}) configuration.set(shop, "key2", {"data": "test2"}) # key1 from shop should come from global configuration assert configuration.get(shop, "key1").get("data") == "test1" # key2 shouldn't be in global configurations assert configuration.get(None, "key2") is None # Update global configuration configuration.set(None, "key1", {"data": "test_bump"}) assert configuration.get(shop, "key1").get("data") == "test_bump" # Override shop data for global key1 configuration.set(shop, "key1", "test_data") assert configuration.get(shop, "key1") == "test_data" # Update shop configuration for global key1 configuration.set(shop, "key1", "test_data1") assert configuration.get(shop, "key1") == "test_data1"
def test_simple_set_and_get_cascading(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_simple_set_and_get_cascading', } }): cache.init_cache() shop = get_default_shop() configuration.set(None, "answer", 42) assert configuration.get(None, "answer") == 42 assert configuration.get(shop, "answer", 42) assert configuration.get(None, "non-existing") is None assert configuration.get(shop, "non-existing") is None configuration.set(shop, "non-existing", "hello") assert configuration.get(None, "non-existing") is None assert configuration.get(shop, "non-existing") == "hello" assert configuration.get(None, "foo") is None assert configuration.get(shop, "foo") is None configuration.set(None, "foo", "bar") configuration.set(shop, "foo", "baz") assert configuration.get(None, "foo") == "bar" assert configuration.get(shop, "foo") == "baz"
def test_get_url(test_type): init_cache() assert_request( "GET", ROUTE + GET_URL_INPUT[test_type], AssertRequest({}, {}), GET_URL_OUTPUT[test_type], )
def main(): src_dir = path.realpath(BOOK_SRC_DIR) chapters = [ path.join(src_dir, p) for p in sorted(os.listdir(src_dir)) if p.endswith('.html') ] skipping = True skip_until = None digits = math.ceil(math.log10(len(chapters))) fmt = f'{digits}d' if not path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) cache.init_cache() for i, chapter_filename in enumerate(chapters): i += 1 if skip_until is None or chapter_filename.endswith(skip_until): skipping = False output_basename = path.basename(chapter_filename) output_filename = path.join(OUTPUT_DIR, output_basename) print( colored('[{}/{}]:'.format(format(i, fmt), len(chapters)), 'green', attrs=['bold']), output_basename) if skipping: continue with open(output_filename, 'w') as f: chapter_txt = read(chapter_filename) try: chapter_processed = process_chapter(chapter_txt) except TeXRenderError as e: cprint('Error while converting TeX to MathML', 'red', attrs=['bold']) print(e.proc) print(e.proc.output.strip()) cprint(e.proc.stderr.strip(), 'red') cprint('TeX source:', 'red', attrs=['bold']) print(e.src) if e.context: cprint('Page context:', 'red', attrs=['bold']) print(e.context) print( 'Check the chapter online:', colored(ONLINE_SRC_BASE + output_basename, 'cyan', attrs=['underline'])) sys.exit(1) f.write(str(process_chapter(read(chapter_filename)))) cprint('Done!', 'green', attrs=['bold'])
def test_xtheme_extra_view_exceptions(rf): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() with override_current_theme_class(H2G2Theme, get_default_shop()): request = rf.get("/") request.shop = get_default_shop() assert extra_view_dispatch(request, "vogons").status_code == 404 with pytest.raises(ImproperlyConfigured): assert extra_view_dispatch(request, "true")
def test_theme_with_default_template_dir(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() get_default_shop() with override_current_theme_class(E-CommerceTestingThemeWithCustomBase, get_default_shop()): c = SmartClient() soup = c.soup(reverse("E-Commerce:index")) assert "Simple base for themes to use" in soup.find("h1").text assert "Welcome to test E-Commerce!" in soup.find("h1").text
def test_theme_activation(): cache.init_cache() shop = get_default_shop() with override_provides("xtheme", [ "E-Commerce_tests.xtheme.utils:FauxTheme", "E-Commerce_tests.xtheme.utils:FauxTheme2" ]): set_current_theme(FauxTheme.identifier, shop) assert isinstance(get_current_theme(shop), FauxTheme) set_current_theme(FauxTheme2.identifier, shop) assert isinstance(get_current_theme(shop), FauxTheme2) with pytest.raises(ValueError): set_current_theme(printable_gibberish(), shop)
def test_configuration_gets_saved(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_gets_saved', } }): cache.init_cache() configuration.set(None, "x", 1) assert configuration.get(None, "x") == 1 configuration.set(None, "x", 2) assert configuration.get(None, "x") == 2 configuration.set(None, "x", 3) assert configuration.get(None, "x") == 3 conf_item = ConfigurationItem.objects.get(shop=None, key="x") assert conf_item.value == 3
def test_configuration_set_and_get(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_set_and_get', } }): cache.init_cache() shop = get_default_shop() test_conf_data = {"data": "test"} configuration.set(shop, "key", test_conf_data) # Get the configuration via configuration API assert configuration.get(shop, "key") == test_conf_data # Check that configuration is saved to database assert ConfigurationItem.objects.get(shop=shop, key="key").value == test_conf_data
def test_theme_settings_api(): cache.init_cache() shop = get_default_shop() with override_provides("xtheme", [ "E-Commerce_tests.xtheme.utils:FauxTheme", "E-Commerce_tests.xtheme.utils:FauxTheme2" ]): ThemeSettings.objects.all().delete() theme = get_theme_by_identifier(FauxTheme2.identifier, shop) theme.set_setting("foo", "bar") theme.set_settings(quux=[4, 8, 15, 16, 23, 42]) theme = get_theme_by_identifier(FauxTheme2.identifier, shop) assert theme.get_setting("foo") == "bar" assert theme.get_settings() == { "foo": "bar", "quux": [4, 8, 15, 16, 23, 42] }
def test_cache_api(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() key = "test_prefix:123" value = "456" cache.set(key, value) assert cache.get(key) == value cache.bump_version(key) assert cache.get(key, default="derp") == "derp" # version was bumped, so no way this is there cache.set(key, value) assert cache.get(key) == value
def test_configuration_update(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_update', } }): cache.init_cache() shop = get_default_shop() configuration.set(shop, "key1", {"data": "test1"}) configuration.set(shop, "key2", {"data": "test2"}) configuration.set(shop, "key3", {"data": "test3"}) assert configuration.get(shop, "key1").get("data") == "test1" assert configuration.get(shop, "key3").get("data") == "test3" # Update configuration configuration.set(shop, "key3", {"data": "test_bump"}) assert configuration.get(shop, "key3").get("data") == "test_bump"
def test_configuration_cache(): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() shop = get_default_shop() configuration.set(None, "key1", "test1") configuration.set(shop, "key2", "test2") # Shop configurations cache should be bumped assert cache.get(configuration._get_cache_key(shop)) is None configuration.get(shop, "key1") # Now shop configurations and key2 should found from cache assert cache.get(configuration._get_cache_key(shop)).get("key2") == "test2"
def init_app(name, config): import socket if "gevent" in socket.socket.__module__: import pymysql pymysql.install_as_MySQLdb() static_url_path = None static_folder = None if 'STATIC_FOLDER' in dir(config): static_url_path = config.STATIC_URL static_folder = config.STATIC_FOLDER if static_url_path.endswith('/'): static_url_path = static_url_path[:-1] app = Flask(name, static_url_path=static_url_path, static_folder=static_folder) app.config.from_object(config) app.register_error_handler(400, error_handle_400) app.register_error_handler(404, error_handle_404) app.register_error_handler(500, error_handle_500) if 'LOGGER_CONFIG' in app.config and 'sentry_dsn' in app.config[ 'LOGGER_CONFIG']: from raven.contrib.flask import Sentry Sentry(app, dsn=app.config['LOGGER_CONFIG']['sentry_dsn']) if 'I18N' in app.config: __import__(app.config['I18N'], fromlist=['*']) if 'CACHES' in app.config: cache.init_cache(app.config['CACHES']) if 'DATABASES' in app.config: db = dbmodel.init_db(app.config.get('DATABASE_BACKEND', ''), app.config['DATABASES'], app.config.get('DATABASE_OPTIONS'), app.config.get('DEBUG', False)) if db.BACKEND == 'django': app.before_request(db.refresh_db_connections) if 'SESSION_COOKIE_NAME' in app.config: app.session_interface = _ServerSessionInterface(app) if 'GEOIP_PATH' in app.config: init_geo(app.config['GEOIP_PATH']) if app.config.get('HTTP_PROXY_FIX', False): from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) global _app # pylint: disable=global-statement _app = app return app
def test_xtheme_extra_views(rf): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() with override_current_theme_class(H2G2Theme, get_default_shop()): request = rf.get("/", {"name": "Arthur Dent"}) request.shop = get_default_shop() # Simulate /xtheme/greeting response = extra_view_dispatch(request, "greeting") assert force_text(response.content) == "So long, and thanks for all the fish, Arthur Dent" # Try that again (to exercise the _VIEW_CACHE code path): response = extra_view_dispatch(request, "greeting") assert force_text(response.content) == "So long, and thanks for all the fish, Arthur Dent" # Now test that CBVs work assert not extra_view_dispatch(request, "faux").content
def test_classic_gray_theme_settings(admin_user): with override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_configuration_cache', } }): cache.init_cache() shop = get_default_shop() with override_provides("xtheme", ["E-Commerce.themes.classic_gray.theme:ClassicGrayTheme"]): set_current_theme(ClassicGrayTheme.identifier, shop) theme = _get_current_theme(shop) assert isinstance(theme, ClassicGrayTheme) ThemeSettings.objects.all().delete() client = Client() admin_user.set_password("admin") admin_user.save() client.login(username=admin_user.username, password="******") theme_config_url = reverse("E-Commerce_admin:xtheme.config_detail", kwargs=dict(theme_identifier=ClassicGrayTheme.identifier)) response = client.get(theme_config_url) assert response.status_code == 200 assert theme.get_setting("shop_logo_width") is None assert theme.get_setting("shop_logo_height") is None assert theme.get_setting("shop_logo_alignment") is None assert theme.get_setting("shop_logo_aspect_ratio") is None settings = { "stylesheet": "E-Commerce/classic_gray/blue/style.css" } response = client.post(theme_config_url, data=settings) assert response.status_code == 302 theme = _get_current_theme(shop) for key, value in settings.items(): assert theme.get_setting(key) == value
def test_xtheme_wizard_pane(rf, admin_user): with override_settings( E-Commerce_SETUP_WIZARD_PANE_SPEC = [ "E-Commerce.xtheme.admin_module.views.ThemeWizardPane" ], CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'test_simple_set_and_get_with_shop', } } ): cache.init_cache() shop = get_default_shop() with override_provides("xtheme", ["E-Commerce_tests.xtheme.utils:FauxTheme"]): from E-Commerce_tests.xtheme.utils import FauxTheme assert get_current_theme(shop) is None fields = _extract_fields(rf, admin_user) fields["theme-activate"] = FauxTheme.identifier request = apply_request_middleware(rf.post("/", data=fields), user=admin_user) response = WizardView.as_view()(request) assert isinstance(get_current_theme(shop), FauxTheme) assert_redirect_to_dashboard(rf, admin_user, shop)
def __init_cache(self, source): self.caches[source] = cache.init_cache(source) self.source_indices[source] = len(self.source_indices) self.source_names.append(source)
def test_get(test_type): init_cache() assert_request("GET", ROUTE, GET_INPUT[test_type], GET_OUTPUT[test_type])
def test_post(test_type): init_cache() assert_request("POST", ROUTE, POST_INPUT[test_type], POST_OUTPUT[test_type])
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
async def startup_event(): logger.info("Processing startup initialization") init_cache()
from flask import Flask, jsonify, request from cache import init_cache from slack_api.message import set_user_dm from slack_api.user import search_user, set_user_status app = Flask(__name__) init_cache(app) @app.route('/') def index(): return jsonify("True") @app.route('/api/v1/user/<email>', methods=['GET']) def user_api_v1(email): return jsonify(search_user(email)) @app.route('/api/v1/status/<email>', methods=['POST']) def status_api_v1(email): user: dict = search_user(email) user_id = user["id"] status_text = request.get_json()["text"] status_emoji = request.get_json()["emoji"] return set_user_status(user_id, status_text, status_emoji) @app.route('/api/v1/message/<email>', methods=['POST']) def message_api_v1(email):
from flask.ext.assets import Environment as Asset from cache import init_cache from database import init_db from utils.assets import init_app as init_asset from utils.jinja import init_app as init_jinja from utils.i18n import PopongBabel from utils.linkall import init_app as init_linkall from utils.login import init_app as init_login from utils.mobile import PopongMobile from utils.reverse_proxy import init_app as init_reverse_proxy from views import init_app as init_view from widgets import init_app as init_widgets Asset(app) init_cache(app) init_asset(app) init_db(app) init_jinja(app) PopongBabel(app) PopongMobile(app) init_linkall(app) init_login(app) init_reverse_proxy(app) init_view(app) init_widgets(app) setattr(app, '__loaded__', True) def parse_args():