def init_postgresql_fts(apps, schema_editor): conn = schema_editor.connection if hasattr(conn, "vendor") and conn.vendor == "postgresql": script_path = os.path.join( askbot.get_install_directory(), "search", "postgresql", "thread_and_post_models_10032013.plsql" ) setup_full_text_search(script_path) script_path = os.path.join( askbot.get_install_directory(), "search", "postgresql", "user_profile_search_12202015.plsql" ) setup_full_text_search(script_path)
def handle_noargs(self, **options): script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'thread_and_post_models_10032013.plsql' ) setup_full_text_search(script_path) script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'user_profile_search_12192015.plsql' ) setup_full_text_search(script_path)
def get_available_skins(selected=None): """Returns a dictionary of skin name --> directory where "templates" and "media" subdirectories can be found. selected is a name of preferred skin if it's None, then information about all skins will be returned otherwise, only data about selected and default skins will be returned selected skin is guaranteed to be the first item in the dictionary """ skins = OrderedDict() extra_skins_dir = getattr(django_settings, 'ASKBOT_EXTRA_SKINS_DIR', None) if extra_skins_dir: skins.update(get_skins_from_dir(extra_skins_dir)) if 'default' in skins: raise ValueError('"default" is not an acceptable name for a custom skin') if selected in skins: selected_dir = skins[selected] skins.clear() skins[selected] = selected_dir elif selected == 'default': skins = OrderedDict() elif selected: raise ValueError( 'skin ' + str(selected) + \ ' not found, please check ASKBOT_EXTRA_SKINS_DIR setting ' + \ 'or in the corresponding directory' ) #insert default as a last item skins['default'] = askbot.get_install_directory() return skins
def handle_noargs(self, **options): script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'thread_and_post_models_01162012.plsql' ) setup_full_text_search(script_path)
def tearDown(self): #delete the dummy skin test_skin_dir = os.path.join( askbot.get_install_directory(), 'skins', 'test_skin' ) shutil.rmtree(test_skin_dir)
def setUp(self): #create dummy skin skin_image_dir = os.path.join( askbot.get_install_directory(), 'skins', 'test_skin', 'media', 'images' ) mkdir_p(skin_image_dir) test_image_file = os.path.join( askbot.get_install_directory(), 'tests', 'images', 'logo.gif' ) shutil.copy(test_image_file, skin_image_dir)
def get_tinymce_sample_config(): """returns the sample configuration for TinyMCE as string""" askbot_root = askbot.get_install_directory() file_path = os.path.join(askbot_root, "setup_templates", "tinymce_sample_config.py") config_file = open(file_path, "r") sample_config = config_file.read() config_file.close() return sample_config
def test_uploaded_logo(self): logo_src = os.path.join(askbot.get_install_directory(), "tests", "images", "logo.gif") logo_file = open(logo_src, "r") new_logo = UploadedFile(file=logo_file) askbot_settings.update("SITE_LOGO_URL", new_logo) logo_url = askbot_settings.SITE_LOGO_URL self.assertTrue(logo_url.startswith(django_settings.MEDIA_URL)) response = self.client.get(logo_url) self.assertTrue(response.status_code == 200)
def tearDown(self): #delete the dummy skin test_skin_dir = os.path.join( askbot.get_install_directory(), 'skins', 'test_skin' ) shutil.rmtree(test_skin_dir) askbot_settings.update('ASKBOT_DEFAULT_SKIN', 'default')
def init_postgresql_fts(apps, schema_editor): conn = schema_editor.connection if hasattr(conn, 'vendor') and conn.vendor == 'postgresql': script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'thread_and_post_models_10032013.plsql' ) setup_full_text_search(script_path) script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'user_profile_search_12192015.plsql' ) setup_full_text_search(script_path)
def test_new_skins(): """tests that there are no directories in the `askbot/skins` because we've moved skin files a few levels up""" askbot_root = askbot.get_install_directory() for item in os.listdir(os.path.join(askbot_root, "skins")): item_path = os.path.join(askbot_root, "skins", item) if os.path.isdir(item_path): raise AskbotConfigError( ("Time to move skin files from %s.\n" "Now we have `askbot/templates` and `askbot/media`") % item_path )
def forwards(self, orm): "Write your forwards methods here." if 'postgresql_psycopg2' in askbot.get_database_engine_name(): script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'thread_and_post_models_01162012.plsql' ) setup_full_text_search(script_path)
def forwards(self, orm): "Write your forwards methods here." if 'postgresql_psycopg2' in askbot.get_database_engine_name(): script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'exercise_problem_comment_models.plsql' ) setup_full_text_search(script_path)
def test_new_skins(): """tests that there are no directories in the `askbot/skins` because we've moved skin files a few levels up""" askbot_root = askbot.get_install_directory() for item in os.listdir(os.path.join(askbot_root, 'skins')): if item == '__pycache__': continue item_path = os.path.join(askbot_root, 'skins', item) if os.path.isdir(item_path): raise AskbotConfigError( ('Time to move skin files from %s.\nNow we have `askbot/templates` and `askbot/media`') % item_path)
def forwards(self, orm): "Write your forwards methods here." db_engine_name = askbot.get_database_engine_name() if 'postgresql_psycopg2' in db_engine_name: script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'user_profile_search_02262013.plsql' ) postgresql.setup_full_text_search(script_path)
def test_new_skins(): """tests that there are no directories in the `askbot/skins` because we've moved skin files a few levels up""" askbot_root = askbot.get_install_directory() for item in os.listdir(os.path.join(askbot_root, 'skins')): if item == '__pycache__': continue item_path = os.path.join(askbot_root, 'skins', item) if os.path.isdir(item_path): raise AskbotConfigError( ('Time to move skin files from %s.\n' 'Now we have `askbot/templates` and `askbot/media`') % item_path )
def test_uploaded_logo(self): logo_src = os.path.join( askbot.get_install_directory(), 'tests', 'images', 'logo.gif' ) logo_file = open(logo_src, 'r') new_logo = UploadedFile(file = logo_file) askbot_settings.update('SITE_LOGO_URL', new_logo) logo_url = askbot_settings.SITE_LOGO_URL self.assertTrue(logo_url.startswith(django_settings.MEDIA_URL)) response = self.client.get(logo_url, follow=True) self.assertTrue(response.status_code == 200)
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." if db.backend_name == 'mysql': table_name = orm['askbot.Thread']._meta.db_table if mysql_table_supports_full_text_search(table_name): columns = ('title', 'tagnames') sql = get_create_full_text_index_sql(INDEX_NAME, table_name, columns) db.execute(sql) elif db.backend_name == 'postgres': script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'thread_and_post_models_27112012.plsql') postgresql.setup_full_text_search(script_path)
def init_postgresql_fts(apps, schema_editor): conn = schema_editor.connection # if conn does not have an attribute vendor, there is probalby something # wrong with Django and we should raise an exception, i.e. provoke the # AttributeError if not hasattr(conn, 'vendor') or conn.vendor != 'postgresql': return #there used to be also setup of thread and post model FTS, #but now we have a better migration 0009 script_path = os.path.join(askbot.get_install_directory(), 'search', 'postgresql', 'user_profile_search_12202015.plsql') setup_full_text_search(script_path)
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." if db.backend_name == 'mysql': table_name = orm['askbot.Thread']._meta.db_table if mysql_table_supports_full_text_search(table_name): columns = ('title', 'tagnames') sql = get_create_full_text_index_sql(INDEX_NAME, table_name, columns) db.execute(sql) elif db.backend_name == 'postgres': script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'thread_and_post_models_27112012.plsql' ) postgresql.setup_full_text_search(script_path)
def setUp(self): # create dummy skin self.temp_dir = tempfile.mkdtemp() self.skins_dir_backup = getattr(django_settings, 'ASKBOT_EXTRA_SKINS_DIR', None) setattr(django_settings, 'ASKBOT_EXTRA_SKINS_DIR', self.temp_dir) skin_image_dir = os.path.join( self.temp_dir, 'test_skin', 'media', 'images' ) mkdir_p(skin_image_dir) test_image_file = os.path.join( askbot.get_install_directory(), 'tests', 'images', 'logo.gif' ) shutil.copy(test_image_file, skin_image_dir)
def setUp(self): #create dummy skin self.temp_dir = tempfile.mkdtemp() self.skins_dir_backup = getattr(django_settings, 'ASKBOT_EXTRA_SKINS_DIR', None) setattr(django_settings, 'ASKBOT_EXTRA_SKINS_DIR', self.temp_dir) skin_image_dir = os.path.join( self.temp_dir, 'test_skin', 'media', 'images' ) mkdir_p(skin_image_dir) test_image_file = os.path.join( askbot.get_install_directory(), 'tests', 'images', 'logo.gif' ) shutil.copy(test_image_file, skin_image_dir)
def get_available_skins(selected=None): """Returns a dictionary of skin name --> directory where "templates" and "media" subdirectories can be found. selected is a name of preferred skin if it's None, then information about all skins will be returned otherwise, only data about selected and default skins will be returned selected skin is guaranteed to be the first item in the dictionary """ skins = OrderedDict() extra_skins_dir = getattr(django_settings, 'ASKBOT_EXTRA_SKINS_DIR', None) if extra_skins_dir: skins.update(get_skins_from_dir(extra_skins_dir)) if 'default' in skins: raise ValueError( '"default" is not an acceptable name for a custom skin') if selected in skins: selected_dir = skins[selected] skins.clear() skins[selected] = selected_dir elif selected == 'default': skins = OrderedDict() elif selected: raise ValueError( 'skin ' + str(selected) + \ ' not found, please check ASKBOT_EXTRA_SKINS_DIR setting ' + \ 'or in the corresponding directory' ) #insert default as a last item skins['default'] = askbot.get_install_directory() return skins
def tearDown(self): # delete the dummy skin test_skin_dir = os.path.join(askbot.get_install_directory(), "skins", "test_skin") shutil.rmtree(test_skin_dir) askbot_settings.update("ASKBOT_DEFAULT_SKIN", "default")
def tearDown(self): #delete the dummy skin test_skin_dir = os.path.join(askbot.get_install_directory(), 'skins', 'test_skin') shutil.rmtree(test_skin_dir)
def forwards(self, orm): "Write your forwards methods here." profiles = orm['askbot.GroupProfile'].objects.all() items = profiles.iterator() count = profiles.count() message = 'Transfering group information from Tag to Group model' for profile in ProgressBar(items, count, message): group_tag = profile.group_tag group_name = group_tag.name.replace('-', ' ') group = orm['askbot.Group']() group.name = group_name group.logo_url = profile.logo_url group.moderate_email = profile.moderate_email group.is_open = profile.is_open group.preapproved_emails = profile.preapproved_emails group.preapproved_email_domains = profile.preapproved_email_domains try: #see if such group is already there auth_group = orm['auth.Group'].objects.get(name=group_name) group.group_ptr = auth_group except orm['auth.Group'].DoesNotExist: pass group.save() #update thread groups thread_groups = orm['askbot.ThreadToGroup'].objects thread_groups = thread_groups.filter(tag=group_tag) thread_groups.update(group=group) #update post groups post_groups = orm['askbot.PostToGroup'].objects post_groups = post_groups.filter(tag=group_tag) post_groups.update(group=group) #update user groups memberships = group_tag.user_memberships.all() for membership in memberships: membership.user.groups.add(group) db_engine_name = askbot.get_database_engine_name() if 'postgresql_psycopg2' in db_engine_name: from django.db import connection cursor = connection.cursor() cursor.execute( 'DROP TRIGGER IF EXISTS group_membership_tsv_update_trigger ' 'ON askbot_groupmembership' ) message = 'Deleting old group information' items = profiles.iterator() for profile in ProgressBar(items, count, message): group_tag = profile.group_tag group_tag.user_memberships.all().delete() profile.delete() #for postgresql setup new user full text search if 'postgresql_psycopg2' in db_engine_name: script_path = os.path.join( askbot.get_install_directory(), 'search', 'postgresql', 'user_profile_search_08312012.plsql' ) setup_full_text_search(script_path)
def tearDown(self): #delete the dummy skin test_skin_dir = os.path.join(askbot.get_install_directory(), 'skins', 'test_skin') shutil.rmtree(test_skin_dir) askbot_settings.update('ASKBOT_DEFAULT_SKIN', 'default')
from askbot.conf.settings_wrapper import settings from askbot.deps.livesettings import ConfigurationGroup from askbot.deps.livesettings import BooleanValue, StringValue from django.utils.translation import ugettext as _ import askbot from askbot import const import os MARKUP = ConfigurationGroup( 'MARKUP', _('Markup formatting') ) mathjax_dir = os.path.join( askbot.get_install_directory(), 'skins', 'common', 'media' ) settings.register( BooleanValue( MARKUP, 'MARKUP_CODE_FRIENDLY', description = _('Enable code-friendly Markdown'), help_text = _( 'If checked, underscore characters will not ' 'trigger italic or bold formatting - ' 'bold and italic text can still be marked up ' 'with asterisks. Note that "MathJax support" '
# encoding:utf-8 """ All constants could be used in other modules For reasons that models, views can't have unicode text in this project, all unicode text go here. """ from django.utils.translation import ugettext_lazy as _ import os import re from askbot import get_install_directory DEFAULT_USER_DATA_EXPORT_DIR = os.path.abspath( os.path.join(get_install_directory(), '..', 'user_data') ) #todo: customize words CLOSE_REASONS = ( (1, _('duplicate question')), (2, _('question is off-topic or not relevant')), (3, _('too subjective and argumentative')), (4, _('not a real question')), (5, _('the question is answered, right answer was accepted')), (6, _('question is not relevant or outdated')), (7, _('question contains offensive or malicious remarks')), (8, _('spam or advertising')), (9, _('too localized')), ) LONG_TIME = 60*60*24*30 #30 days is a lot of time
# encoding:utf-8 """ All constants could be used in other modules For reasons that models, views can't have unicode text in this project, all unicode text go here. """ from django.utils.translation import ugettext_lazy as _ import os import re from askbot import get_install_directory DEFAULT_USER_DATA_EXPORT_DIR = os.path.abspath( os.path.join(get_install_directory(), '..', 'user_data')) #todo: customize words CLOSE_REASONS = ( (1, _('duplicate question')), (2, _('question is off-topic or not relevant')), (3, _('too subjective and argumentative')), (4, _('not a real question')), (5, _('the question is answered, right answer was accepted')), (6, _('question is not relevant or outdated')), (7, _('question contains offensive or malicious remarks')), (8, _('spam or advertising')), (9, _('too localized')), ) LONG_TIME = 60 * 60 * 24 * 30 #30 days is a lot of time DATETIME_FORMAT = '%I:%M %p, %d %b %Y' SHARE_NOTHING = 0
def get_tinymce_sample_config(): """returns the sample configuration for TinyMCE as string""" askbot_root = askbot.get_install_directory() file_path = os.path.join(askbot_root, 'setup_templates', 'tinymce_sample_config.py') return open(file_path, 'r').read()
def test_command(self): # create user today = date.today() # create user & fill out profile user = User.objects.create(username='******', email='*****@*****.**') profile = UserProfile(auth_user_ptr=user, date_of_birth=today) profile.save() lang1 = 'en' lang2 = 'es' localized_profile1 = LocalizedUserProfile(auth_user=user, language_code=lang1, about='about me') localized_profile1.save() localized_profile2 = LocalizedUserProfile(auth_user=user, language_code=lang2, about='sobre mi') localized_profile2.save() # put three upfiles in place paths = list() for idx in range(1, 4): path = self.put_upfile('file{}.txt'.format(idx)) paths.append(path) # post question with an image text_tpl ='hello there ![image]({} "Image {}")' url = self.get_upfile_url_from_path(paths[0]) question_text = text_tpl.format(url, 1) question = user.post_question(title='question', body_text=question_text, tags='one two') # post answer with an image url = self.get_upfile_url_from_path(paths[1]) answer_text = text_tpl.format(url, 2) answer = user.post_answer(question, answer_text) # post comment with an image url = self.get_upfile_url_from_path(paths[2]) comment_text = text_tpl.format(url, 3) comment = user.post_comment(answer, comment_text) # run extract data command into a temp dir askbot_dir = askbot.get_install_directory() test_dir = os.path.join(askbot_dir, 'tests', 'temp_export_user_data') if os.path.isdir(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) backup_file = os.path.join(test_dir, 'backup.zip') management.call_command('askbot_export_user_data', user_id=user.pk, file_name=backup_file) # test: unzip the file zip_file = zipfile.ZipFile(backup_file, 'r') extract_dir = os.path.join(test_dir, 'extracted') zip_file.extractall(extract_dir) json_file = os.path.join(extract_dir, 'data.json') self.assertTrue(os.path.isfile(json_file)) # test: load json json_data = json.loads(open(json_file).read()) # test: validate question q_data = json_data['questions'][0] thread = question.thread self.assertEqual(q_data['title'], thread.title) self.assertEqual(q_data['tags'], thread.tagnames) self.assertEqual(q_data['text'], question.text) self.assertEqual(q_data['added_at'], str(question.added_at)) self.assertEqual(q_data['last_edited_at'], str(question.last_edited_at)) question_url = site_url(question.get_absolute_url()) self.assertEqual(q_data['url'], question_url) # test: validate answer, just check it's there self.assertEqual(len(json_data['answers']), 1) # test: validate comment self.assertEqual(len(json_data['comments']), 1) # test: validate user profile data user_data = json_data['user_profile'] self.assertEqual(user_data['username'], user.username) lang_data = user_data['localized_profiles'] profile_url_tpl = site_url('/{}/users/{}/bob/') self.assertEqual(lang_data[lang1]['about'], 'about me') lang1_url = profile_url_tpl.format('en', user.pk) self.assertEqual(lang_data[lang1]['profile_url'], lang1_url) self.assertEqual(lang_data[lang2]['about'], 'sobre mi') lang2_url = profile_url_tpl.format('es', user.pk) self.assertEqual(lang_data[lang2]['profile_url'], lang2_url) self.assertEqual(user_data['email'], user.email) self.assertEqual(user_data['date_of_birth'], str(today)) # test: verify that uploaded files are there upfile_names = [os.path.basename(path) for path in paths] for name in upfile_names: extracted_path = os.path.join(extract_dir, 'upfiles', name) self.assertTrue(os.path.isfile(extracted_path)) shutil.rmtree(test_dir)
import subprocess, os from django.core.management.base import NoArgsCommand import askbot DOC_DIR = os.path.join(askbot.get_install_directory(), 'doc') class Command(NoArgsCommand): def handle_noargs(self, **options): os.chdir(DOC_DIR) subprocess.call(['make', 'html'])
def test_staticfiles(): """tests configuration of the staticfiles app""" errors = list() django_version = django.VERSION if django_version[0] == 1 and django_version[1] < 3: staticfiles_app_name = "staticfiles" wrong_staticfiles_app_name = "django.contrib.staticfiles" try_import("staticfiles", "django-staticfiles") import staticfiles if staticfiles.__version__[0] != 1: raise AskbotConfigError( "Please use the newest available version of " "django-staticfiles app, type\n" "pip install --upgrade django-staticfiles" ) if not hasattr(django_settings, "STATICFILES_STORAGE"): raise AskbotConfigError( "Configure STATICFILES_STORAGE setting as desired, " "a reasonable default is\n" "STATICFILES_STORAGE = 'staticfiles.storage.StaticFilesStorage'" ) else: staticfiles_app_name = "django.contrib.staticfiles" wrong_staticfiles_app_name = "staticfiles" if staticfiles_app_name not in django_settings.INSTALLED_APPS: errors.append("Add to the INSTALLED_APPS section of your settings.py:\n" " '%s'," % staticfiles_app_name) if wrong_staticfiles_app_name in django_settings.INSTALLED_APPS: errors.append( "Remove from the INSTALLED_APPS section of your settings.py:\n" " '%s'," % wrong_staticfiles_app_name ) static_url = django_settings.STATIC_URL or "" if static_url is None or str(static_url).strip() == "": errors.append( "Add STATIC_URL setting to your settings.py file. " "The setting must be a url at which static files " "are accessible." ) url = urlparse(static_url).path if not (url.startswith("/") and url.endswith("/")): # a simple check for the url errors.append("Path in the STATIC_URL must start and end with the /.") if django_settings.ADMIN_MEDIA_PREFIX != static_url + "admin/": errors.append("Set ADMIN_MEDIA_PREFIX as: \n" " ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'") # django_settings.STATICFILES_DIRS can have strings or tuples staticfiles_dirs = [d[1] if isinstance(d, tuple) else d for d in django_settings.STATICFILES_DIRS] default_skin_tuple = None askbot_root = askbot.get_install_directory() old_default_skin_dir = os.path.abspath(os.path.join(askbot_root, "skins")) for dir_entry in django_settings.STATICFILES_DIRS: if isinstance(dir_entry, tuple): if dir_entry[0] == "default/media": default_skin_tuple = dir_entry elif isinstance(dir_entry, str): if os.path.abspath(dir_entry) == old_default_skin_dir: errors.append("Remove from STATICFILES_DIRS in your settings.py file:\n" + dir_entry) askbot_root = os.path.dirname(askbot.__file__) default_skin_media_dir = os.path.abspath(os.path.join(askbot_root, "media")) if default_skin_tuple: media_dir = default_skin_tuple[1] if default_skin_media_dir != os.path.abspath(media_dir): errors.append( "Add to STATICFILES_DIRS the following entry: " "('default/media', os.path.join(ASKBOT_ROOT, 'media'))," ) extra_skins_dir = getattr(django_settings, "ASKBOT_EXTRA_SKINS_DIR", None) if extra_skins_dir is not None: if not os.path.isdir(extra_skins_dir): errors.append( "Directory specified with settning ASKBOT_EXTRA_SKINS_DIR " "must exist and contain your custom skins for askbot." ) if extra_skins_dir not in staticfiles_dirs: errors.append( "Add ASKBOT_EXTRA_SKINS_DIR to STATICFILES_DIRS entry in " "your settings.py file.\n" "NOTE: it might be necessary to move the line with " "ASKBOT_EXTRA_SKINS_DIR just above STATICFILES_DIRS." ) if django_settings.STATICFILES_STORAGE == "django.contrib.staticfiles.storage.StaticFilesStorage": if os.path.dirname(django_settings.STATIC_ROOT) == "": # static root is needed only for local storoge of # the static files raise AskbotConfigError("Specify the static files directory " "with setting STATIC_ROOT") if errors: errors.append("Run command (after fixing the above errors)\n" " python manage.py collectstatic\n") print_errors(errors) if django_settings.STATICFILES_STORAGE == "django.contrib.staticfiles.storage.StaticFilesStorage": if not os.path.isdir(django_settings.STATIC_ROOT): askbot_warning("Please run command\n\n" " python manage.py collectstatic")
def test_command(self): # create user today = date.today() # create user & fill out profile user = User.objects.create(username='******', email='*****@*****.**') profile = UserProfile(auth_user_ptr=user, date_of_birth=today) profile.save() lang1 = 'en' lang2 = 'es' localized_profile1 = LocalizedUserProfile(auth_user=user, language_code=lang1, about='about me') localized_profile1.save() localized_profile2 = LocalizedUserProfile(auth_user=user, language_code=lang2, about='sobre mi') localized_profile2.save() # put three upfiles in place paths = list() for idx in range(1, 4): path = self.put_upfile('file{}.txt'.format(idx)) paths.append(path) # post question with an image text_tpl = 'hello there ![image]({} "Image {}")' url = self.get_upfile_url_from_path(paths[0]) question_text = text_tpl.format(url, 1) question = user.post_question(title='question', body_text=question_text, tags='one two') # post answer with an image url = self.get_upfile_url_from_path(paths[1]) answer_text = text_tpl.format(url, 2) answer = user.post_answer(question, answer_text) # post comment with an image url = self.get_upfile_url_from_path(paths[2]) comment_text = text_tpl.format(url, 3) comment = user.post_comment(answer, comment_text) # run extract data command into a temp dir askbot_dir = askbot.get_install_directory() test_dir = os.path.join(askbot_dir, 'tests', 'temp_export_user_data') if os.path.isdir(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) backup_file = os.path.join(test_dir, 'backup.zip') management.call_command('askbot_export_user_data', user_id=user.pk, file_name=backup_file) # test: unzip the file zip_file = zipfile.ZipFile(backup_file, 'r') extract_dir = os.path.join(test_dir, 'extracted') zip_file.extractall(extract_dir) json_file = os.path.join(extract_dir, 'data.json') self.assertTrue(os.path.isfile(json_file)) # test: load json with open(json_file) as f: json_data = json.loads(f.read()) # test: validate question q_data = json_data['questions'][0] thread = question.thread self.assertEqual(q_data['title'], thread.title) self.assertEqual(q_data['tags'], thread.tagnames) self.assertEqual(q_data['text'], question.text) self.assertEqual(q_data['added_at'], str(question.added_at)) self.assertEqual(q_data['last_edited_at'], str(question.last_edited_at)) question_url = site_url(question.get_absolute_url()) self.assertEqual(q_data['url'], question_url) # test: validate answer, just check it's there self.assertEqual(len(json_data['answers']), 1) # test: validate comment self.assertEqual(len(json_data['comments']), 1) # test: validate user profile data user_data = json_data['user_profile'] self.assertEqual(user_data['username'], user.username) lang_data = user_data['localized_profiles'] profile_url_tpl = site_url('/{}/users/{}/bob/') self.assertEqual(lang_data[lang1]['about'], 'about me') lang1_url = profile_url_tpl.format('en', user.pk) self.assertEqual(lang_data[lang1]['profile_url'], lang1_url) self.assertEqual(lang_data[lang2]['about'], 'sobre mi') lang2_url = profile_url_tpl.format('es', user.pk) self.assertEqual(lang_data[lang2]['profile_url'], lang2_url) self.assertEqual(user_data['email'], user.email) self.assertEqual(user_data['date_of_birth'], str(today)) # test: verify that uploaded files are there upfile_names = [os.path.basename(path) for path in paths] for name in upfile_names: extracted_path = os.path.join(extract_dir, 'upfiles', name) self.assertTrue(os.path.isfile(extracted_path)) shutil.rmtree(test_dir)
def setUp(self): # create dummy skin skin_image_dir = os.path.join(askbot.get_install_directory(), "skins", "test_skin", "media", "images") mkdir_p(skin_image_dir) test_image_file = os.path.join(askbot.get_install_directory(), "tests", "images", "logo.gif") shutil.copy(test_image_file, skin_image_dir)
def test_staticfiles(): """tests configuration of the staticfiles app""" errors = list() django_version = django.VERSION if django_version[0] == 1 and django_version[1] < 3: staticfiles_app_name = 'staticfiles' wrong_staticfiles_app_name = 'django.contrib.staticfiles' try_import('staticfiles', 'django-staticfiles') import staticfiles if staticfiles.__version__[0] != 1: raise AskbotConfigError( 'Please use the newest available version of ' 'django-staticfiles app, type\n' 'pip install --upgrade django-staticfiles' ) if not hasattr(django_settings, 'STATICFILES_STORAGE'): raise AskbotConfigError( 'Configure STATICFILES_STORAGE setting as desired, ' 'a reasonable default is\n' "STATICFILES_STORAGE = 'staticfiles.storage.StaticFilesStorage'" ) else: staticfiles_app_name = 'django.contrib.staticfiles' wrong_staticfiles_app_name = 'staticfiles' if staticfiles_app_name not in django_settings.INSTALLED_APPS: errors.append( 'Add to the INSTALLED_APPS section of your settings.py:\n' " '%s'," % staticfiles_app_name ) if wrong_staticfiles_app_name in django_settings.INSTALLED_APPS: errors.append( 'Remove from the INSTALLED_APPS section of your settings.py:\n' " '%s'," % wrong_staticfiles_app_name ) static_url = django_settings.STATIC_URL or '' if static_url is None or str(static_url).strip() == '': errors.append( 'Add STATIC_URL setting to your settings.py file. ' 'The setting must be a url at which static files ' 'are accessible.' ) url = urlparse(static_url).path if not (url.startswith('/') and url.endswith('/')): #a simple check for the url errors.append( 'Path in the STATIC_URL must start and end with the /.' ) if django_settings.ADMIN_MEDIA_PREFIX != static_url + 'admin/': errors.append( 'Set ADMIN_MEDIA_PREFIX as: \n' " ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'" ) # django_settings.STATICFILES_DIRS can have strings or tuples staticfiles_dirs = [d[1] if isinstance(d, tuple) else d for d in django_settings.STATICFILES_DIRS] default_skin_tuple = None askbot_root = askbot.get_install_directory() old_default_skin_dir = os.path.abspath(os.path.join(askbot_root, 'skins')) for dir_entry in django_settings.STATICFILES_DIRS: if isinstance(dir_entry, tuple): if dir_entry[0] == 'default/media': default_skin_tuple = dir_entry elif isinstance(dir_entry, str): if os.path.abspath(dir_entry) == old_default_skin_dir: errors.append( 'Remove from STATICFILES_DIRS in your settings.py file:\n' + dir_entry ) askbot_root = os.path.dirname(askbot.__file__) default_skin_media_dir = os.path.abspath(os.path.join(askbot_root, 'media')) if default_skin_tuple: media_dir = default_skin_tuple[1] if default_skin_media_dir != os.path.abspath(media_dir): errors.append( 'Add to STATICFILES_DIRS the following entry: ' "('default/media', os.path.join(ASKBOT_ROOT, 'media'))," ) extra_skins_dir = getattr(django_settings, 'ASKBOT_EXTRA_SKINS_DIR', None) if extra_skins_dir is not None: if not os.path.isdir(extra_skins_dir): errors.append( 'Directory specified with setting ASKBOT_EXTRA_SKINS_DIR ' 'must exist and contain your custom skins for askbot.' ) if extra_skins_dir not in staticfiles_dirs: errors.append( 'Add ASKBOT_EXTRA_SKINS_DIR to STATICFILES_DIRS entry in ' 'your settings.py file.\n' 'NOTE: it might be necessary to move the line with ' 'ASKBOT_EXTRA_SKINS_DIR just above STATICFILES_DIRS.' ) if django_settings.STATICFILES_STORAGE == \ 'django.contrib.staticfiles.storage.StaticFilesStorage': if os.path.dirname(django_settings.STATIC_ROOT) == '': #static root is needed only for local storoge of #the static files raise AskbotConfigError( 'Specify the static files directory ' 'with setting STATIC_ROOT' ) if errors: errors.append( 'Run command (after fixing the above errors)\n' ' python manage.py collectstatic\n' ) required_finders = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) finders = getattr(django_settings, 'STATICFILES_FINDERS', None) missing_finders = list() for finder in required_finders: if finder not in finders: missing_finders.append(finder) if missing_finders: errors.append( 'Please make sure that the following items are \n' + \ 'part of the STATICFILES_FINDERS tuple, create this tuple, if it is missing:\n' + ' "' + '",\n "'.join(missing_finders) + '",\n' ) print_errors(errors) if django_settings.STATICFILES_STORAGE == \ 'django.contrib.staticfiles.storage.StaticFilesStorage': if not os.path.isdir(django_settings.STATIC_ROOT): askbot_warning( 'Please run command\n\n' ' python manage.py collectstatic' )