id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
20,200
views.py
django-wiki_django-wiki/src/wiki/plugins/globalhistory/views.py
from django.contrib.auth.decorators import login_required from django.db.models import F from django.utils.decorators import method_decorator from django.views.generic import ListView from wiki import models from wiki.core.paginator import WikiPaginator class GlobalHistory(ListView): template_name = "wiki/plugins/globalhistory/globalhistory.html" paginator_class = WikiPaginator paginate_by = 30 model = models.ArticleRevision context_object_name = "revisions" @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): self.only_last = kwargs.get("only_last", 0) return super().dispatch(request, *args, **kwargs) def get_queryset(self): if self.only_last == "1": return ( self.model.objects.can_read(self.request.user) .filter(article__current_revision=F("id")) .order_by("-modified") ) else: return self.model.objects.can_read(self.request.user).order_by( "-modified" ) def get_context_data(self, **kwargs): kwargs["only_last"] = self.only_last return super().get_context_data(**kwargs)
1,213
Python
.py
30
32.733333
75
0.664686
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,201
models.py
django-wiki_django-wiki/src/wiki/plugins/notifications/models.py
from django.db import models from django.db.models import signals from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django_nyt.models import Subscription from django_nyt.utils import notify from wiki import models as wiki_models from wiki.decorators import disable_signal_for_loaddata from wiki.models.pluginbase import ArticlePlugin from wiki.plugins.notifications import settings from wiki.plugins.notifications.util import get_title class ArticleSubscription(ArticlePlugin): subscription = models.OneToOneField(Subscription, on_delete=models.CASCADE) def __str__(self): title = _("%(user)s subscribing to %(article)s (%(type)s)") % { "user": self.subscription.settings.user.username, "article": self.article.current_revision.title, "type": self.subscription.notification_type.label, } return str(title) class Meta: unique_together = ("subscription", "articleplugin_ptr") # Matches label of upcoming 0.1 release db_table = "wiki_notifications_articlesubscription" def default_url(article, urlpath=None): if urlpath: return reverse("wiki:get", kwargs={"path": urlpath.path}) return article.get_absolute_url() @disable_signal_for_loaddata def post_article_revision_save(**kwargs): instance = kwargs["instance"] if kwargs.get("created", False): url = default_url(instance.article) filter_exclude = {"settings__user": instance.user} if instance.deleted: notify( _("Article deleted: %s") % get_title(instance), settings.ARTICLE_EDIT, target_object=instance.article, url=url, filter_exclude=filter_exclude, ) elif instance.previous_revision: notify( _("Article modified: %s") % get_title(instance), settings.ARTICLE_EDIT, target_object=instance.article, url=url, filter_exclude=filter_exclude, ) else: notify( _("New article created: %s") % get_title(instance), settings.ARTICLE_EDIT, target_object=instance, url=url, filter_exclude=filter_exclude, ) # Whenever a new revision is created, we notif√Ω users that an article # was edited signals.post_save.connect( post_article_revision_save, sender=wiki_models.ArticleRevision, ) # TODO: We should notify users when the current_revision of an article is # changed...
2,644
Python
.py
66
31.621212
79
0.65446
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,202
util.py
django-wiki_django-wiki/src/wiki/plugins/notifications/util.py
from django.utils.translation import gettext as _ def get_title(article): """Utility function to format the title of an article...""" return truncate_title(article.title) def truncate_title(title): """Truncate a title (of an article, file, image etc) to be displayed in notifications messages.""" if not title: return _("(none)") if len(title) > 25: return "%s..." % title[:22] return title
435
Python
.py
11
34.545455
102
0.67381
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,203
settings.py
django-wiki_django-wiki/src/wiki/plugins/notifications/settings.py
# Deprecated APP_LABEL = None # Key for django_nyt - changing it will break any existing notifications. ARTICLE_EDIT = "article_edit" SLUG = "notifications"
159
Python
.py
5
30.4
73
0.782895
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,204
apps.py
django-wiki_django-wiki/src/wiki/plugins/notifications/apps.py
from django.apps import AppConfig from django.db.models import signals from django.utils.translation import gettext_lazy as _ class NotificationsConfig(AppConfig): name = "wiki.plugins.notifications" verbose_name = _("Wiki notifications") label = "wiki_notifications" def ready(self): """ NOTIFICATIONS FOR PLUGINS """ from django_nyt.utils import notify from wiki.core.plugins import registry from wiki.decorators import disable_signal_for_loaddata from . import models def get_receiver(notification_dict): @disable_signal_for_loaddata def plugin_notification(instance, **kwargs): if notification_dict.get("ignore", lambda x: False)(instance): return if kwargs.get("created", False) == notification_dict.get( "created", True ): if "get_url" in notification_dict: url = notification_dict["get_url"](instance) else: url = models.default_url( notification_dict["get_article"](instance) ) message = notification_dict["message"](instance) notify( message, notification_dict["key"], target_object=notification_dict["get_article"]( instance ), url=url, ) return plugin_notification for plugin in registry.get_plugins(): notifications = getattr(plugin, "notifications", []) for notification_dict in notifications: signals.post_save.connect( get_receiver(notification_dict), sender=notification_dict["model"], )
1,967
Python
.py
46
27.347826
78
0.529258
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,205
wiki_plugin.py
django-wiki_django-wiki/src/wiki/plugins/notifications/wiki_plugin.py
from django.urls import re_path from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from . import settings from . import views class NotifyPlugin(BasePlugin): slug = settings.SLUG urlpatterns = { "root": [ re_path( r"^$", views.NotificationSettings.as_view(), name="notification_settings", ), ] } article_view = views.NotificationSettings().dispatch settings_form = "wiki.plugins.notifications.forms.SubscriptionForm" registry.register(NotifyPlugin)
598
Python
.py
19
24.421053
71
0.664336
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,206
forms.py
django-wiki_django-wiki/src/wiki/plugins/notifications/forms.py
from django import forms from django.contrib.contenttypes.models import ContentType from django.forms.models import BaseModelFormSet from django.forms.models import modelformset_factory from django.utils.safestring import mark_safe from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from django_nyt.models import NotificationType from django_nyt.models import Settings from django_nyt.models import Subscription from wiki.core.plugins.base import PluginSettingsFormMixin from wiki.plugins.notifications import models from wiki.plugins.notifications.settings import ARTICLE_EDIT class SettingsModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return gettext("Receive notifications %(interval)s") % { "interval": obj.get_interval_display() } class ArticleSubscriptionModelMultipleChoiceField( forms.ModelMultipleChoiceField ): def label_from_instance(self, obj): return gettext("%(title)s - %(url)s") % { "title": obj.article.current_revision.title, "url": obj.article.get_absolute_url(), } class SettingsModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") super().__init__(*args, **kwargs) instance = kwargs.get("instance", None) self.__editing_instance = False if instance: self.__editing_instance = True self.fields[ "delete_subscriptions" ] = ArticleSubscriptionModelMultipleChoiceField( models.ArticleSubscription.objects.filter( subscription__settings=instance, article__current_revision__deleted=False, ), label=gettext("Remove subscriptions"), required=False, help_text=gettext( "Select article subscriptions to remove from notifications" ), initial=models.ArticleSubscription.objects.none(), ) self.fields["email"] = forms.TypedChoiceField( label=_("Email digests"), choices=( (0, gettext("Unchanged (selected on each article)")), (1, gettext("No emails")), (2, gettext("Email on any change")), ), coerce=lambda x: int(x) if x is not None else None, widget=forms.RadioSelect(), required=False, initial=0, ) def save(self, *args, **kwargs): instance = super().save(*args, commit=False, **kwargs) instance.user = self.user if self.__editing_instance: self.cleaned_data["delete_subscriptions"].delete() if self.cleaned_data["email"] == 1: instance.subscription_set.all().update( send_emails=False, ) elif self.cleaned_data["email"] == 2: instance.subscription_set.all().update( send_emails=True, ) instance.save() return instance class BaseSettingsFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop("user") # Ensure that at least 1 default settings object exists all_settings = Settings.objects.filter(user=self.user).order_by( "is_default" ) if not all_settings.exists(): Settings.objects.create(user=self.user, is_default=True) else: to_update = all_settings.first() if not to_update.is_default: to_update.is_default = True to_update.save() super().__init__(*args, **kwargs) def get_queryset(self): return ( Settings.objects.filter( user=self.user, ) .exclude( subscription__articlesubscription__article__current_revision__deleted=True, ) .prefetch_related( "subscription_set__articlesubscription", ) .order_by("is_default") .distinct() ) SettingsFormSet = modelformset_factory( Settings, form=SettingsModelForm, formset=BaseSettingsFormSet, extra=0, fields=("interval",), ) class SubscriptionForm(PluginSettingsFormMixin, forms.Form): settings_form_headline = _("Notifications") settings_order = 1 settings_write_access = False settings = SettingsModelChoiceField( None, empty_label=None, label=_("Settings") ) edit = forms.BooleanField( required=False, label=_("When this article is edited") ) edit_email = forms.BooleanField( required=False, label=_("Also receive emails about article edits"), widget=forms.CheckboxInput( attrs={ "onclick": mark_safe( "$('#id_edit').attr('checked', $(this).is(':checked'));" ) } ), ) def __init__(self, article, request, *args, **kwargs): self.article = article self.user = request.user initial = kwargs.pop("initial", None) self.notification_type = NotificationType.objects.get_or_create( key=ARTICLE_EDIT, content_type=ContentType.objects.get_for_model(article), )[0] self.edit_notifications = models.ArticleSubscription.objects.filter( article=article, subscription__notification_type=self.notification_type, subscription__settings__user=self.user, ) self.default_settings = Settings.get_default_setting(request.user) if self.edit_notifications: self.default_settings = self.edit_notifications[ 0 ].subscription.settings if not initial: initial = { "edit": bool(self.edit_notifications), "edit_email": bool( self.edit_notifications.filter( subscription__send_emails=True ) ), "settings": self.default_settings, } kwargs["initial"] = initial super().__init__(*args, **kwargs) self.fields["settings"].queryset = Settings.objects.filter( user=request.user, ) def get_usermessage(self): if self.changed_data: return _("Your notification settings were updated.") else: return _( "Your notification settings were unchanged, so nothing saved." ) def save(self, *args, **kwargs): if not self.changed_data: return if self.cleaned_data["edit"]: try: edit_notification = models.ArticleSubscription.objects.get( subscription__notification_type=self.notification_type, article=self.article, subscription__settings=self.cleaned_data["settings"], ) edit_notification.subscription.send_emails = self.cleaned_data[ "edit_email" ] edit_notification.subscription.save() except models.ArticleSubscription.DoesNotExist: subscription, __ = Subscription.objects.get_or_create( settings=self.cleaned_data["settings"], notification_type=self.notification_type, object_id=self.article.id, ) models.ArticleSubscription.objects.create( subscription=subscription, article=self.article, ) subscription.send_emails = self.cleaned_data["edit_email"] subscription.save() else: self.edit_notifications.delete()
8,008
Python
.py
200
28.4
91
0.58282
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,207
views.py
django-wiki_django-wiki/src/wiki/plugins/notifications/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.utils.translation import gettext as _ from django.views.generic import FormView from . import forms from . import models class NotificationSettings(FormView): template_name = "wiki/plugins/notifications/settings.html" form_class = forms.SettingsFormSet @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def form_valid(self, formset): for form in formset: settings = form.save() messages.info( self.request, _( "You will receive notifications %(interval)s for " "%(articles)d articles" ) % { "interval": settings.get_interval_display(), "articles": self.get_article_subscriptions( form.instance ).count(), }, ) return redirect("wiki:notification_settings") def get_article_subscriptions(self, nyt_settings): return ( models.ArticleSubscription.objects.filter( subscription__settings=nyt_settings, article__current_revision__deleted=False, ) .select_related("article", "article__current_revision") .distinct() ) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["user"] = self.request.user kwargs["form_kwargs"] = {"user": self.request.user} return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["formset"] = context["form"] for form in context["formset"]: if form.instance: form.instance.articlesubscriptions = ( self.get_article_subscriptions(form.instance) ) return context
2,150
Python
.py
54
29.037037
70
0.600096
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,208
0002_auto_20151118_1811.py
django-wiki_django-wiki/src/wiki/plugins/notifications/migrations/0002_auto_20151118_1811.py
from django.db import migrations class Migration(migrations.Migration): atomic = False dependencies = [ ("wiki_notifications", "0001_initial"), ] operations = [ migrations.AlterModelTable( name="articlesubscription", table="wiki_notifications_articlesubscription", ), ]
343
Python
.py
12
21.5
59
0.647239
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,209
0001_initial.py
django-wiki_django-wiki/src/wiki/plugins/notifications/migrations/0001_initial.py
from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [ ("django_nyt", "0006_auto_20141229_1630"), ("wiki", "0001_initial"), ] operations = [ migrations.CreateModel( name="ArticleSubscription", fields=[ ( "articleplugin_ptr", models.OneToOneField( auto_created=True, to="wiki.ArticlePlugin", primary_key=True, parent_link=True, serialize=False, on_delete=models.CASCADE, ), ), ( "subscription", models.OneToOneField( to="django_nyt.Subscription", on_delete=models.CASCADE ), ), ], options={}, bases=("wiki.articleplugin",), ), migrations.AlterUniqueTogether( name="articlesubscription", unique_together={("subscription", "articleplugin_ptr")}, ), ]
1,215
Python
.py
37
18.216216
78
0.4523
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,210
wiki_notifications_create_defaults.py
django-wiki_django-wiki/src/wiki/plugins/notifications/management/commands/wiki_notifications_create_defaults.py
from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from django.utils import translation from django_nyt.models import Settings from django_nyt.utils import subscribe from wiki.models import Article from wiki.plugins.notifications import models from wiki.plugins.notifications.settings import ARTICLE_EDIT class Command(BaseCommand): args = "[file-name.csv]" # @ReservedAssignment help = "Import and parse messages directly from a CSV file." def handle(self, *args, **options): from django.conf import settings with translation.override(language=settings.LANGUAGE_CODE): # User: Settings settings_map = {} def subscribe_to_article(article, user): if user not in settings_map: settings_map[user], __ = Settings.objects.get_or_create( user=user ) return subscribe( settings_map[user], ARTICLE_EDIT, content_type=ContentType.objects.get_for_model(article), object_id=article.id, ) subs = 0 articles = Article.objects.all() for article in articles: if article.owner: subscription = subscribe_to_article(article, article.owner) models.ArticleSubscription.objects.get_or_create( article=article, subscription=subscription ) subs += 1 for revision in ( article.articlerevision_set.exclude(user=article.owner) .exclude(user=None) .values("user") .distinct() ): user = get_user_model().objects.get(id=revision["user"]) subs += 1 subscription = subscribe_to_article(article, user) models.ArticleSubscription.objects.get_or_create( article=article, subscription=subscription ) self.stdout.write( "Created {subs:d} subscriptions on {arts:d} articles".format( subs=subs, arts=articles.count(), ), ending="\n", )
2,478
Python
.py
57
28.929825
79
0.556569
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,211
settings.py
django-wiki_django-wiki/src/wiki/plugins/links/settings.py
from django.conf import settings as django_settings #: If a relative slug is used in a wiki markdown link and no article is #: found with the given slug starting at the current articles level a #: link to a not yet existing article is created. Creating the article #: can be done by following the link. This link will be relative to #: ``LOOKUP_LEVEL``. This should be the level that most articles are #: created at. LOOKUP_LEVEL = getattr(django_settings, "WIKI_LINKS_LOOKUP_LEVEL", 2)
488
Python
.py
8
59.875
71
0.77453
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,212
apps.py
django-wiki_django-wiki/src/wiki/plugins/links/apps.py
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class LinksConfig(AppConfig): name = "wiki.plugins.links" verbose_name = _("Wiki links") label = "wiki_links"
213
Python
.py
6
32.166667
54
0.746341
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,213
wiki_plugin.py
django-wiki_django-wiki/src/wiki/plugins/links/wiki_plugin.py
from django.urls import re_path from django.urls import reverse_lazy from django.utils.translation import gettext as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from wiki.plugins.links import settings from wiki.plugins.links import views from wiki.plugins.links.mdx.djangowikilinks import WikiPathExtension from wiki.plugins.links.mdx.urlize import makeExtension as urlize_makeExtension class LinkPlugin(BasePlugin): slug = "links" urlpatterns = { "article": [ re_path( r"^json/query-urlpath/$", views.QueryUrlPath.as_view(), name="links_query_urlpath", ), ] } sidebar = { "headline": _("Links"), "icon_class": "fa-bookmark", "template": "wiki/plugins/links/sidebar.html", "form_class": None, "get_form_kwargs": (lambda a: {}), } wikipath_config = [ ("base_url", reverse_lazy("wiki:get", kwargs={"path": ""})), ("default_level", settings.LOOKUP_LEVEL), ] markdown_extensions = [ urlize_makeExtension(), WikiPathExtension(wikipath_config), ] registry.register(LinkPlugin)
1,217
Python
.py
36
27.166667
79
0.651618
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,214
views.py
django-wiki_django-wiki/src/wiki/plugins/links/views.py
from django.utils.decorators import method_decorator from django.views.generic import View from wiki import models from wiki.core.utils import object_to_json_response from wiki.decorators import get_article class QueryUrlPath(View): @method_decorator(get_article(can_read=True)) def dispatch(self, request, article, *args, **kwargs): max_num = kwargs.pop("max_num", 20) query = request.GET.get("query", None) matches = [] if query: matches = ( models.URLPath.objects.can_read(request.user) .active() .filter( article__current_revision__title__contains=query, article__current_revision__deleted=False, ) ) matches = matches.select_related_common() matches = [ "[{title:s}](wiki:{url:s})".format( title=m.article.current_revision.title, url="/" + m.path.strip("/"), ) for m in matches[:max_num] ] return object_to_json_response(matches)
1,140
Python
.py
29
27.793103
69
0.564195
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,215
urlize.py
django-wiki_django-wiki/src/wiki/plugins/links/mdx/urlize.py
import re import xml import markdown # Regular expression is meant to match the following pattern: # # [BEGIN][PROTOCOL]HOST[:PORT][/[PATH]][END] # # Everything except HOST is meant to be optional, as denoted by square # brackets. # # Patter elements are as follows: # # BEGIN # String preceding the link. Can be empty, or any string that ends # in whitespace, '(', or '<'. # # PROTOCOL # Syntax defined in https://tools.ietf.org/html/rfc3986 - for # example: 'http://', 'https://', 'ftp://', or 'ftps://'. # # HOST # Host can be one of: IPv4 address, IPv6 address in full form, IPv6 # address in shortened form (e.g. ::1 vs 0:....:0:1 or any # combination of), FQDN-like entry (dot-separated domain # components), or string 'localhost'. # # PORT # Port should be a numeric value. Keep in mind that it must be # preceded with the colon (':'). # # PATH # Additional PATH, including any GET parameters that should be part # of the URL. # # END # String following the link. Can be empty, or any string that ends # in whitespace, ')', or '>'. If ')', then must match with '(' in # BEGIN. If '>', then must match with '<' in BEGIN. # # It should be noted that there are some inconsistencies with the below # regex, mainly that: # # - No IPv4 or IPv6 address validation is performed. # - Excessively long IPv6 addresses will end-up being matched if the # shortened form happens somewhere in the middle of host string. # # In order to make the regex easier to handle later on, the following # named groups are provided: # # - begin (string coming before the link, including whitespace or # brackets). # - url (entire URL that can be used, for example, as actual link for # href). # - protocol (protocol, together with the trailing ://) # - host (just the host part) # - port (just the port number) # - path (path, combined with any additional GET parameters) # - end (string coming after the link, including whitespace or # brackets) # URLIZE_RE = ( # Links must start at beginning of string, or be preceded with # whitespace, '(', or '<'. r"^(?P<begin>|.*?[\s\(\<])" r"(?P<url>" # begin url group # Leading protocol specification. r"(?P<protocol>([A-Z][A-Z0-9+.-]*://|))" # Host identifier r"(?P<host>" # begin host identifier group r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|" # IPv4, match before FQDN r"\[?([A-F0-9]{1,4}:){7}([A-F0-9]{1,4})\]?|" # IPv6, full form r"\[?:(:[A-F0-9]{1,4}){1,6}\]?|" # IPv6, leading zeros removed r"([A-F0-9]{1,4}:){1,6}:([A-F0-9]{1,4}){1,6}|" # IPv6, zeros in middle removed. r"\[?([A-F0-9]{1,4}:){1,6}:\]?|" # IPv6, trailing zeros removed r"\[?::\]?|" # IPv6, just "empty" address r"([A-Z0-9]([A-Z0-9-]{0,61}[A-Z0-9])?\.)+([A-Z]{2,6}\.?|[A-Z]{2,}\.?)" # FQDN r")" # end host identifier group # Optional port r"(:(?P<port>[0-9]+))?" # Optional trailing slash with path and GET parameters. r"(/(?P<path>[^\s\[\(\]\)\<\>]*))?" r")" # end url group # Links must stop at end of string, or be followed by a whitespace, ')', or '>'. r"(?P<end>[\s\)\>].*?|)$" ) class UrlizePattern(markdown.inlinepatterns.Pattern): def getCompiledRegExp(self): """ Return compiled regular expression for matching the URL patterns. We introduce case-insensitive matching in addition to standard matching flags added by parent class. """ # Ensure links are matched only if they stand on their own to avoid bad matches etc. return re.compile(URLIZE_RE, re.DOTALL | re.UNICODE | re.IGNORECASE) def handleMatch(self, m): """ Processes match found within the text. """ protocol = m.group("protocol") url = m.group("url") text = url begin_url = m.group("begin") end_url = m.group("end") # If opening and ending character for URL are not the same, # return text unchanged. if begin_url: begin_delimeter = begin_url[-1] else: begin_delimeter = "" if end_url: end_delimeter = end_url[0] else: end_delimeter = "" if ( begin_delimeter == "<" and end_delimeter != ">" or begin_delimeter == "(" and end_delimeter != ")" or end_delimeter == ")" and begin_delimeter != "(" or end_delimeter == ">" and begin_delimeter != "<" ): return url # If no supported protocol is specified, assume plaintext http # and add it to the url. if protocol == "": url = "http://" + url # Convenience link to distinguish external links more easily. # icon = markdown.util.etree.Element("span") icon = xml.etree.ElementTree.Element("span") icon.set("class", "fa fa-external-link-alt") # Link text. # span_text = markdown.util.etree.Element("span") span_text = xml.etree.ElementTree.Element("span") span_text.text = markdown.util.AtomicString(" " + text) # Set-up link itself. # el = markdown.util.etree.Element("a") el = xml.etree.ElementTree.Element("a") el.set("href", url) el.set("target", "_blank") el.set("rel", "nofollow") el.append(icon) el.append(span_text) return el class UrlizeExtension(markdown.extensions.Extension): """Urlize Extension for Python-Markdown.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def extendMarkdown(self, md): """Replace autolink with UrlizePattern""" # md.inlinePatterns["autolink"] = UrlizePattern(URLIZE_RE, md) md.inlinePatterns.register( UrlizePattern(URLIZE_RE, md), "autolink", 91 ) # 91 is hardcoded value to put it ahead of html def makeExtension(*args, **kwargs): return UrlizeExtension(*args, **kwargs)
6,005
Python
.py
157
32.77707
92
0.608823
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,216
djangowikilinks.py
django-wiki_django-wiki/src/wiki/plugins/links/mdx/djangowikilinks.py
""" Wikipath Extension for Python-Markdown ====================================== Converts [Link Name](wiki:ArticleName) to relative links pointing to article. Basic usage: >>> import markdown >>> text = "Some text with a [Link Name](wiki:ArticleName)." >>> html = markdown.markdown(text, ['wikipath(base_url="/wiki/view/")']) >>> html '<p>Some text with a <a class="wikipath" href="/wiki/view/ArticleName/">Link Name</a>.</p>' Dependencies: * [Python 3.4+](https://python.org) * [Markdown 2.6+](https://pypi.python.org/pypi/Markdown) """ from os import path as os_path from xml.etree import ElementTree as etree import markdown from wiki import models from wiki.conf import settings # from markdown.util import etree class WikiPathExtension(markdown.extensions.Extension): def __init__(self, configs): # set extension defaults self.config = { "base_url": ["/", "String to append to beginning of URL."], "html_class": ["wikipath", "CSS hook. Leave blank for none."], "default_level": [ 2, "The level that most articles are created at. Relative links will tend to start at that level.", ], } # Override defaults with user settings for key, value in configs: self.setConfig(key, value) def extendMarkdown(self, md): self.md = md # append to end of inline patterns WIKI_RE = r"\[(?P<label>[^\]]+?)\]\(wiki:(?P<wikipath>[a-zA-Z0-9\./_-]*?)(?P<fragment>#[a-zA-Z0-9\./_-]*)?\)" wikiPathPattern = WikiPath(WIKI_RE, self.config, md=md) wikiPathPattern.md = md md.inlinePatterns.register( wikiPathPattern, "djangowikipath", 171 ) # 171 is hardcoded value to put it ahead of reference class WikiPath(markdown.inlinepatterns.Pattern): def __init__(self, pattern, config, **kwargs): super().__init__(pattern, **kwargs) self.config = config # TODO: This method is too complex (C901) def handleMatch(self, m): # noqa: max-complexity 11 wiki_path = m.group("wikipath") absolute = False if wiki_path.startswith("/"): absolute = True wiki_path = wiki_path.strip("/") # Use this to calculate some kind of meaningful path # from the link, regardless of whether or not something can be # looked up path_from_link = "" if absolute: base_path = self.config["base_url"][0] path_from_link = os_path.join(str(base_path), wiki_path) urlpath = None path = path_from_link try: urlpath = models.URLPath.get_by_path(wiki_path) path = urlpath.get_absolute_url() except models.URLPath.DoesNotExist: pass # Treat as relative path, meaning relative to the markdown instance's article else: urlpath = models.URLPath.objects.get(article=self.md.article) source_components = urlpath.path.strip("/").split("/") # We take the first (self.config['default_level'] - 1) components, so adding # one more component would make a path of length # self.config['default_level'] starting_level = max(0, self.config["default_level"][0] - 1) starting_path = "/".join(source_components[:starting_level]) path_from_link = os_path.join(starting_path, wiki_path) lookup = models.URLPath.objects.none() if urlpath.parent: lookup = urlpath.parent.get_descendants().filter( slug=wiki_path ) else: lookup = urlpath.get_descendants().filter(slug=wiki_path) if lookup.count() > 0: urlpath = lookup[0] path = urlpath.get_absolute_url() else: urlpath = None path = self.config["base_url"][0] + path_from_link label = m.group("label") fragment = m.group("fragment") or "" href = path + fragment if settings.WIKILINKS_TRAILING_SLASH: if href and not href.endswith("/"): href = href + "/" else: if href.endswith("/") and len(href) > 1: href = href[:-1] a = etree.Element("a") a.set("href", href) if not urlpath: a.set("class", self.config["html_class"][0] + " linknotfound") else: a.set("class", self.config["html_class"][0]) a.text = label return a def _getMeta(self): """Return meta data or config data.""" base_url = self.config["base_url"][0] html_class = self.config["html_class"][0] if hasattr(self.md, "Meta"): if "wiki_base_url" in self.md.Meta: base_url = self.md.Meta["wiki_base_url"][0] if "wiki_html_class" in self.md.Meta: html_class = self.md.Meta["wiki_html_class"][0] return base_url, html_class def makeExtension(**kwargs): return WikiPathExtension(**kwargs)
5,175
Python
.py
120
33.266667
117
0.578162
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,217
models.py
django-wiki_django-wiki/src/wiki/plugins/attachments/models.py
import os from django.conf import settings as django_settings from django.db import models from django.db.models import signals from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from wiki import managers from wiki.decorators import disable_signal_for_loaddata from wiki.models.article import BaseRevisionMixin from wiki.models.pluginbase import ReusablePlugin from . import settings class IllegalFileExtension(Exception): """File extension on upload is not allowed""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( "AttachmentRevision", verbose_name=_("current revision"), blank=True, null=True, related_name="current_set", on_delete=models.CASCADE, help_text=_( "The revision of this attachment currently in use (on all articles using the attachment)" ), ) original_filename = models.CharField( max_length=256, verbose_name=_("original filename"), blank=True, null=True, ) def can_write(self, user): if not settings.ANONYMOUS and (not user or user.is_anonymous): return False return ReusablePlugin.can_write(self, user) def can_delete(self, user): return self.can_write(user) class Meta: verbose_name = _("attachment") verbose_name_plural = _("attachments") # Matches label of upcoming 0.1 release db_table = "wiki_attachments_attachment" def __str__(self): from wiki.models import Article try: return "{}: {}".format( self.article.current_revision.title, self.original_filename, ) except Article.DoesNotExist: return "Attachment for non-existing article" def extension_allowed(filename): try: extension = filename.split(".")[-1] except IndexError: # No extension raise IllegalFileExtension( gettext("No file extension found in filename. That's not okay!") ) if extension.lower() not in map( lambda x: x.lower(), settings.FILE_EXTENSIONS ): raise IllegalFileExtension( gettext( "The following filename is illegal: {filename:s}. Extension " "has to be one of {extensions:s}" ).format( filename=filename, extensions=", ".join(settings.FILE_EXTENSIONS), ) ) return extension def upload_path(instance, filename): extension = extension_allowed(filename) # Has to match original extension filename if ( instance.id and instance.attachment and instance.attachment.original_filename ): original_extension = instance.attachment.original_filename.split(".")[ -1 ] if not extension.lower() == original_extension: raise IllegalFileExtension( "File extension has to be '%s', not '%s'." % (original_extension, extension.lower()) ) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace( "%aid", str(instance.attachment.article.id) ) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5( str(random.randint(0, 100000000000000)).encode("ascii") ) upload_path = os.path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += ".upload" return os.path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey("Attachment", on_delete=models.CASCADE) file = models.FileField( upload_to=upload_path, # @ReservedAssignment max_length=255, verbose_name=_("file"), storage=settings.STORAGE_BACKEND, ) description = models.TextField(blank=True) class Meta: verbose_name = _("attachment revision") verbose_name_plural = _("attachment revisions") ordering = ("created",) get_latest_by = "revision_number" # Matches label of upcoming 0.1 release db_table = "wiki_attachments_attachmentrevision" def get_filename(self): """Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent.""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split("/")[-1] return ".".join(filename.split(".")[:-1]) def get_size(self): """Used to retrieve the file size and not cause exceptions.""" try: return self.file.size except (ValueError, OSError): return None def __str__(self): return "%s: %s (r%d)" % ( self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number, ) @disable_signal_for_loaddata def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split("/")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. max_depth = 1 if len(path) != 0: if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 for depth in range(0, max_depth): delete_path = "/".join(path[:-depth] if depth > 0 else path) try: if ( len( os.listdir( os.path.join(django_settings.MEDIA_ROOT, delete_path) ) ) == 0 ): os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass @disable_signal_for_loaddata def on_attachment_revision_pre_save(**kwargs): instance = kwargs["instance"] if instance._state.adding: update_previous_revision = ( not instance.previous_revision and instance.attachment and instance.attachment.current_revision and instance.attachment.current_revision != instance ) if update_previous_revision: instance.previous_revision = instance.attachment.current_revision if not instance.revision_number: try: previous_revision = ( instance.attachment.attachmentrevision_set.latest() ) instance.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow # it does. except (AttachmentRevision.DoesNotExist, Attachment.DoesNotExist): instance.revision_number = 1 @disable_signal_for_loaddata def on_attachment_revision_post_save(**kwargs): instance = kwargs["instance"] if not instance.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is # me! instance.attachment.current_revision = instance instance.attachment.save() signals.pre_delete.connect(on_revision_delete, AttachmentRevision) signals.pre_save.connect(on_attachment_revision_pre_save, AttachmentRevision) signals.post_save.connect(on_attachment_revision_post_save, AttachmentRevision)
7,816
Python
.py
205
29.473171
101
0.638382
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,218
settings.py
django-wiki_django-wiki/src/wiki/plugins/attachments/settings.py
from django.conf import settings as django_settings from django.core.exceptions import ImproperlyConfigured from wiki.conf import settings as wiki_settings # Deprecated APP_LABEL = None SLUG = "attachments" # Please see this note about support for UTF-8 files on django/apache: # https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/modwsgi/#if-you-get-a-unicodeencodeerror #: Allow anonymous users upload access (not nice on an open network) #: ``WIKI_ATTACHMENTS_ANONYMOUS`` can override this, otherwise the default #: in ``wiki.conf.settings`` is used. ANONYMOUS = getattr( django_settings, "WIKI_ATTACHMENTS_ANONYMOUS", wiki_settings.ANONYMOUS_UPLOAD, ) # Maximum file sizes: Please use something like LimitRequestBody on # your web server. # http://httpd.apache.org/docs/2.2/mod/core.html#LimitRequestBody #: Where to store article attachments, relative to ``MEDIA_ROOT``. #: You should NEVER enable directory indexing in ``MEDIA_ROOT/UPLOAD_PATH``! #: Actually, you can completely disable serving it, if you want. Files are #: sent to the user through a Django view that reads and streams a file. UPLOAD_PATH = getattr( django_settings, "WIKI_ATTACHMENTS_PATH", "wiki/attachments/%aid/" ) #: Should the upload path be obscurified? If so, a random hash will be #: added to the path such that someone can not guess the location of files #: (if you have restricted permissions and the files are still located #: within the web server's file system). UPLOAD_PATH_OBSCURIFY = getattr( django_settings, "WIKI_ATTACHMENTS_PATH_OBSCURIFY", True ) #: Allowed extensions for attachments, empty to disallow uploads completely. #: If ``WIKI_ATTACHMENTS_APPEND_EXTENSION`` files are saved with an appended #: ".upload" to the file to ensure that your web server never actually executes #: some script. The extensions are case insensitive. #: You are asked to explicitly enter all file extensions that you want #: to allow. For your own safety. #: Note: this setting is called WIKI_ATTACHMENTS_EXTENSIONS not WIKI_ATTACHMENTS_FILE_EXTENTIONS FILE_EXTENSIONS = getattr( django_settings, "WIKI_ATTACHMENTS_EXTENSIONS", ["pdf", "doc", "odt", "docx", "txt"], ) #: Storage backend to use, default is to use the same as the rest of the #: wiki, which is set in ``WIKI_STORAGE_BACKEND``, but you can override it #: with ``WIKI_ATTACHMENTS_STORAGE_BACKEND``. STORAGE_BACKEND = getattr( django_settings, "WIKI_ATTACHMENTS_STORAGE_BACKEND", wiki_settings.STORAGE_BACKEND, ) #: Store files always with an appended .upload extension to be sure that #: something nasty does not get executed on the server. SAFETY FIRST! APPEND_EXTENSION = getattr( django_settings, "WIKI_ATTACHMENTS_APPEND_EXTENSION", True ) #: Important for e.g. S3 backends: If your storage backend does not have a .path #: attribute for the file, but only a .url attribute, you should use False. #: This will reveal the direct download URL so it does not work perfectly for #: files you wish to be kept private. USE_LOCAL_PATH = getattr(django_settings, "WIKI_ATTACHMENTS_LOCAL_PATH", True) if (not USE_LOCAL_PATH) and APPEND_EXTENSION: raise ImproperlyConfigured( "django-wiki (attachment plugin) not USE_LOCAL_PATH and APPEND_EXTENSION: " "You have configured to append .upload and not use local paths. That won't " "work as all your attachments will be stored and sent with a .upload " "extension. You have to trust your storage backend to be safe for storing" "the extensions you have allowed." )
3,565
Python
.py
71
47.690141
102
0.761631
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,219
markdown_extensions.py
django-wiki_django-wiki/src/wiki/plugins/attachments/markdown_extensions.py
import re import markdown from django.contrib.auth.models import AnonymousUser from django.template.loader import render_to_string from django.urls import reverse from wiki.core.markdown import add_to_registry from wiki.core.permissions import can_read from wiki.plugins.attachments import models ATTACHMENT_RE = re.compile( r"(?P<before>.*)\[( *((attachment\:(?P<id>[0-9]+))|(title\:\"(?P<title>[^\"]+)\")|(?P<size>size)))+\](?P<after>.*)", re.IGNORECASE, ) class AttachmentExtension(markdown.Extension): """Abbreviation Extension for Python-Markdown.""" def extendMarkdown(self, md): """Insert AbbrPreprocessor before ReferencePreprocessor.""" add_to_registry( md.preprocessors, "dw-attachments", AttachmentPreprocessor(md), ">html_block", ) class AttachmentPreprocessor(markdown.preprocessors.Preprocessor): """django-wiki attachment preprocessor - parse text for [attachment:id] references.""" def run(self, lines): new_text = [] for line in lines: m = ATTACHMENT_RE.match(line) if not m: new_text.append(line) continue attachment_id = m.group("id").strip() title = m.group("title") size = m.group("size") before = self.run([m.group("before")])[0] after = self.run([m.group("after")])[0] try: attachment = models.Attachment.objects.get( articles__current_revision__deleted=False, id=attachment_id, current_revision__deleted=False, articles=self.md.article, ) url = reverse( "wiki:attachments_download", kwargs={ "article_id": self.md.article.id, "attachment_id": attachment.id, }, ) # The readability of the attachment is decided relative # to the owner of the original article. # I.e. do not insert attachments in other articles that # the original uploader cannot read, that would be out # of scope! article_owner = attachment.article.owner if not article_owner: article_owner = AnonymousUser() if not title: title = attachment.original_filename if size: size = attachment.current_revision.get_size() attachment_can_read = can_read(self.md.article, article_owner) html = render_to_string( "wiki/plugins/attachments/render.html", context={ "url": url, "filename": attachment.original_filename, "title": title, "size": size, "attachment_can_read": attachment_can_read, }, ) line = self.md.htmlStash.store(html) except models.Attachment.DoesNotExist: html = ( """<span class="attachment attachment-deleted">Attachment with ID """ """#{} is deleted.</span>""" ).format(attachment_id) line = line.replace( "[" + m.group(2) + "]", self.md.htmlStash.store(html) ) new_text.append(before + line + after) return new_text
3,628
Python
.py
84
28.97619
120
0.528045
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,220
urls.py
django-wiki_django-wiki/src/wiki/plugins/attachments/urls.py
from django.urls import re_path from wiki.plugins.attachments import views urlpatterns = [ re_path(r"^$", views.AttachmentView.as_view(), name="attachments_index"), re_path( r"^search/$", views.AttachmentSearchView.as_view(), name="attachments_search", ), re_path( r"^add/(?P<attachment_id>[0-9]+)/$", views.AttachmentAddView.as_view(), name="attachments_add", ), re_path( r"^replace/(?P<attachment_id>[0-9]+)/$", views.AttachmentReplaceView.as_view(), name="attachments_replace", ), re_path( r"^history/(?P<attachment_id>[0-9]+)/$", views.AttachmentHistoryView.as_view(), name="attachments_history", ), re_path( r"^download/(?P<attachment_id>[0-9]+)/$", views.AttachmentDownloadView.as_view(), name="attachments_download", ), re_path( r"^delete/(?P<attachment_id>[0-9]+)/$", views.AttachmentDeleteView.as_view(), name="attachments_delete", ), re_path( r"^download/(?P<attachment_id>[0-9]+)/revision/(?P<revision_id>[0-9]+)/$", views.AttachmentDownloadView.as_view(), name="attachments_download", ), re_path( r"^change/(?P<attachment_id>[0-9]+)/revision/(?P<revision_id>[0-9]+)/$", views.AttachmentChangeRevisionView.as_view(), name="attachments_revision_change", ), ]
1,430
Python
.py
45
24.977778
82
0.59104
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,221
apps.py
django-wiki_django-wiki/src/wiki/plugins/attachments/apps.py
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class AttachmentsConfig(AppConfig): name = "wiki.plugins.attachments" verbose_name = _("Wiki attachments") label = "wiki_attachments"
237
Python
.py
6
36.166667
54
0.772926
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,222
wiki_plugin.py
django-wiki_django-wiki/src/wiki/plugins/attachments/wiki_plugin.py
from django.urls import include from django.urls import re_path from django.utils.translation import gettext as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from wiki.plugins.attachments import models from wiki.plugins.attachments import settings from wiki.plugins.attachments import views from wiki.plugins.attachments.markdown_extensions import AttachmentExtension from wiki.plugins.notifications.settings import ARTICLE_EDIT from wiki.plugins.notifications.util import truncate_title class AttachmentPlugin(BasePlugin): slug = settings.SLUG urlpatterns = { "article": [re_path("", include("wiki.plugins.attachments.urls"))] } article_tab = (_("Attachments"), "fa fa-file") article_view = views.AttachmentView().dispatch # List of notifications to construct signal handlers for. This # is handled inside the notifications plugin. notifications = [ { "model": models.AttachmentRevision, "message": lambda obj: ( _("A file was changed: %s") if not obj.deleted else _("A file was deleted: %s") ) % truncate_title(obj.get_filename()), "key": ARTICLE_EDIT, "created": True, "get_article": lambda obj: obj.attachment.article, } ] markdown_extensions = [AttachmentExtension()] registry.register(AttachmentPlugin)
1,453
Python
.py
36
33.722222
76
0.696454
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,223
admin.py
django-wiki_django-wiki/src/wiki/plugins/attachments/admin.py
from django.contrib import admin from . import models class AttachmentRevisionAdmin(admin.TabularInline): model = models.AttachmentRevision extra = 1 fields = ("file", "user", "user_message") class AttachmentAdmin(admin.ModelAdmin): inlines = [AttachmentRevisionAdmin] admin.site.register(models.Attachment, AttachmentAdmin)
348
Python
.py
9
35.111111
55
0.792169
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,224
forms.py
django-wiki_django-wiki/src/wiki/plugins/attachments/forms.py
import tempfile import zipfile from django import forms from django.core.files.uploadedfile import File from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from wiki.core.permissions import can_moderate from wiki.plugins.attachments import models from wiki.plugins.attachments.models import IllegalFileExtension class AttachmentForm(forms.ModelForm): description = forms.CharField( label=_("Description"), help_text=_("A short summary of what the file contains"), required=False, ) def __init__(self, *args, **kwargs): self.article = kwargs.pop("article", None) self.request = kwargs.pop("request", None) self.attachment = kwargs.pop("attachment", None) super().__init__(*args, **kwargs) def clean_file(self): uploaded_file = self.cleaned_data.get("file", None) if uploaded_file: try: models.extension_allowed(uploaded_file.name) except IllegalFileExtension as e: raise forms.ValidationError(e) return uploaded_file def save(self, *args, **kwargs): commit = kwargs.get("commit", True) attachment_revision = super().save(commit=False) # Added because of AttachmentArchiveForm removing file from fields # should be more elegant attachment_revision.file = self.cleaned_data["file"] if not self.attachment: attachment = models.Attachment() attachment.article = self.article attachment.original_filename = attachment_revision.get_filename() if commit: attachment.save() attachment.articles.add(self.article) else: attachment = self.attachment attachment_revision.attachment = attachment attachment_revision.set_from_request(self.request) if commit: attachment_revision.save() return attachment_revision class Meta: model = models.AttachmentRevision fields = ( "file", "description", ) class AttachmentReplaceForm(AttachmentForm): replace = forms.BooleanField( label=_("Remove previous"), help_text=_( "Remove previous attachment revisions and their files (to " "save space)?" ), required=False, ) class AttachmentArchiveForm(AttachmentForm): file = forms.FileField( # @ReservedAssignment label=_("File or zip archive"), required=True ) unzip_archive = forms.BooleanField( label=_("Unzip file"), help_text=_( "Create individual attachments for files in a .zip file - directories do not work." ), required=False, ) def clean_file(self): uploaded_file = self.cleaned_data.get("file", None) if uploaded_file and self.cleaned_data.get("unzip_archive", False): try: self.zipfile = zipfile.ZipFile(uploaded_file.file, mode="r") for zipinfo in self.zipfile.filelist: try: models.extension_allowed(zipinfo.filename) except IllegalFileExtension as e: raise forms.ValidationError(e) except zipfile.BadZipfile: raise forms.ValidationError(gettext("Not a zip file")) else: return super().clean_file() return uploaded_file def clean(self): super().clean() if not can_moderate(self.article, self.request.user): raise forms.ValidationError( gettext("User not allowed to moderate this article") ) return self.cleaned_data def save(self, *args, **kwargs): # This is not having the intended effect if "file" not in self._meta.fields: self._meta.fields.append("file") if self.cleaned_data["unzip_archive"]: new_attachments = [] try: uploaded_file = self.cleaned_data.get("file", None) self.zipfile = zipfile.ZipFile(uploaded_file.file, mode="r") for zipinfo in self.zipfile.filelist: f = tempfile.NamedTemporaryFile(mode="w+b") f.write(self.zipfile.read(zipinfo.filename)) f = File(f, name=zipinfo.filename) try: attachment = models.Attachment() attachment.article = self.article attachment.original_filename = zipinfo.filename attachment.save() attachment.articles.add(self.article) attachment_revision = models.AttachmentRevision() attachment_revision.file = f attachment_revision.description = self.cleaned_data[ "description" ] attachment_revision.attachment = attachment attachment_revision.set_from_request(self.request) attachment_revision.save() f.close() except models.IllegalFileExtension: raise new_attachments.append(attachment_revision) except zipfile.BadZipfile: raise return new_attachments else: return super().save(*args, **kwargs) class Meta(AttachmentForm.Meta): fields = [ "description", ] class DeleteForm(forms.Form): """This form is both used for dereferencing and deleting attachments""" confirm = forms.BooleanField(label=_("Yes I am sure..."), required=False) def clean_confirm(self): if not self.cleaned_data["confirm"]: raise forms.ValidationError(gettext("You are not sure enough!")) return True class SearchForm(forms.Form): query = forms.CharField( label="", widget=forms.TextInput(attrs={"class": "search-query form-control"}), )
6,166
Python
.py
148
29.986486
95
0.595429
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,225
views.py
django-wiki_django-wiki/src/wiki/plugins/attachments/views.py
from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from django.http import Http404 from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.utils.translation import gettext as _ from django.views.generic import FormView from django.views.generic import ListView from django.views.generic import TemplateView from django.views.generic import View from wiki.core.http import send_file from wiki.core.paginator import WikiPaginator from wiki.decorators import get_article from wiki.decorators import response_forbidden from wiki.plugins.attachments import forms from wiki.plugins.attachments import models from wiki.plugins.attachments import settings from wiki.views.mixins import ArticleMixin class AttachmentView(ArticleMixin, FormView): form_class = forms.AttachmentForm template_name = "wiki/plugins/attachments/index.html" @method_decorator(get_article(can_read=True)) def dispatch(self, request, article, *args, **kwargs): if article.can_moderate(request.user): self.attachments = ( models.Attachment.objects.filter( articles=article, current_revision__deleted=False ) .exclude(current_revision__file=None) .order_by("original_filename") ) self.form_class = forms.AttachmentArchiveForm else: self.attachments = models.Attachment.objects.active().filter( articles=article ) # Fixing some weird transaction issue caused by adding commit_manually # to form_valid return super().dispatch(request, article, *args, **kwargs) def form_valid(self, form): if ( self.request.user.is_anonymous and not settings.ANONYMOUS or not self.article.can_write(self.request.user) or self.article.current_revision.locked ): return response_forbidden(self.request, self.article, self.urlpath) attachment_revision = form.save() if isinstance(attachment_revision, list): messages.success( self.request, _("Successfully added: %s") % ( ", ".join( [ar.get_filename() for ar in attachment_revision] ) ), ) else: messages.success( self.request, _("%s was successfully added.") % attachment_revision.get_filename(), ) self.article.clear_cache() return redirect( "wiki:attachments_index", path=self.urlpath.path, article_id=self.article.id, ) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["article"] = self.article kwargs["request"] = self.request return kwargs def get_context_data(self, **kwargs): # Needed since Django 1.9 because get_context_data is no longer called # with the form instance if "form" not in kwargs: kwargs["form"] = self.get_form() kwargs["attachments"] = self.attachments kwargs["deleted_attachments"] = models.Attachment.objects.filter( articles=self.article, current_revision__deleted=True ) kwargs["search_form"] = forms.SearchForm() kwargs["selected_tab"] = "attachments" kwargs["anonymous_disallowed"] = ( self.request.user.is_anonymous and not settings.ANONYMOUS ) return super().get_context_data(**kwargs) class AttachmentHistoryView(ArticleMixin, TemplateView): template_name = "wiki/plugins/attachments/history.html" @method_decorator(get_article(can_read=True)) def dispatch(self, request, article, attachment_id, *args, **kwargs): if article.can_moderate(request.user): self.attachment = get_object_or_404( models.Attachment, id=attachment_id, articles=article ) else: self.attachment = get_object_or_404( models.Attachment.objects.active(), id=attachment_id, articles=article, ) return super().dispatch(request, article, *args, **kwargs) def get_context_data(self, **kwargs): kwargs["attachment"] = self.attachment kwargs[ "revisions" ] = self.attachment.attachmentrevision_set.all().order_by( "-revision_number" ) kwargs["selected_tab"] = "attachments" return super().get_context_data(**kwargs) class AttachmentReplaceView(ArticleMixin, FormView): form_class = forms.AttachmentForm template_name = "wiki/plugins/attachments/replace.html" @method_decorator(get_article(can_write=True, not_locked=True)) def dispatch(self, request, article, attachment_id, *args, **kwargs): if request.user.is_anonymous and not settings.ANONYMOUS: return response_forbidden( request, article, kwargs.get("urlpath", None) ) if article.can_moderate(request.user): self.attachment = get_object_or_404( models.Attachment, id=attachment_id, articles=article ) self.can_moderate = True else: self.attachment = get_object_or_404( models.Attachment.objects.active(), id=attachment_id, articles=article, ) self.can_moderate = False return super().dispatch(request, article, *args, **kwargs) def get_form_class(self): if self.can_moderate: return forms.AttachmentReplaceForm else: return forms.AttachmentForm def form_valid(self, form): try: attachment_revision = form.save(commit=True) attachment_revision.set_from_request(self.request) attachment_revision.previous_revision = ( self.attachment.current_revision ) attachment_revision.save() self.attachment.current_revision = attachment_revision self.attachment.save() messages.success( self.request, _("%s uploaded and replaces old attachment.") % attachment_revision.get_filename(), ) self.article.clear_cache() except models.IllegalFileExtension as e: messages.error( self.request, _("Your file could not be saved: %s") % e ) return redirect( "wiki:attachments_replace", attachment_id=self.attachment.id, path=self.urlpath.path, article_id=self.article.id, ) if self.can_moderate: if form.cleaned_data["replace"]: # form has no cleaned_data field unless self.can_moderate is True try: most_recent_revision = ( self.attachment.attachmentrevision_set.exclude( id=attachment_revision.id, created__lte=attachment_revision.created, ).latest() ) most_recent_revision.delete() except ObjectDoesNotExist: msg = ( "{attachment} does not contain any revisions.".format( attachment=str(self.attachment.original_filename) ) ) messages.error(self.request, msg) return redirect( "wiki:attachments_index", path=self.urlpath.path, article_id=self.article.id, ) def get_form(self, form_class=None): form = super().get_form(form_class=form_class) form.fields["file"].help_text = _( "Your new file will automatically be renamed to match the file already present. Files with different extensions are not allowed." ) return form def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["article"] = self.article kwargs["request"] = self.request kwargs["attachment"] = self.attachment return kwargs def get_initial(self, **kwargs): return {"description": self.attachment.current_revision.description} def get_context_data(self, **kwargs): if "form" not in kwargs: kwargs["form"] = self.get_form() kwargs["attachment"] = self.attachment kwargs["selected_tab"] = "attachments" return super().get_context_data(**kwargs) class AttachmentDownloadView(ArticleMixin, View): @method_decorator(get_article(can_read=True)) def dispatch(self, request, article, attachment_id, *args, **kwargs): if article.can_moderate(request.user): self.attachment = get_object_or_404( models.Attachment, id=attachment_id, articles=article ) else: self.attachment = get_object_or_404( models.Attachment.objects.active(), id=attachment_id, articles=article, ) revision_id = kwargs.get("revision_id", None) if revision_id: self.revision = get_object_or_404( models.AttachmentRevision, id=revision_id, attachment__articles=article, ) else: self.revision = self.attachment.current_revision return super().dispatch(request, article, *args, **kwargs) def get(self, request, *args, **kwargs): if self.revision: if settings.USE_LOCAL_PATH: try: return send_file( request, self.revision.file.path, self.revision.created, self.attachment.original_filename, ) except OSError: pass else: return HttpResponseRedirect(self.revision.file.url) raise Http404 class AttachmentChangeRevisionView(ArticleMixin, View): form_class = forms.AttachmentForm template_name = "wiki/plugins/attachments/replace.html" @method_decorator(get_article(can_write=True, not_locked=True)) def dispatch( self, request, article, attachment_id, revision_id, *args, **kwargs ): if article.can_moderate(request.user): self.attachment = get_object_or_404( models.Attachment, id=attachment_id, articles=article ) else: self.attachment = get_object_or_404( models.Attachment.objects.active(), id=attachment_id, articles=article, ) self.revision = get_object_or_404( models.AttachmentRevision, id=revision_id, attachment__articles=article, ) return super().dispatch(request, article, *args, **kwargs) def post(self, request, *args, **kwargs): self.attachment.current_revision = self.revision self.attachment.save() self.article.clear_cache() messages.success( self.request, _("Current revision changed for %s.") % self.attachment.original_filename, ) return redirect( "wiki:attachments_index", path=self.urlpath.path, article_id=self.article.id, ) def get_context_data(self, **kwargs): kwargs["selected_tab"] = "attachments" if "form" not in kwargs: kwargs["form"] = self.get_form() return ArticleMixin.get_context_data(self, **kwargs) class AttachmentAddView(ArticleMixin, View): @method_decorator(get_article(can_write=True, not_locked=True)) def dispatch(self, request, article, attachment_id, *args, **kwargs): self.attachment = get_object_or_404( models.Attachment.objects.active().can_write(request.user), id=attachment_id, ) return super().dispatch(request, article, *args, **kwargs) def post(self, request, *args, **kwargs): if not self.attachment.articles.filter(id=self.article.id): self.attachment.articles.add(self.article) self.attachment.save() self.article.clear_cache() messages.success( self.request, _('Added a reference to "%(att)s" from "%(art)s".') % { "att": self.attachment.original_filename, "art": self.article.current_revision.title, }, ) else: messages.error( self.request, _('"%(att)s" is already referenced.') % {"att": self.attachment.original_filename}, ) return redirect( "wiki:attachments_index", path=self.urlpath.path, article_id=self.article.id, ) class AttachmentDeleteView(ArticleMixin, FormView): form_class = forms.DeleteForm template_name = "wiki/plugins/attachments/delete.html" @method_decorator(get_article(can_write=True, not_locked=True)) def dispatch(self, request, article, attachment_id, *args, **kwargs): self.attachment = get_object_or_404( models.Attachment, id=attachment_id, articles=article ) if not self.attachment.can_delete(request.user): return response_forbidden( request, article, kwargs.get("urlpath", None) ) return super().dispatch(request, article, *args, **kwargs) def form_valid(self, form): if self.attachment.article == self.article: revision = models.AttachmentRevision() revision.attachment = self.attachment revision.set_from_request(self.request) revision.deleted = True revision.file = ( self.attachment.current_revision.file if self.attachment.current_revision else None ) revision.description = ( self.attachment.current_revision.description if self.attachment.current_revision else "" ) revision.save() self.attachment.current_revision = revision self.attachment.save() self.article.clear_cache() messages.info( self.request, _("The file %s was deleted.") % self.attachment.original_filename, ) else: self.attachment.articles.remove(self.article) messages.info( self.request, _("This article is no longer related to the file %s.") % self.attachment.original_filename, ) self.article.clear_cache() return redirect( "wiki:get", path=self.urlpath.path, article_id=self.article.id ) def get_context_data(self, **kwargs): kwargs["attachment"] = self.attachment kwargs["selected_tab"] = "attachments" if "form" not in kwargs: kwargs["form"] = self.get_form() return super().get_context_data(**kwargs) class AttachmentSearchView(ArticleMixin, ListView): template_name = "wiki/plugins/attachments/search.html" allow_empty = True context_object_name = "attachments" paginator_class = WikiPaginator paginate_by = 10 @method_decorator(get_article(can_write=True)) def dispatch(self, request, article, *args, **kwargs): return super().dispatch(request, article, *args, **kwargs) def get_queryset(self): self.query = self.request.GET.get("query", None) if not self.query: qs = models.Attachment.objects.none() else: qs = models.Attachment.objects.active().can_read(self.request.user) qs = qs.filter( Q(original_filename__contains=self.query) | Q(current_revision__description__contains=self.query) | Q(article__current_revision__title__contains=self.query) ) return qs.order_by("original_filename") def get_context_data(self, **kwargs): # Is this a bit of a hack? Use better inheritance? kwargs_article = ArticleMixin.get_context_data(self, **kwargs) kwargs_listview = ListView.get_context_data(self, **kwargs) kwargs["search_form"] = forms.SearchForm(self.request.GET) kwargs["query"] = self.query kwargs.update(kwargs_article) kwargs.update(kwargs_listview) kwargs["selected_tab"] = "attachments" return kwargs
17,166
Python
.py
411
30.287105
141
0.595583
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,226
0001_initial.py
django-wiki_django-wiki/src/wiki/plugins/attachments/migrations/0001_initial.py
import django.db.models.deletion import wiki.plugins.attachments.models from django.conf import settings from django.db import migrations from django.db import models from django.db.models.fields import GenericIPAddressField as IPAddressField class Migration(migrations.Migration): dependencies = [ ("wiki", "0001_initial"), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name="Attachment", fields=[ ( "reusableplugin_ptr", models.OneToOneField( parent_link=True, serialize=False, primary_key=True, to="wiki.ReusablePlugin", auto_created=True, on_delete=models.CASCADE, ), ), ( "original_filename", models.CharField( max_length=256, verbose_name="original filename", blank=True, null=True, ), ), ], options={ "verbose_name": "attachment", "verbose_name_plural": "attachments", }, bases=("wiki.reusableplugin",), ), migrations.CreateModel( name="AttachmentRevision", fields=[ ( "id", models.AutoField( serialize=False, primary_key=True, verbose_name="ID", auto_created=True, ), ), ( "revision_number", models.IntegerField(verbose_name="revision number", editable=False), ), ("user_message", models.TextField(blank=True)), ("automatic_log", models.TextField(editable=False, blank=True)), ( "ip_address", IPAddressField( editable=False, verbose_name="IP address", blank=True, null=True ), ), ("modified", models.DateTimeField(auto_now=True)), ("created", models.DateTimeField(auto_now_add=True)), ("deleted", models.BooleanField(default=False, verbose_name="deleted")), ("locked", models.BooleanField(default=False, verbose_name="locked")), ( "file", models.FileField( max_length=255, verbose_name="file", upload_to=wiki.plugins.attachments.models.upload_path, ), ), ("description", models.TextField(blank=True)), ( "attachment", models.ForeignKey( to="wiki_attachments.Attachment", on_delete=models.CASCADE ), ), ( "previous_revision", models.ForeignKey( blank=True, on_delete=django.db.models.deletion.SET_NULL, to="wiki_attachments.AttachmentRevision", null=True, ), ), ( "user", models.ForeignKey( blank=True, verbose_name="user", on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, null=True, ), ), ], options={ "ordering": ("created",), "get_latest_by": "revision_number", "verbose_name": "attachment revision", "verbose_name_plural": "attachment revisions", }, bases=(models.Model,), ), migrations.AddField( model_name="attachment", name="current_revision", field=models.OneToOneField( to="wiki_attachments.AttachmentRevision", blank=True, verbose_name="current revision", related_name="current_set", help_text="The revision of this attachment currently in use (on all articles using the attachment)", null=True, on_delete=models.CASCADE, ), preserve_default=True, ), ]
4,838
Python
.py
128
20.484375
116
0.439014
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,227
0002_auto_20151118_1816.py
django-wiki_django-wiki/src/wiki/plugins/attachments/migrations/0002_auto_20151118_1816.py
from django.db import migrations class Migration(migrations.Migration): atomic = False dependencies = [ ("wiki_attachments", "0001_initial"), ] operations = [ migrations.AlterModelTable( name="attachment", table="wiki_attachments_attachment", ), migrations.AlterModelTable( name="attachmentrevision", table="wiki_attachments_attachmentrevision", ), ]
464
Python
.py
16
20.9375
56
0.61851
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,228
settings.py
django-wiki_django-wiki/src/wiki/conf/settings.py
import bleach from django.conf import settings as django_settings from django.contrib.messages import constants as messages from django.core.files.storage import default_storage from django.urls import reverse_lazy from django.utils.translation import gettext_lazy as _ #: Should urls be case sensitive? URL_CASE_SENSITIVE = getattr(django_settings, "WIKI_URL_CASE_SENSITIVE", False) # Non-configurable (at the moment) WIKI_LANGUAGE = "markdown" #: The editor class to use -- maybe a 3rd party or your own...? You can always #: extend the built-in editor and customize it! EDITOR = getattr( django_settings, "WIKI_EDITOR", "wiki.editors.markitup.MarkItUp" ) #: Whether to use Bleach or not. It's not recommended to turn this off unless #: you know what you're doing and you don't want to use the other options. MARKDOWN_SANITIZE_HTML = getattr( django_settings, "WIKI_MARKDOWN_SANITIZE_HTML", True ) #: Arguments for the Markdown instance, as a dictionary. The "extensions" key #: should be a list of extra extensions to use besides the built-in django-wiki #: extensions, and the "extension_configs" should be a dictionary, specifying #: the keyword-arguments to pass to each extension. #: #: For a list of extensions officially supported by Python-Markdown, see: #: https://python-markdown.github.io/extensions/ #: #: To set a custom title for table of contents, specify the following in your #: Django project settings:: #: #: WIKI_MARKDOWN_KWARGS = { #: 'extension_configs': { #: 'wiki.plugins.macros.mdx.toc': {'title': 'Contents of this article'}, #: }, #: } #: #: Besides the extensions enabled by the "extensions" key, the following #: built-in django-wiki extensions can be configured with "extension_configs": #: "wiki.core.markdown.mdx.codehilite", "wiki.core.markdown.mdx.previewlinks", #: "wiki.core.markdown.mdx.responsivetable", "wiki.plugins.macros.mdx.macro", #: "wiki.plugins.macros.mdx.toc", "wiki.plugins.macros.mdx.wikilinks". MARKDOWN_KWARGS = { "extensions": [ "markdown.extensions.footnotes", "markdown.extensions.attr_list", "markdown.extensions.footnotes", "markdown.extensions.attr_list", "markdown.extensions.def_list", "markdown.extensions.tables", "markdown.extensions.abbr", "markdown.extensions.sane_lists", ], "extension_configs": { "wiki.plugins.macros.mdx.toc": {"title": _("Contents")} }, } MARKDOWN_KWARGS.update(getattr(django_settings, "WIKI_MARKDOWN_KWARGS", {})) _default_tag_whitelists = bleach.ALLOWED_TAGS.union( { "figure", "figcaption", "br", "hr", "p", "div", "img", "pre", "span", "sup", "table", "thead", "tbody", "th", "tr", "td", "dl", "dt", "dd", } ).union({f"h{n}" for n in range(1, 7)}) #: List of allowed tags in Markdown article contents. MARKDOWN_HTML_WHITELIST = _default_tag_whitelists MARKDOWN_HTML_WHITELIST = MARKDOWN_HTML_WHITELIST.union( getattr(django_settings, "WIKI_MARKDOWN_HTML_WHITELIST", frozenset()) ) _default_attribute_whitelist = bleach.ALLOWED_ATTRIBUTES for tag in MARKDOWN_HTML_WHITELIST: if tag not in _default_attribute_whitelist: _default_attribute_whitelist[tag] = [] _default_attribute_whitelist[tag].append("class") _default_attribute_whitelist[tag].append("id") _default_attribute_whitelist[tag].append("target") _default_attribute_whitelist[tag].append("rel") _default_attribute_whitelist["img"].append("src") _default_attribute_whitelist["img"].append("alt") _default_attribute_whitelist["td"].append("align") #: Dictionary of allowed attributes in Markdown article contents. MARKDOWN_HTML_ATTRIBUTES = _default_attribute_whitelist MARKDOWN_HTML_ATTRIBUTES.update( getattr(django_settings, "WIKI_MARKDOWN_HTML_ATTRIBUTES", {}) ) #: Allowed inline styles in Markdown article contents, default is no styles #: (empty list). MARKDOWN_HTML_STYLES = getattr( django_settings, "WIKI_MARKDOWN_HTML_STYLES", [] ) _project_defined_attrs = getattr( django_settings, "WIKI_MARKDOWN_HTML_ATTRIBUTE_WHITELIST", False ) # If styles are allowed but no custom attributes are defined, we allow styles # for all kinds of tags. if MARKDOWN_HTML_STYLES and not _project_defined_attrs: MARKDOWN_HTML_ATTRIBUTES["*"] = "style" #: This slug is used in URLPath if an article has been deleted. The children of the #: URLPath of that article are moved to lost and found. They keep their permissions #: and all their content. LOST_AND_FOUND_SLUG = getattr( django_settings, "WIKI_LOST_AND_FOUND_SLUG", "lost-and-found" ) #: When True, this blocks new slugs that resolve to non-wiki views, stopping #: users creating articles that conflict with overlapping URLs from other apps. CHECK_SLUG_URL_AVAILABLE = getattr( django_settings, "WIKI_CHECK_SLUG_URL_AVAILABLE", True ) #: Do we want to log IPs of anonymous users? LOG_IPS_ANONYMOUS = getattr(django_settings, "WIKI_LOG_IPS_ANONYMOUS", True) #: Do we want to log IPs of logged in users? LOG_IPS_USERS = getattr(django_settings, "WIKI_LOG_IPS_USERS", False) #: Mapping from message.level to bootstrap class names. MESSAGE_TAG_CSS_CLASS = getattr( django_settings, "WIKI_MESSAGE_TAG_CSS_CLASS", { messages.DEBUG: "alert alert-info", messages.ERROR: "alert alert-danger", messages.INFO: "alert alert-info", messages.SUCCESS: "alert alert-success", messages.WARNING: "alert alert-warning", }, ) #: Weather to append a trailing slash to rendered Wikilinks. Defaults to True WIKILINKS_TRAILING_SLASH = getattr( django_settings, "WIKI_WIKILINKS_TRAILING_SLASH", True ) #################################### # PERMISSIONS AND ACCOUNT HANDLING # #################################### # NB! None of these callables need to handle anonymous users as they are treated # in separate settings... #: A function returning True/False if a user has permission to #: read contents of an article and plugins. #: Relevance: Viewing articles and plugins. CAN_READ = getattr(django_settings, "WIKI_CAN_READ", None) #: A function returning True/False if a user has permission to #: change contents, i.e. add new revisions to an article. #: Often, plugins also use this. #: Relevance: Editing articles, changing revisions, editing plugins. CAN_WRITE = getattr(django_settings, "WIKI_CAN_WRITE", None) #: A function returning True/False if a user has permission to assign #: permissions on an article. #: Relevance: Changing owner and group membership. CAN_ASSIGN = getattr(django_settings, "WIKI_CAN_ASSIGN", None) #: A function returning True/False if the owner of an article has permission #: to change the group to a user's own groups. #: Relevance: Changing group membership. CAN_ASSIGN_OWNER = getattr(django_settings, "WIKI_ASSIGN_OWNER", None) #: A function returning True/False if a user has permission to change #: read/write access for groups and others. CAN_CHANGE_PERMISSIONS = getattr( django_settings, "WIKI_CAN_CHANGE_PERMISSIONS", None ) #: Specifies if a user has access to soft deletion of articles. CAN_DELETE = getattr(django_settings, "WIKI_CAN_DELETE", None) #: A function returning True/False if a user has permission to change #: moderate, ie. lock articles and permanently delete content. CAN_MODERATE = getattr(django_settings, "WIKI_CAN_MODERATE", None) #: A function returning True/False if a user has permission to create #: new groups and users for the wiki. CAN_ADMIN = getattr(django_settings, "WIKI_CAN_ADMIN", None) #: Treat anonymous (i.e. non logged in) users as the "other" user group. ANONYMOUS = getattr(django_settings, "WIKI_ANONYMOUS", True) #: Globally enable write access for anonymous users, if true anonymous users #: will be treated as the others_write boolean field on models.Article. ANONYMOUS_WRITE = getattr(django_settings, "WIKI_ANONYMOUS_WRITE", False) #: Globally enable create access for anonymous users. #: Defaults to ``ANONYMOUS_WRITE``. ANONYMOUS_CREATE = getattr( django_settings, "WIKI_ANONYMOUS_CREATE", ANONYMOUS_WRITE ) #: Default setting to allow anonymous users upload access. Used in #: plugins.attachments and plugins.images, and can be overwritten in #: these plugins. ANONYMOUS_UPLOAD = getattr(django_settings, "WIKI_ANONYMOUS_UPLOAD", False) #: Sign up, login and logout views should be accessible. ACCOUNT_HANDLING = getattr(django_settings, "WIKI_ACCOUNT_HANDLING", True) #: Signup allowed? If it's not allowed, logged in superusers can still access #: the signup page to create new users. ACCOUNT_SIGNUP_ALLOWED = ACCOUNT_HANDLING and getattr( django_settings, "WIKI_ACCOUNT_SIGNUP_ALLOWED", True ) if ACCOUNT_HANDLING: LOGIN_URL = reverse_lazy("wiki:login") LOGOUT_URL = reverse_lazy("wiki:logout") SIGNUP_URL = reverse_lazy("wiki:signup") else: LOGIN_URL = getattr(django_settings, "LOGIN_URL", "/") LOGOUT_URL = getattr(django_settings, "LOGOUT_URL", "/") SIGNUP_URL = getattr(django_settings, "WIKI_SIGNUP_URL", "/") ################## # OTHER SETTINGS # ################## #: Maximum amount of children to display in a menu before showing "+more". #: NEVER set this to 0 as it will wrongly inform the user that there are no #: children and for instance that an article can be safely deleted. SHOW_MAX_CHILDREN = getattr(django_settings, "WIKI_SHOW_MAX_CHILDREN", 20) #: User Bootstrap's select widget. Switch off if you're not using Bootstrap! USE_BOOTSTRAP_SELECT_WIDGET = getattr( django_settings, "WIKI_USE_BOOTSTRAP_SELECT_WIDGET", True ) #: Dotted name of the class used to construct urlpatterns for the wiki. #: Default is wiki.urls.WikiURLPatterns. To customize urls or view handlers, #: you can derive from this. URL_CONFIG_CLASS = getattr(django_settings, "WIKI_URL_CONFIG_CLASS", None) #: Seconds of timeout before renewing the article cache. Articles are automatically #: renewed whenever an edit occurs but article content may be generated from #: other objects that are changed. CACHE_TIMEOUT = getattr(django_settings, "WIKI_CACHE_TIMEOUT", 600) #: Choose the Group model to use for permission handling. Defaults to django's auth.Group. GROUP_MODEL = getattr(django_settings, "WIKI_GROUP_MODEL", "auth.Group") ################### # SPAM PROTECTION # ################### #: Maximum allowed revisions per hour for any given user or IP. REVISIONS_PER_HOUR = getattr(django_settings, "WIKI_REVISIONS_PER_HOUR", 60) #: Maximum allowed revisions per minute for any given user or IP. REVISIONS_PER_MINUTES = getattr( django_settings, "WIKI_REVISIONS_PER_MINUTES", 5 ) #: Maximum allowed revisions per hour for any anonymous user and any IP. REVISIONS_PER_HOUR_ANONYMOUS = getattr( django_settings, "WIKI_REVISIONS_PER_HOUR_ANONYMOUS", 10 ) #: Maximum allowed revisions per minute for any anonymous user and any IP. REVISIONS_PER_MINUTES_ANONYMOUS = getattr( django_settings, "WIKI_REVISIONS_PER_MINUTES_ANONYMOUS", 2 ) #: Number of minutes to look back for looking up ``REVISIONS_PER_MINUTES`` #: and ``REVISIONS_PER_MINUTES_ANONYMOUS``. REVISIONS_MINUTES_LOOKBACK = getattr( django_settings, "WIKI_REVISIONS_MINUTES_LOOKBACK", 2 ) ########### # STORAGE # ########### #: Default Django storage backend to use for images, attachments etc. STORAGE_BACKEND = getattr( django_settings, "WIKI_STORAGE_BACKEND", default_storage ) #: Use django-sendfile for sending out files? Otherwise the whole file is #: first read into memory and than send with a mime type based on the file. USE_SENDFILE = getattr(django_settings, "WIKI_ATTACHMENTS_USE_SENDFILE", False)
11,747
Python
.py
262
41.984733
90
0.732418
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,229
conf.py
django-wiki_django-wiki/docs/conf.py
import inspect import os import sys from datetime import datetime import bleach import django try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding import force_str as force_text # # django-wiki documentation build configuration file, created by # sphinx-quickstart on Mon Jul 23 16:13:51 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("../src")) sys.path.insert(0, os.path.abspath("../testproject")) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings.dev") django.setup() # Auto list fields from django models - from https://djangosnippets.org/snippets/2533/#c5977 def process_docstring(app, what, name, obj, options, lines): # This causes import errors if left outside the function from django.db import models # Only look at objects that inherit from Django's base model class if inspect.isclass(obj) and issubclass(obj, models.Model): # Grab the field list from the meta class fields = obj._meta.get_fields() for field in fields: # Skip ManyToOneRel and ManyToManyRel fields which have no 'verbose_name' or 'help_text' if not hasattr(field, "verbose_name"): continue # Decode and strip any html out of the field's help text help_text = bleach.clean(force_text(field.help_text), strip=True) # Decode and capitalize the verbose name, for use if there isn't # any help text verbose_name = force_text(field.verbose_name).capitalize() if help_text: # Add the model field to the end of the docstring as a param # using the help text as the description lines.append(f":param {field.attname}: {help_text}") else: # Add the model field to the end of the docstring as a param # using the verbose name as the description lines.append(f":param {field.attname}: {verbose_name}") # Add the field's type to the docstring if isinstance(field, models.ForeignKey): for to in field.to_fields: lines.append( ":type %s: %s to :class:`~%s`" % (field.attname, type(field).__name__, to) ) else: lines.append(f":type {field.attname}: {type(field).__name__}") return lines extlinks = { "url-issue": ( "https://github.com/django-wiki/django-wiki/issues/%s", "#%s", ), } def setup(app): # Register the docstring processor with sphinx app.connect("autodoc-process-docstring", process_docstring) # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.extlinks", "sphinx.ext.todo", "sphinx.ext.viewcode", # Fix: https://github.com/readthedocs/sphinx_rtd_theme/issues/1452 "sphinxcontrib.jquery", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "django-wiki" copyright = f"{datetime.now().year}, Benjamin Bach" # noqa path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) sys.path = [path] + sys.path sys.path = [os.path.join(path, "wiki")] + sys.path import wiki # noqa from wiki import __about__ # noqa # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(__about__.__version__.split(".")[0:100]) # The full version, including alpha/beta/rc tags. release = __about__.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] linkcheck_ignore = [ r"wiki.+", ] # -- Options for HTML output --------------------------------------------------- html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "django-wikidoc" # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ( "index", "django-wiki.tex", "django-wiki Documentation", "Benjamin Bach", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ("index", "django-wiki", "django-wiki Documentation", ["Benjamin Bach"], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "django-wiki", "django-wiki Documentation", "Benjamin Bach", "django-wiki", "Wiki engine for Django - with real data models!", "Miscellaneous", ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
11,326
Python
.py
262
39.496183
100
0.689687
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,230
settings.py
django-wiki_django-wiki/tests/settings.py
import os from django.urls import reverse_lazy TESTS_DATA_ROOT = os.path.dirname(__file__) MEDIA_ROOT = os.path.join(TESTS_DATA_ROOT, "media") DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}} DEBUG = True AUTH_USER_MODEL = "testdata.CustomUser" WIKI_GROUP_MODEL = "testdata.CustomGroup" SITE_ID = 1 ROOT_URLCONF = "tests.testdata.urls" INSTALLED_APPS = [ "tests.testdata", "django.contrib.auth.apps.AuthConfig", "django.contrib.contenttypes.apps.ContentTypesConfig", "django.contrib.sessions.apps.SessionsConfig", "django.contrib.admin.apps.AdminConfig", "django.contrib.humanize.apps.HumanizeConfig", "django.contrib.sites.apps.SitesConfig", "django.contrib.messages", "django_nyt.apps.DjangoNytConfig", "mptt", "sekizai", "sorl.thumbnail", "wiki.apps.WikiConfig", "wiki.plugins.attachments.apps.AttachmentsConfig", "wiki.plugins.editsection.apps.EditSectionConfig", "wiki.plugins.notifications.apps.NotificationsConfig", "wiki.plugins.images.apps.ImagesConfig", "wiki.plugins.macros.apps.MacrosConfig", "wiki.plugins.pymdown.apps.PyMdownConfig", "wiki.plugins.globalhistory.apps.GlobalHistoryConfig", "wiki.plugins.redlinks.apps.RedlinksConfig", ] MIDDLEWARE = [ "django.middleware.common.CommonMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", ] USE_TZ = True SECRET_KEY = "b^fv_)t39h%9p40)fnkfblo##jkr!$0)lkp6bpy!fi*f$4*92!" STATIC_URL = "/static/" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.contrib.auth.context_processors.auth", "django.template.context_processors.debug", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.request", "django.template.context_processors.static", "django.template.context_processors.tz", "django.contrib.messages.context_processors.messages", "sekizai.context_processors.sekizai", ] }, }, ] LOGIN_REDIRECT_URL = reverse_lazy("wiki:get", kwargs={"path": ""})
2,480
Python
.py
63
33.31746
70
0.69888
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,231
base.py
django-wiki_django-wiki/tests/base.py
import os import unittest import django_functest from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.template import Context from django.template import Template from django.test import override_settings from django.test import TestCase from django.urls import reverse from wiki.models import URLPath SUPERUSER1_USERNAME = "admin" SUPERUSER1_PASSWORD = "secret" NORMALUSER1_USERNAME = "normaluser" NORMALUSER1_PASSWORD = "secret" class RequireSuperuserMixin: def setUp(self): super().setUp() from django.contrib.auth import get_user_model User = get_user_model() self.superuser1 = User.objects.create_superuser( SUPERUSER1_USERNAME, "nobody@example.com", SUPERUSER1_PASSWORD ) class RequireBasicData(RequireSuperuserMixin): """ Mixin that creates common data required for all tests. """ def setUp(self): super().setUp() from django.contrib.auth import get_user_model User = get_user_model() self.normaluser1 = User.objects.create_user( NORMALUSER1_USERNAME, "nobody@example.com", NORMALUSER1_PASSWORD ) class TestBase(RequireBasicData, TestCase): pass class RequireRootArticleMixin: def setUp(self): super().setUp() self.root = URLPath.create_root() self.root_article = URLPath.root().article rev = self.root_article.current_revision rev.title = "Root Article" rev.content = "root article content" rev.save() class ArticleTestBase(RequireRootArticleMixin, TestBase): """ Sets up basic data for testing with an article and some revisions """ pass class DjangoClientTestBase(TestBase): def setUp(self): super().setUp() self.client.login( username=SUPERUSER1_USERNAME, password=SUPERUSER1_PASSWORD ) class WebTestCommonMixin(RequireBasicData, django_functest.ShortcutLoginMixin): """ Common setup required for WebTest and Selenium tests """ def setUp(self): super().setUp() self.shortcut_login( username=SUPERUSER1_USERNAME, password=SUPERUSER1_PASSWORD ) class WebTestBase( WebTestCommonMixin, django_functest.FuncWebTestMixin, TestCase ): pass INCLUDE_SELENIUM_TESTS = os.environ.get("INCLUDE_SELENIUM_TESTS", "0") == "1" @unittest.skipUnless(INCLUDE_SELENIUM_TESTS, "Skipping Selenium tests") class SeleniumBase( WebTestCommonMixin, django_functest.FuncSeleniumMixin, StaticLiveServerTestCase, ): driver_name = "Chrome" display = os.environ.get("SELENIUM_SHOW_BROWSER", "0") == "1" if not INCLUDE_SELENIUM_TESTS: # Don't call super() in setUpClass(), it will attempt to instantiate # a browser instance which is slow and might fail @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass class ArticleWebTestUtils: def get_by_path(self, path): """ Get the article response for the path. Example: self.get_by_path("Level1/Slug2/").title """ return self.client.get(reverse("wiki:get", kwargs={"path": path})) class TemplateTestCase(TestCase): @property def template(self): raise NotImplementedError("Subclasses must implement this") def render(self, context): return Template(self.template).render(Context(context)) # See # https://github.com/django-wiki/django-wiki/pull/382 class wiki_override_settings(override_settings): def enable(self): super().enable() self.reload_wiki_settings() def disable(self): super().disable() self.reload_wiki_settings() def reload_wiki_settings(self): from importlib import reload from wiki.conf import settings reload(settings)
3,904
Python
.py
112
28.625
79
0.700214
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,232
models.py
django-wiki_django-wiki/tests/testdata/models.py
from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): some_field = models.IntegerField(default=0) custom_groups = models.ManyToManyField( "CustomGroup", verbose_name="groups", blank=True, help_text=( "The groups this user belongs to. A user will get all permissions " "granted to each of their groups." ), related_name="user_set", related_query_name="user", ) class CustomGroup(models.Model): pass # user with invalid renamed identifier, and no email field class VeryCustomUser(AbstractBaseUser): identifier = models.IntegerField() USERNAME_FIELD = "identifier"
791
Python
.py
22
29.909091
79
0.708661
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,233
urls.py
django-wiki_django-wiki/tests/testdata/urls.py
from django.conf import settings from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include from django.urls import re_path urlpatterns = [ re_path(r"^admin/doc/", include("django.contrib.admindocs.urls")), re_path(r"^admin/", admin.site.urls), ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() urlpatterns += [ re_path( r"^media/(?P<path>.*)$", "django.views.static.serve", {"document_root": settings.MEDIA_ROOT}, ), ] urlpatterns += [ re_path(r"^django_functest/", include("django_functest.urls")), re_path(r"^notify/", include("django_nyt.urls")), re_path(r"", include("wiki.urls")), ]
762
Python
.py
23
28.347826
70
0.668478
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,234
0001_initial.py
django-wiki_django-wiki/tests/testdata/migrations/0001_initial.py
# Generated by Django 2.2.1 on 2019-07-03 19:03 import django.contrib.auth.models import django.contrib.auth.validators import django.utils.timezone from django.db import migrations from django.db import models class Migration(migrations.Migration): initial = True dependencies = [ ("auth", "0008_alter_user_username_max_length"), ] operations = [ migrations.CreateModel( name="CustomGroup", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], ), migrations.CreateModel( name="VeryCustomUser", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("password", models.CharField(max_length=128, verbose_name="password")), ( "last_login", models.DateTimeField( blank=True, null=True, verbose_name="last login" ), ), ("identifier", models.IntegerField()), ], options={ "abstract": False, }, ), migrations.CreateModel( name="CustomUser", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("password", models.CharField(max_length=128, verbose_name="password")), ( "last_login", models.DateTimeField( blank=True, null=True, verbose_name="last login" ), ), ( "is_superuser", models.BooleanField( default=False, help_text="Designates that this user has all permissions without explicitly assigning them.", verbose_name="superuser status", ), ), ( "username", models.CharField( error_messages={ "unique": "A user with that username already exists." }, help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.", max_length=150, unique=True, validators=[ django.contrib.auth.validators.UnicodeUsernameValidator() ], verbose_name="username", ), ), ( "first_name", models.CharField( blank=True, max_length=30, verbose_name="first name" ), ), ( "last_name", models.CharField( blank=True, max_length=150, verbose_name="last name" ), ), ( "email", models.EmailField( blank=True, max_length=254, verbose_name="email address" ), ), ( "is_staff", models.BooleanField( default=False, help_text="Designates whether the user can log into this admin site.", verbose_name="staff status", ), ), ( "is_active", models.BooleanField( default=True, help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.", verbose_name="active", ), ), ( "date_joined", models.DateTimeField( default=django.utils.timezone.now, verbose_name="date joined" ), ), ("some_field", models.IntegerField(default=0)), ( "groups", models.ManyToManyField( blank=True, help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.", related_name="user_set", related_query_name="user", to="auth.Group", verbose_name="groups", ), ), ( "user_permissions", models.ManyToManyField( blank=True, help_text="Specific permissions for this user.", related_name="user_set", related_query_name="user", to="auth.Permission", verbose_name="user permissions", ), ), ], options={ "verbose_name": "user", "verbose_name_plural": "users", "abstract": False, }, managers=[ ("objects", django.contrib.auth.models.UserManager()), ], ), ]
6,144
Python
.py
167
18.011976
138
0.38647
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,235
test_basic.py
django-wiki_django-wiki/tests/core/test_basic.py
import tempfile from datetime import datetime from django.test import TestCase from wiki.conf import settings as wiki_settings from wiki.core.http import send_file from wiki.forms import Group from wiki.models import Article from wiki.models import ArticleRevision from wiki.models import URLPath from ..base import wiki_override_settings from ..testdata.models import CustomGroup class URLPathTests(TestCase): def test_manager(self): root = URLPath.create_root() child = URLPath.create_urlpath(root, "child") self.assertIsNone(root.parent) self.assertEqual(list(root.children.all().active()), [child]) class CustomGroupTests(TestCase): @wiki_override_settings(WIKI_GROUP_MODEL="auth.Group") def test_setting(self): self.assertEqual(wiki_settings.GROUP_MODEL, "auth.Group") def test_custom(self): self.assertEqual(Group, CustomGroup) self.assertEqual(wiki_settings.GROUP_MODEL, "testdata.CustomGroup") class LineEndingsTests(TestCase): def test_manager(self): article = Article() article.add_revision( ArticleRevision(title="Root", content="Hello\nworld"), save=True ) self.assertEqual("Hello\r\nworld", article.current_revision.content) class HttpTests(TestCase): def test_send_file(self): fabricate_request = self.client.get("/").wsgi_request fobject = tempfile.NamedTemporaryFile("r") response = send_file( fabricate_request, fobject.name, filename="test.pdf" ) assert response.has_header("Content-Disposition") assert "inline" in response.get("Content-Disposition") response = send_file( fabricate_request, fobject.name, filename="test.jpeg" ) assert response.has_header("Content-Disposition") response = send_file( fabricate_request, fobject.name, filename="test.jpeg", last_modified=datetime.now(), ) assert response.has_header("Content-Disposition") fobject.close()
2,085
Python
.py
52
33.096154
76
0.695695
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,236
test_sites.py
django-wiki_django-wiki/tests/core/test_sites.py
from importlib import reload from django.contrib.sites.models import Site from django.test.testcases import TestCase from django.urls import include from django.urls import re_path from wiki import sites from wiki import urls from wiki.apps import WikiConfig from wiki.models import Article from wiki.models import URLPath from ..base import wiki_override_settings class WikiCustomSite(sites.WikiSite): def get_article_urls(self): urlpatterns = [ re_path( "^some-prefix/(?P<article_id>[0-9]+)/$", self.article_view, name="get", ), ] return urlpatterns def get_article_path_urls(self): urlpatterns = [ re_path( "^some-other-prefix/(?P<path>.+/|)$", self.article_view, name="get", ), ] return urlpatterns class WikiCustomConfig(WikiConfig): default_site = "tests.core.test_sites.WikiCustomSite" urlpatterns = [ re_path(r"^notify/", include("django_nyt.urls")), re_path(r"", include("wiki.urls")), ] @wiki_override_settings( INSTALLED_APPS=[ "tests.testdata", "django.contrib.auth.apps.AuthConfig", "django.contrib.contenttypes.apps.ContentTypesConfig", "django.contrib.sessions.apps.SessionsConfig", "django.contrib.admin.apps.AdminConfig", "django.contrib.humanize.apps.HumanizeConfig", "django.contrib.sites.apps.SitesConfig", "django_nyt.apps.DjangoNytConfig", "mptt", "sekizai", "sorl.thumbnail", "tests.core.test_sites.WikiCustomConfig", "wiki.plugins.attachments.apps.AttachmentsConfig", "wiki.plugins.notifications.apps.NotificationsConfig", "wiki.plugins.images.apps.ImagesConfig", "wiki.plugins.macros.apps.MacrosConfig", "wiki.plugins.globalhistory.apps.GlobalHistoryConfig", ], ROOT_URLCONF="tests.core.test_sites", ) class CustomWikiSiteTest(TestCase): def setUp(self): # Reload wiki.urls since it may have already been instantiated by another test app. self._old_site = sites.site sites.site = sites.DefaultWikiSite() reload(urls) def tearDown(self): sites.site = self._old_site reload(urls) def test_use_custom_wiki_site(self): self.assertEqual(sites.site.__class__.__name__, "WikiCustomSite") def test_get_absolute_url_if_urlpath_set_is_not_exists__no_root_urlconf( self ): a = Article.objects.create() self.assertEqual(a.get_absolute_url(), "/some-prefix/1/") def test_get_absolute_url_if_urlpath_set_is_exists__no_root_urlconf(self): a1 = Article.objects.create() s1 = Site.objects.create(domain="something.com", name="something.com") u1 = URLPath.objects.create(article=a1, site=s1) a2 = Article.objects.create() s2 = Site.objects.create( domain="somethingelse.com", name="somethingelse.com" ) URLPath.objects.create( article=a2, site=s2, parent=u1, slug="test_slug" ) self.assertEqual( a2.get_absolute_url(), "/some-other-prefix/test_slug/" )
3,258
Python
.py
88
29.227273
91
0.646574
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,237
test_paginator.py
django-wiki_django-wiki/tests/core/test_paginator.py
from django.test import TestCase from wiki.core.paginator import WikiPaginator class PaginatorTest(TestCase): """ Test the WikiPaginator and it's page_range() function """ def test_paginator(self): objects = [1] p = WikiPaginator(objects, 2, side_pages=2) self.assertEqual(p.num_pages, 1) p.page(1) self.assertEqual(p.page_range, [1]) objects = [1, 2, 3, 4, 5, 6, 7, 8, 9] p = WikiPaginator(objects, 2, side_pages=2) self.assertEqual(p.num_pages, 5) p.page(1) self.assertEqual(p.page_range, [1, 2, 3, 0, 5]) p.page(3) self.assertEqual(p.page_range, [1, 2, 3, 4, 5]) objects = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] p = WikiPaginator(objects, 2, side_pages=2) self.assertEqual(p.num_pages, 9) p.page(1) self.assertEqual(p.page_range, [1, 2, 3, 0, 9]) p.page(5) self.assertEqual(p.page_range, [1, 0, 3, 4, 5, 6, 7, 0, 9]) p.page(8) self.assertEqual(p.page_range, [1, 0, 6, 7, 8, 9])
1,097
Python
.py
28
31.214286
77
0.568053
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,238
test_accounts.py
django-wiki_django-wiki/tests/core/test_accounts.py
from django.conf import settings as django_settings from django.contrib import auth from django.contrib.auth import authenticate from django.contrib.auth.models import AnonymousUser from django.shortcuts import resolve_url from wiki.conf import settings as wiki_settings from wiki.models import reverse from ..base import ArticleWebTestUtils from ..base import DjangoClientTestBase from ..base import RequireRootArticleMixin from ..base import SUPERUSER1_PASSWORD from ..base import SUPERUSER1_USERNAME from ..base import TestBase from ..base import wiki_override_settings from ..testdata.models import CustomUser SIGNUP_TEST_USERNAME = "wiki" SIGNUP_TEST_PASSWORD = "wiki1234567" class AccountUpdateTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_password_change(self): """ Test that we can make a successful password change via the update form """ # Check out that it works as expected, notice that there is no referrer # on this GET request. self.client.get( resolve_url( "wiki:profile_update", ) ) # Now check that we don't succeed with unmatching passwords example_data = { "password1": "abcdef", "password2": "abcdef123", "email": self.superuser1.email, } # save a new revision response = self.client.post( resolve_url("wiki:profile_update"), example_data ) self.assertContains( response, "Passwords don", status_code=200 ) # Django 2/3 output different escaped versions of single quote in don't # Now check that we don't succeed with unmatching passwords example_data = { "password1": "abcdef", "password2": "abcdef", "email": self.superuser1.email, } # save a new revision response = self.client.post( resolve_url("wiki:profile_update"), example_data ) # Need to force str() because of: # TypeError: coercing to Unicode: need string or buffer, __proxy__ # found self.assertRedirects(response, str(django_settings.LOGIN_REDIRECT_URL)) self.assertEqual( self.superuser1, authenticate( username=self.superuser1.username, password=example_data["password1"], ), ) class UpdateProfileViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_update_profile(self): self.client.post( resolve_url("wiki:profile_update"), { "email": "test@test.com", "password1": "newPass", "password2": "newPass", }, follow=True, ) test_auth = authenticate(username="admin", password="newPass") self.assertIsNotNone(test_auth) self.assertEqual(test_auth.email, "test@test.com") @wiki_override_settings(ACCOUNT_HANDLING=True) class LogoutViewTests(RequireRootArticleMixin, DjangoClientTestBase): def test_logout_account_handling(self): self.client.get(wiki_settings.LOGOUT_URL) user = auth.get_user(self.client) self.assertIs(auth.get_user(self.client).is_authenticated, False) self.assertIsInstance(user, AnonymousUser) @wiki_override_settings(ACCOUNT_HANDLING=True) class LoginTestViews(RequireRootArticleMixin, TestBase): def test_already_signed_in(self): self.client.force_login(self.superuser1) response = self.client.get(wiki_settings.LOGIN_URL) self.assertRedirects(response, reverse("wiki:root")) def test_log_in(self): self.client.post( wiki_settings.LOGIN_URL, {"username": SUPERUSER1_USERNAME, "password": SUPERUSER1_PASSWORD}, ) self.assertIs(self.superuser1.is_authenticated, True) self.assertEqual(auth.get_user(self.client), self.superuser1) class SignupViewTests(RequireRootArticleMixin, TestBase): @wiki_override_settings(ACCOUNT_HANDLING=True, ACCOUNT_SIGNUP_ALLOWED=True) def test_signup(self): response = self.client.post( wiki_settings.SIGNUP_URL, data={ "password1": SIGNUP_TEST_PASSWORD, "password2": SIGNUP_TEST_PASSWORD, "username": SIGNUP_TEST_USERNAME, "email": "wiki@wiki.com", }, ) self.assertIs( CustomUser.objects.filter(email="wiki@wiki.com").exists(), True ) self.assertRedirects(response, reverse("wiki:login")) # Test that signing up the same user again gives a validation error # Regression test: https://github.com/django-wiki/django-wiki/issues/1152 response = self.client.post( wiki_settings.SIGNUP_URL, data={ "password1": SIGNUP_TEST_PASSWORD, "password2": SIGNUP_TEST_PASSWORD, "username": SIGNUP_TEST_USERNAME, "email": "wiki@wiki.com", }, ) self.assertIs(response.status_code, 200) self.assertContains(response, "username already exists")
5,272
Python
.py
130
31.561538
82
0.64876
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,239
test_utils.py
django-wiki_django-wiki/tests/core/test_utils.py
from django.test import TestCase from wiki.core.utils import object_to_json_response class TestUtils(TestCase): def test_object_to_json(self): """ Simple test, the actual serialization happens in json.dumps and we don't wanna test this core module in depth. """ obj = [] response = object_to_json_response(obj) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"[]")
467
Python
.py
12
32.083333
74
0.675497
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,240
test_template_tags.py
django-wiki_django-wiki/tests/core/test_template_tags.py
""" Almost all test cases covers both tag calling and template using. """ from django.conf import settings as django_settings from django.contrib.contenttypes.models import ContentType from django.http import HttpRequest from wiki.conf import settings from wiki.forms import CreateRootForm from wiki.models import Article from wiki.models import ArticleForObject from wiki.models import ArticleRevision from wiki.templatetags.wiki_tags import article_for_object from wiki.templatetags.wiki_tags import login_url from wiki.templatetags.wiki_tags import wiki_form from wiki.templatetags.wiki_tags import wiki_render from ..base import TemplateTestCase if not django_settings.configured: django_settings.configure() # XXX article_for_object accepts context, but not using it class ArticleForObjectTemplatetagTest(TemplateTestCase): template = """ {% load wiki_tags %} {% article_for_object obj as anything %} {{ anything }} """ def setUp(self): super().setUp() from wiki.templatetags import wiki_tags wiki_tags._cache = {} def test_obj_arg_is_not_a_django_model(self): from wiki.templatetags import wiki_tags with self.assertRaises(TypeError): article_for_object({}, "") with self.assertRaises(TypeError): article_for_object({"request": 100500}, {}) with self.assertRaises(TypeError): self.render({"obj": "tiger!"}) self.assertEqual(len(wiki_tags._cache), 0) def test_obj_is_not_in__cache_and_articleforobject_is_not_exist(self): from wiki.templatetags.wiki_tags import _cache as cache obj = Article.objects.create() article_for_object({}, obj) self.assertIn(obj, cache) self.assertIsNone(cache[obj]) self.assertEqual(len(cache), 1) self.render({"obj": obj}) self.assertIn(obj, cache) self.assertIsNone(cache[obj]) self.assertEqual(len(cache), 1) def test_obj_is_not_in__cache_and_articleforobjec_is_exist(self): from wiki.templatetags.wiki_tags import _cache as cache a = Article.objects.create() content_type = ContentType.objects.get_for_model(a) ArticleForObject.objects.create( article=a, content_type=content_type, object_id=1 ) output = article_for_object({}, a) self.assertEqual(output, a) self.assertIn(a, cache) self.assertEqual(cache[a], a) self.assertEqual(len(cache), 1) self.render({"obj": a}) self.assertIn(a, cache) self.assertEqual(cache[a], a) self.assertEqual(len(cache), 1) def test_obj_in__cache_and_articleforobject_is_not_exist(self): model = Article.objects.create() from wiki.templatetags import wiki_tags wiki_tags._cache = {model: "spam"} article_for_object({}, model) self.assertIn(model, wiki_tags._cache) self.assertIsNone(wiki_tags._cache[model]) self.assertEqual(len(wiki_tags._cache), 1) self.render({"obj": model}) self.assertIn(model, wiki_tags._cache) self.assertIsNone(wiki_tags._cache[model]) self.assertEqual(len(wiki_tags._cache), 1) self.assertNotIn("spam", wiki_tags._cache.values()) def test_obj_in__cache_and_articleforobjec_is_exist(self): article = Article.objects.create() content_type = ContentType.objects.get_for_model(article) ArticleForObject.objects.create( article=article, content_type=content_type, object_id=1 ) from wiki.templatetags import wiki_tags wiki_tags._cache = {article: "spam"} output = article_for_object({}, article) self.assertEqual(output, article) self.assertIn(article, wiki_tags._cache) self.assertEqual(wiki_tags._cache[article], article) output = self.render({"obj": article}) self.assertIn(article, wiki_tags._cache) self.assertEqual(wiki_tags._cache[article], article) expected = "Article without content (1)" self.assertIn(expected, output) # TODO manage plugins in template class WikiRenderTest(TemplateTestCase): template = """ {% load wiki_tags %} {% wiki_render article pc %} """ def tearDown(self): from wiki.core.plugins import registry registry._cache = {} super().tearDown() keys = [ "article", "content", "preview", "plugins", "STATIC_URL", "CACHE_TIMEOUT", ] def test_if_preview_content_is_none(self): # monkey patch from wiki.core.plugins import registry registry._cache = {"ham": "spam"} article = Article.objects.create() output = wiki_render({}, article) self.assertCountEqual(self.keys, output) self.assertEqual(output["article"], article) self.assertIsNone(output["content"]) self.assertIs(output["preview"], False) self.assertEqual(output["plugins"], {"ham": "spam"}) self.assertEqual(output["STATIC_URL"], django_settings.STATIC_URL) self.assertEqual(output["CACHE_TIMEOUT"], settings.CACHE_TIMEOUT) # Additional check self.render({"article": article, "pc": None}) def test_called_with_preview_content_and_article_have_current_revision( self ): article = Article.objects.create() ArticleRevision.objects.create( article=article, title="Test title", content="Some beauty test text", ) content = ( """This is a normal paragraph\n""" """\n""" """Headline\n""" """========\n""" ) expected = ( """(?s).*<p>This is a normal paragraph</p>\n""" """<h1 id="wiki-toc-headline">Headline""" """.*</h1>.*""" ) # monkey patch from wiki.core.plugins import registry registry._cache = {"spam": "eggs"} output = wiki_render({}, article, preview_content=content) self.assertCountEqual(self.keys, output) self.assertEqual(output["article"], article) self.assertRegex(output["content"], expected) self.assertIs(output["preview"], True) self.assertEqual(output["plugins"], {"spam": "eggs"}) self.assertEqual(output["STATIC_URL"], django_settings.STATIC_URL) self.assertEqual(output["CACHE_TIMEOUT"], settings.CACHE_TIMEOUT) output = self.render({"article": article, "pc": content}) self.assertRegex(output, expected) def test_called_with_preview_content_and_article_dont_have_current_revision( self ): article = Article.objects.create() content = ( """This is a normal paragraph\n""" """\n""" """Headline\n""" """========\n""" ) # monkey patch from wiki.core.plugins import registry registry._cache = {"spam": "eggs"} output = wiki_render({}, article, preview_content=content) self.assertCountEqual(self.keys, output) self.assertEqual(output["article"], article) self.assertMultiLineEqual(output["content"], "") self.assertIs(output["preview"], True) self.assertEqual(output["plugins"], {"spam": "eggs"}) self.assertEqual(output["STATIC_URL"], django_settings.STATIC_URL) self.assertEqual(output["CACHE_TIMEOUT"], settings.CACHE_TIMEOUT) self.render({"article": article, "pc": content}) class WikiFormTest(TemplateTestCase): template = """ {% load wiki_tags %} {% wiki_form form_obj %} """ def test_form_obj_is_not_baseform_instance(self): context = {"test_key": "test_value"} form_obj = "ham" with self.assertRaises(TypeError): wiki_form(context, form_obj) self.assertEqual(context, {"test_key": "test_value"}) with self.assertRaises(TypeError): self.render({"test_key": 100500}) self.assertEqual(context, {"test_key": "test_value"}) def test_form_obj_is_baseform_instance(self): context = {"test_key": "test_value"} # not by any special reasons, just a form form_obj = CreateRootForm() wiki_form(context, form_obj) self.assertEqual(context, {"test_key": "test_value", "form": form_obj}) self.render({"form_obj": form_obj}) self.assertEqual(context, {"test_key": "test_value", "form": form_obj}) class LoginUrlTest(TemplateTestCase): template = """ {% load wiki_tags %} {% login_url as some_url %} {{ some_url }} """ def test_no_request_in_context(self): with self.assertRaises(KeyError): login_url({}) with self.assertRaises(KeyError): self.render({}) def test_login_url_if_no_query_string_in_request(self): r = HttpRequest() r.META = {} r.path = "best/test/page/ever/" output = login_url({"request": r}) expected = "/_accounts/login/?next=best/test/page/ever/" self.assertEqual(output, expected) output = self.render({"request": r}) self.assertIn(expected, output) def test_login_url_if_query_string_is_empty(self): r = HttpRequest() r.META = {"QUERY_STRING": ""} r.path = "best/test/page/ever/" output = login_url({"request": r}) expected = "/_accounts/login/?next=best/test/page/ever/" self.assertEqual(output, expected) output = self.render({"request": r}) self.assertIn(expected, output) def test_login_url_if_query_string_is_not_empty(self): r = HttpRequest() r.META = {"QUERY_STRING": "title=Main_page&action=raw"} r.path = "best/test/page/ever/" context = {"request": r} output = login_url(context) expected = ( "/_accounts/login/" "?next=best/test/page/ever/%3Ftitle%3DMain_page%26action%3Draw" ) self.assertEqual(output, expected) output = self.render({"request": r}) self.assertIn(expected, output)
10,268
Python
.py
247
32.951417
80
0.625214
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,241
test_managers.py
django-wiki_django-wiki/tests/core/test_managers.py
""" Tests that the custom queryset methods work, this is important because the pattern of building them is different from Django 1.5 to 1.6 to 1.7 so there will be 3 patterns in play at the same time. """ from wiki.models import Article from wiki.models import URLPath from wiki.plugins.attachments.models import Attachment from ..base import ArticleTestBase class ArticleManagerTests(ArticleTestBase): def test_queryset_methods_directly_on_manager(self): self.assertEqual(Article.objects.can_read(self.superuser1).count(), 1) self.assertEqual(Article.objects.can_write(self.superuser1).count(), 1) self.assertEqual(Article.objects.active().count(), 1) def test_mass_deletion(self): """ https://github.com/django-wiki/django-wiki/issues/857 """ Article.objects.all().delete() self.assertEqual(Article.objects.all().count(), 0) def test_queryset_methods_on_querysets(self): self.assertEqual( Article.objects.all().can_read(self.superuser1).count(), 1 ) self.assertEqual( Article.objects.all().can_write(self.superuser1).count(), 1 ) self.assertEqual(Article.objects.all().active().count(), 1) # See: https://code.djangoproject.com/ticket/22817 def test_queryset_empty_querysets(self): self.assertEqual( Article.objects.none().can_read(self.superuser1).count(), 0 ) self.assertEqual( Article.objects.none().can_write(self.superuser1).count(), 0 ) self.assertEqual(Article.objects.none().active().count(), 0) class AttachmentManagerTests(ArticleTestBase): def test_queryset_methods_directly_on_manager(self): # Do the same for Attachment which uses ArtickeFkManager self.assertEqual( Attachment.objects.can_read(self.superuser1).count(), 0 ) self.assertEqual( Attachment.objects.can_write(self.superuser1).count(), 0 ) self.assertEqual(Attachment.objects.active().count(), 0) def test_queryset_methods_on_querysets(self): self.assertEqual( Attachment.objects.all().can_read(self.superuser1).count(), 0 ) self.assertEqual( Attachment.objects.all().can_write(self.superuser1).count(), 0 ) self.assertEqual(Attachment.objects.all().active().count(), 0) # See: https://code.djangoproject.com/ticket/22817 def test_queryset_empty_query_sets(self): self.assertEqual( Attachment.objects.none().can_read(self.superuser1).count(), 0 ) self.assertEqual( Attachment.objects.none().can_write(self.superuser1).count(), 0 ) self.assertEqual(Attachment.objects.none().active().count(), 0) class URLPathManagerTests(ArticleTestBase): def test_related_manager_works_with_filters(self): root = URLPath.root() self.assertNotIn(root.id, [p.id for p in root.children.active()])
3,014
Python
.py
69
36.014493
79
0.675418
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,242
test_urls.py
django-wiki_django-wiki/tests/core/test_urls.py
from django.conf.urls.static import static from django.contrib.sites.models import Site from django.test.testcases import TestCase from django.urls import include from django.urls import re_path from wiki.models import Article from wiki.models import URLPath from wiki.urls import get_pattern as get_wiki_pattern from wiki.urls import WikiURLPatterns from ..base import wiki_override_settings class WikiCustomUrlPatterns(WikiURLPatterns): def get_article_urls(self): urlpatterns = [ re_path( "^some-prefix/(?P<article_id>[0-9]+)/$", self.article_view_class.as_view(), name="get", ), ] return urlpatterns def get_article_path_urls(self): urlpatterns = [ re_path( "^some-other-prefix/(?P<path>.+/|)$", self.article_view_class.as_view(), name="get", ), ] return urlpatterns urlpatterns = [ re_path(r"^notify/", include("django_nyt.urls")), re_path( r"^elsewhere/", get_wiki_pattern(url_config_class=WikiCustomUrlPatterns), ), ] + static("/static/", document_root="./") @wiki_override_settings( WIKI_URL_CONFIG_CLASS="tests.core.test_models.WikiCustomUrlPatterns", ROOT_URLCONF="tests.core.test_urls", ) class ArticleModelReverseMethodTest(TestCase): def test_get_absolute_url_if_urlpath_set_is_not_exists__no_root_urlconf( self ): a = Article.objects.create() url = a.get_absolute_url() expected = "/elsewhere/some-prefix/1/" self.assertEqual(url, expected) def test_get_absolute_url_if_urlpath_set_is_exists__no_root_urlconf(self): a1 = Article.objects.create() s1 = Site.objects.create(domain="something.com", name="something.com") u1 = URLPath.objects.create(article=a1, site=s1) a2 = Article.objects.create() s2 = Site.objects.create( domain="somethingelse.com", name="somethingelse.com" ) URLPath.objects.create( article=a2, site=s2, parent=u1, slug="test_slug" ) url = a2.get_absolute_url() expected = "/elsewhere/some-other-prefix/test_slug/" self.assertEqual(url, expected)
2,295
Python
.py
62
29.306452
78
0.640505
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,243
test_commands.py
django-wiki_django-wiki/tests/core/test_commands.py
import os import sys import tempfile from django.core.management import call_command from ..base import ArticleTestBase class TestManagementCommands(ArticleTestBase): """ This clever test case can be inherited in other plugins Some data is created with ArticleTestBase, use that. """ def test_dumpdata_loaddata(self): sysout = sys.stdout fixtures_file = tempfile.NamedTemporaryFile( "w", delete=False, suffix=".json" ) sys.stdout = fixtures_file call_command("dumpdata", "wiki") fixtures_file.file.flush() fixtures_file.file.close() sys.stdout = open(os.devnull, "w") call_command("loaddata", fixtures_file.name) sys.stdout = sysout os.unlink(fixtures_file.name)
789
Python
.py
23
27.826087
59
0.680263
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,244
test_template_filters.py
django-wiki_django-wiki/tests/core/test_template_filters.py
from django.contrib.auth import get_user_model from wiki.models import Article from wiki.models import ArticleRevision from wiki.templatetags.wiki_tags import can_delete from wiki.templatetags.wiki_tags import can_moderate from wiki.templatetags.wiki_tags import can_read from wiki.templatetags.wiki_tags import can_write from wiki.templatetags.wiki_tags import get_content_snippet from wiki.templatetags.wiki_tags import is_locked from ..base import TemplateTestCase from ..base import wiki_override_settings User = get_user_model() class GetContentSnippet(TemplateTestCase): template = """ {% load wiki_tags %} {{ some_content|get_content_snippet:"keyword, max_words" }} """ def test_keyword_at_the_end_of_the_content(self): text = "lorem " * 80 content = text + " list" expected = ( "lorem lorem lorem lorem lorem lorem lorem lorem lorem " "lorem lorem lorem lorem lorem lorem <strong>list</strong>" ) output = get_content_snippet(content, "list") self.assertEqual(output, expected) def test_keyword_at_the_beginning_of_the_content(self): text = "lorem " * 80 content = "list " + text expected = ( "<strong>list</strong> lorem lorem lorem lorem lorem " "lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem " "lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem " "lorem lorem lorem" ) output = get_content_snippet(content, "list") self.assertEqual(output, expected) def test_whole_content_consists_of_keywords(self): content = "lorem " * 80 expected = "<strong>lorem</strong>" + 30 * " <strong>lorem</strong>" output = get_content_snippet(content, "lorem") self.assertEqual(output, expected) def test_keyword_is_not_in_a_content(self): content = "lorem " * 80 expected = ( "lorem lorem lorem lorem lorem lorem lorem lorem lorem " "lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem " "lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem" ) output = get_content_snippet(content, "list") self.assertEqual(output, expected) def test_a_few_keywords_in_content(self): text = "lorem " * 80 content = "list " + text text = "ipsum " * 80 content += text + " list " text = "dolorum " * 80 content += text + " list" expected = "<strong>list</strong>" + 30 * " lorem" output = get_content_snippet(content, "list") self.assertEqual(output, expected) # XXX bug or feature? def test_keyword_is_in_content_and_max_words_is_zero(self): text = "spam " * 800 content = text + " list" output = get_content_snippet(content, "list", 0) expected = "spam " * 800 + "<strong>list</strong>" self.assertEqual(output, expected) # XXX bug or feature? def test_keyword_is_in_content_and_max_words_is_negative(self): text = "spam " * 80 content = text + " list" output = get_content_snippet(content, "list", -10) expected = "spam " * 75 + "<strong>list</strong>" self.assertEqual(output, expected) # XXX bug or feature? def test_keyword_is_not_in_content_and_max_words_is_zero(self): content = "spam " * 15 output = get_content_snippet(content, "list", 0) expected = "" self.assertEqual(output, expected) # XXX bug or feature? def test_keyword_is_not_in_content_and_max_words_is_negative(self): content = "spam " * 15 output = get_content_snippet(content, "list", -10) expected = "spam spam spam spam spam" self.assertEqual(output, expected) def test_no_content(self): content = "" output = get_content_snippet(content, "list") self.assertEqual(output, "") content = " " output = get_content_snippet(content, "list") self.assertEqual(output, "") def test_strip_tags(self): keyword = "maybe" content = """ I should citate Shakespeare or Byron. Or <a>maybe</a> copy paste from <a href="http://python.org">python</a> or django documentation. Maybe. """ expected = ( "I should citate Shakespeare or Byron. " "Or <strong>maybe</strong> copy paste from python " "or django documentation. <strong>Maybe.</strong>" ) output = get_content_snippet(content, keyword, 30) self.assertEqual(output, expected) def test_max_words_arg(self): keyword = "eggs" content = """ knight eggs spam ham eggs guido python eggs circus """ expected = ( "knight <strong>eggs</strong> spam ham " "<strong>eggs</strong> guido" ) output = get_content_snippet(content, keyword, 5) self.assertEqual(output, expected) output = get_content_snippet(content, keyword, 0) expected = ( "knight <strong>eggs</strong> spam ham " "<strong>eggs</strong> guido python <strong>eggs</strong>" ) self.assertEqual(output, expected) def test_content_case_preserved(self): keyword = "DOlOr" match = "DoLoR" content = "lorem ipsum %s sit amet" % match output = get_content_snippet(content, keyword) self.assertIn(match, output) self.assertNotIn(keyword, output) class CanRead(TemplateTestCase): template = """ {% load wiki_tags %} {{ article|can_read:user }} """ @wiki_override_settings(WIKI_CAN_READ=lambda *args: True) def test_user_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Nobody", password="pass") output = can_read(a, u) self.assertIs(output, True) output = self.render({"article": a, "user": u}) self.assertIn("True", output) @wiki_override_settings(WIKI_CAN_READ=lambda *args: False) def test_user_dont_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Noman", password="pass") output = can_read(a, u) self.assertIs(output, False) output = self.render({"article": a, "user": u}) self.assertIn("False", output) class CanWrite(TemplateTestCase): template = """ {% load wiki_tags %} {{ article|can_write:user }} """ @wiki_override_settings(WIKI_CAN_DELETE=lambda *args: True) def test_user_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Nobody", password="pass") output = can_write(a, u) self.assertIs(output, True) output = self.render({"article": a, "user": u}) self.assertIn("True", output) @wiki_override_settings(WIKI_CAN_WRITE=lambda *args: False) def test_user_dont_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Noman", password="pass") output = can_write(a, u) self.assertIs(output, False) output = self.render({"article": a, "user": u}) self.assertIn("False", output) class CanDelete(TemplateTestCase): template = """ {% load wiki_tags %} {{ article|can_delete:user }} """ @wiki_override_settings(WIKI_CAN_DELETE=lambda *args: True) def test_user_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Nobody", password="pass") output = can_delete(a, u) self.assertIs(output, True) output = self.render({"article": a, "user": u}) self.assertIn("True", output) @wiki_override_settings(WIKI_CAN_WRITE=lambda *args: False) def test_user_dont_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Noman", password="pass") output = can_delete(a, u) self.assertIs(output, False) output = self.render({"article": a, "user": u}) self.assertIn("False", output) class CanModerate(TemplateTestCase): template = """ {% load wiki_tags %} {{ article|can_moderate:user }} """ @wiki_override_settings(WIKI_CAN_MODERATE=lambda *args: True) def test_user_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Nobody", password="pass") output = can_moderate(a, u) self.assertIs(output, True) output = self.render({"article": a, "user": u}) self.assertIn("True", output) def test_user_dont_have_permission(self): a = Article.objects.create() u = User.objects.create(username="Noman", password="pass") output = can_moderate(a, u) self.assertIs(output, False) output = self.render({"article": a, "user": u}) self.assertIn("False", output) class IsLocked(TemplateTestCase): template = """ {% load wiki_tags %} {{ article|is_locked }} """ def test_no_current_revision(self): a = Article.objects.create() output = is_locked(a) self.assertIsNone(output) output = self.render({"article": a}) self.assertIn("None", output) def test_have_current_revision_and_not_locked(self): a = Article.objects.create() ArticleRevision.objects.create(article=a, locked=False) b = Article.objects.create() ArticleRevision.objects.create(article=b) output = is_locked(a) self.assertIs(output, False) output = is_locked(b) self.assertIs(output, False) output = self.render({"article": a}) self.assertIn("False", output) def test_have_current_revision_and_locked(self): a = Article.objects.create() ArticleRevision.objects.create(article=a, locked=True) output = is_locked(a) self.assertIs(output, True) output = self.render({"article": a}) self.assertIn("True", output) class PluginEnabled(TemplateTestCase): template = """ {% load wiki_tags %} {% if "wiki.plugins.attachments"|plugin_enabled %}It is enabled{% endif %} """ def test_true(self): output = self.render({}) self.assertIn("It is enabled", output) class WikiSettings(TemplateTestCase): template = """ {% load wiki_tags %} {% if "ACCOUNT_HANDLING"|wiki_settings %}It is enabled{% endif %} """ @wiki_override_settings(WIKI_ACCOUNT_HANDLING=lambda *args: True) def test_setting(self): output = self.render({}) self.assertIn("It is enabled", output)
10,883
Python
.py
261
33.482759
82
0.623205
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,245
test_forms.py
django-wiki_django-wiki/tests/core/test_forms.py
from django.test import TestCase from django.utils.translation import gettext from wiki.forms import DeleteForm from wiki.forms import UserCreationForm from tests.base import DjangoClientTestBase from tests.base import RequireRootArticleMixin class DeleteFormTests(RequireRootArticleMixin, DjangoClientTestBase): def test_not_sure(self): data = {"purge": True, "confirm": False} form = DeleteForm( article=self.root_article, has_children=True, data=data ) self.assertIs(form.is_valid(), False) self.assertEqual( form.errors["__all__"], [gettext("You are not sure enough!")] ) class UserCreationFormTests(TestCase): def test_honeypot(self): data = { "address": "Wiki Road 123", "phone": "12345678", "email": "wiki@wiki.com", "username": "WikiMan", "password1": "R@ndomString", "password2": "R@ndomString", } form = UserCreationForm(data=data) self.assertIs(form.is_valid(), False) self.assertEqual( form.errors["__all__"], [ "Thank you, non-human visitor. Please keep trying to fill in the form." ], )
1,258
Python
.py
34
28.441176
87
0.62018
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,246
test_markdown.py
django-wiki_django-wiki/tests/core/test_markdown.py
from unittest.mock import patch import markdown from django.test import TestCase from wiki.core.markdown import ArticleMarkdown from wiki.core.markdown.mdx.codehilite import WikiCodeHiliteExtension from wiki.core.markdown.mdx.responsivetable import ResponsiveTableExtension from wiki.models import URLPath from ..base import ArticleTestBase try: import pygments pygments = True # NOQA except ImportError: pygments = False class ArticleMarkdownTests(ArticleTestBase): @patch("wiki.core.markdown.settings") def test_do_not_modify_extensions(self, settings): extensions = ["footnotes", "attr_list", "sane_lists"] settings.MARKDOWN_KWARGS = {"extensions": extensions} number_of_extensions = len(extensions) ArticleMarkdown(None) self.assertEqual(len(extensions), number_of_extensions) def test_html_removal(self): urlpath = URLPath.create_urlpath( self.root, "html_removal", title="Test 1", content="</html>only_this", ) self.assertEqual(urlpath.article.render(), "<p>only_this</p>") class ResponsiveTableExtensionTests(TestCase): def setUp(self): super().setUp() self.md = markdown.Markdown( extensions=["extra", ResponsiveTableExtension()] ) self.md_without = markdown.Markdown(extensions=["extra"]) def test_wrapping(self): text = "|th|th|\n|--|--|\n|td|td|" expected = ( '<div class="table-responsive">\n' + self.md_without.convert(text) + "\n</div>" ) self.assertEqual(self.md.convert(text), expected) class CodehiliteTests(TestCase): def test_fenced_code(self): md = markdown.Markdown(extensions=["extra", WikiCodeHiliteExtension()]) text = ( "Code:\n" "\n" "```python\n" "echo 'line 1'\n" "echo 'line 2'\n" "```\n" ) result = ( ( """<p>Code:</p>\n""" """<div class="codehilite-wrap"><div class="codehilite"><pre><span></span><span class="n">echo</span> <span class="s1">&#39;line 1&#39;</span>\n""" """<span class="n">echo</span> <span class="s1">&#39;line 2&#39;</span>\n""" """</pre></div>\n""" """</div>""" ) if pygments else ( """<p>Code:</p>\n""" """<div class="codehilite-wrap"><pre class="codehilite"><code class="language-python">echo 'line 1'\n""" """echo 'line 2'\n</code></pre>\n""" """</div>""" ) ) self.assertEqual( md.convert(text), result, ) def test_indented_code(self): md = markdown.Markdown(extensions=["extra", WikiCodeHiliteExtension()]) text = ( "Code:\n" "\n" " #!/usr/bin/python\n" " print('line 1')\n" " print('line 2')\n" " print('æøå')\n" "\n" ) result = ( ( """<p>Code:</p>\n""" """<div class="codehilite-wrap"><table class="codehilitetable"><tr><td class="linenos"><div class="linenodiv"><pre>1\n""" """2\n""" """3\n""" """4</pre></div></td><td class="code"><div class="codehilite"><pre><span></span><span class="ch">#!/usr/bin/python</span>\n""" """<span class="k">print</span><span class="p">(</span><span class="s1">&#39;line 1&#39;</span><span class="p">)</span>\n""" """<span class="k">print</span><span class="p">(</span><span class="s1">&#39;line 2&#39;</span><span class="p">)</span>\n""" """<span class="k">print</span><span class="p">(</span><span class="s1">&#39;æøå&#39;</span><span class="p">)</span>\n""" """</pre></div>\n""" """</td></tr></table></div>""" ) if pygments else ( """<p>Code:</p>\n""" """<div class="codehilite-wrap"><pre class="codehilite"><code class="language-python linenums">#!/usr/bin/python\n""" """print('line 1')\n""" """print('line 2')\n""" """print('æøå')\n</code></pre>\n""" """</div>""" ) ) self.assertEqual( md.convert(text), result, )
4,546
Python
.py
113
29.292035
163
0.513605
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,247
test_views.py
django-wiki_django-wiki/tests/core/test_views.py
import pprint from django.contrib.messages import constants from django.contrib.messages import get_messages from django.http import JsonResponse from django.shortcuts import resolve_url from django.test import override_settings from django.utils import translation from django.utils.html import escape from django_functest import FuncBaseMixin from wiki import models from wiki.conf import settings as wiki_settings from wiki.forms import PermissionsForm from wiki.forms import validate_slug_numbers from wiki.models import ArticleRevision from wiki.models import reverse from wiki.models import URLPath from ..base import ArticleWebTestUtils from ..base import DjangoClientTestBase from ..base import NORMALUSER1_PASSWORD from ..base import NORMALUSER1_USERNAME from ..base import RequireRootArticleMixin from ..base import SeleniumBase from ..base import SUPERUSER1_USERNAME from ..base import WebTestBase from tests.testdata.models import CustomGroup class RootArticleViewTestsBase(FuncBaseMixin): """Tests for creating/viewing the root article.""" def test_root_article(self): """ Test redirecting to /create-root/, creating the root article and a simple markup. """ self.get_url("wiki:root") self.assertUrlsEqual(resolve_url("wiki:root_create")) self.fill( { "#id_content": "test heading h1\n====\n", "#id_title": "Wiki Test", } ) self.submit('button[name="save_changes"]') self.assertUrlsEqual("/") self.assertTextPresent("test heading h1") article = URLPath.root().article self.assertIn("test heading h1", article.current_revision.content) class RootArticleViewTestsWebTest(RootArticleViewTestsBase, WebTestBase): pass class RootArticleViewTestsSelenium(RootArticleViewTestsBase, SeleniumBase): pass class ArticleViewViewTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): """ Tests for article views, assuming a root article already created. """ def dump_db_status(self, message=""): """Debug printing of the complete important database content.""" print(f"*** db status *** {message}") from wiki.models import Article, ArticleRevision for klass in (Article, ArticleRevision, URLPath): print(f"* {klass.__name__} *") pprint.pprint(list(klass.objects.values()), width=240) def test_redirects_to_create_if_the_slug_is_unknown(self): response = self.get_by_path("unknown/") self.assertRedirects( response, resolve_url("wiki:create", path="") + "?slug=unknown" ) def test_redirects_to_create_with_lowercased_slug(self): response = self.get_by_path("Unknown_Linked_Page/") self.assertRedirects( response, resolve_url("wiki:create", path="") + "?slug=unknown_linked_page", ) def test_article_list_update(self): """ Test automatic adding and removing the new article to/from article_list. """ root_data = { "content": "[article_list depth:2]", "current_revision": str( URLPath.root().article.current_revision.id ), "preview": "1", "title": "Root Article", } response = self.client.post( resolve_url("wiki:edit", path=""), root_data ) self.assertRedirects(response, resolve_url("wiki:root")) # verify the new article is added to article_list response = self.client.post( resolve_url("wiki:create", path=""), {"title": "Sub Article 1", "slug": "SubArticle1"}, ) self.assertRedirects( response, resolve_url("wiki:get", path="subarticle1/") ) self.assertContains(self.get_by_path(""), "Sub Article 1") self.assertContains(self.get_by_path(""), "subarticle1/") # verify the deleted article is removed from article_list response = self.client.post( resolve_url("wiki:delete", path="SubArticle1/"), { "confirm": "on", "purge": "on", "revision": str( URLPath.objects.get( slug="subarticle1" ).article.current_revision.id ), }, ) self.assertRedirects(response, resolve_url("wiki:get", path="")) messages = [m.message for m in get_messages(response.wsgi_request)] self.assertIn( "This article together with all its contents are now completely gone", messages[0], ) self.assertNotContains(self.get_by_path(""), "Sub Article 1") def test_anonymous_root(self): self.client.logout() response = self.client.get( reverse("wiki:get", kwargs={"article_id": self.root_article.pk}) ) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("wiki:get", kwargs={"path": ""})) self.assertEqual(response.status_code, 200) def test_normaluser_root(self): self.client.login( username=NORMALUSER1_USERNAME, password=NORMALUSER1_PASSWORD ) response = self.client.get( reverse("wiki:get", kwargs={"article_id": self.root_article.pk}) ) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("wiki:get", kwargs={"path": ""})) self.assertEqual(response.status_code, 200) def test_show_max_children(self): response = self.client.post( resolve_url("wiki:create", path=""), { "title": "Main", "slug": "WikiRoot", "content": "Content level 1", }, ) self.assertRedirects( response, resolve_url("wiki:get", path="wikiroot/") ) response = self.client.get( reverse("wiki:get", kwargs={"path": "wikiroot/"}) ) self.assertEqual(response.status_code, 200) self.assertIsInstance(response.context["children_slice"], list) self.assertEqual(len(response.context["children_slice"]), 0) for idx in range(1, 40): response = self.client.post( resolve_url("wiki:create", path="wikiroot/"), { "title": f"Sub Article {idx}", "slug": f"SubArticle{idx}", "content": f"Sub Article {idx}", }, ) self.assertRedirects( response, resolve_url("wiki:get", path=f"wikiroot/subarticle{idx}/"), ) response = self.client.get( reverse("wiki:get", kwargs={"path": "wikiroot/"}) ) self.assertEqual(response.status_code, 200) self.assertEqual( len(response.context["children_slice"]), wiki_settings.SHOW_MAX_CHILDREN, ) class CreateViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_create_nested_article_in_article(self): response = self.client.post( resolve_url("wiki:create", path=""), { "title": "Level 1", "slug": "Level1", "content": "Content level 1", }, ) self.assertRedirects(response, resolve_url("wiki:get", path="level1/")) response = self.client.post( resolve_url("wiki:create", path="Level1/"), {"title": "test", "slug": "Test", "content": "Content on level 2"}, ) self.assertRedirects( response, resolve_url("wiki:get", path="level1/test/") ) response = self.client.post( resolve_url("wiki:create", path=""), { "title": "test", "slug": "Test", "content": "Other content on level 1", }, ) self.assertRedirects(response, resolve_url("wiki:get", path="test/")) self.assertContains( self.get_by_path("Test/"), "Other content on level 1" ) self.assertContains( self.get_by_path("Level1/Test/"), "Content" ) # on level 2') def test_illegal_slug(self): # A slug cannot be '123' because it gets confused with an article ID. response = self.client.post( resolve_url("wiki:create", path=""), {"title": "Illegal slug", "slug": "123", "content": "blah"}, ) self.assertContains(response, escape(validate_slug_numbers.message)) class MoveViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_illegal_slug(self): # A slug cannot be '123' because it gets confused with an article ID. response = self.client.post( resolve_url("wiki:move", path=""), {"destination": "", "slug": "123", "redirect": ""}, ) self.assertContains(response, escape(validate_slug_numbers.message)) def test_move(self): # Create a hierarchy of pages self.client.post( resolve_url("wiki:create", path=""), {"title": "Test", "slug": "test0", "content": "Content .0."}, ) self.client.post( resolve_url("wiki:create", path="test0/"), {"title": "Test00", "slug": "test00", "content": "Content .00."}, ) self.client.post( resolve_url("wiki:create", path=""), {"title": "Test1", "slug": "test1", "content": "Content .1."}, ) self.client.post( resolve_url("wiki:create", path="test1/"), {"title": "Tes10", "slug": "test10", "content": "Content .10."}, ) self.client.post( resolve_url("wiki:create", path="test1/test10/"), { "title": "Test100", "slug": "test100", "content": "Content .100.", }, ) # Move /test1 => /test0 (an already existing destination slug!) response = self.client.post( resolve_url("wiki:move", path="test1/"), { "destination": str(URLPath.root().article.current_revision.id), "slug": "test0", "redirect": "", }, ) self.assertContains(response, "A slug named") self.assertContains(response, "already exists.") # Move /test1 >= /test2 (valid slug), no redirect test0_id = URLPath.objects.get( slug="test0" ).article.current_revision.id response = self.client.post( resolve_url("wiki:move", path="test1/"), {"destination": str(test0_id), "slug": "test2", "redirect": ""}, ) self.assertRedirects( response, resolve_url("wiki:get", path="test0/test2/") ) # Check that there is no article displayed in this path anymore response = self.get_by_path("test1/") self.assertRedirects(response, "/_create/?slug=test1") # Create /test0/test2/test020 response = self.client.post( resolve_url("wiki:create", path="test0/test2/"), { "title": "Test020", "slug": "test020", "content": "Content .020.", }, ) # Move /test0/test2 => /test1new + create redirect response = self.client.post( resolve_url("wiki:move", path="test0/test2/"), { "destination": str(URLPath.root().article.current_revision.id), "slug": "test1new", "redirect": "true", }, ) self.assertRedirects( response, resolve_url("wiki:get", path="test1new/") ) # Check that /test1new is a valid path response = self.get_by_path("test1new/") self.assertContains(response, "Content .1.") # Check that the child article test0/test2/test020 was also moved response = self.get_by_path("test1new/test020/") self.assertContains(response, "Content .020.") response = self.get_by_path("test0/test2/") self.assertContains(response, "Moved: Test1") self.assertRegex( response.rendered_content, r"moved to <a[^>]*>wiki:/test1new/" ) response = self.get_by_path("test0/test2/test020/") self.assertContains(response, "Moved: Test020") self.assertRegex( response.rendered_content, r"moved to <a[^>]*>wiki:/test1new/test020", ) # Check that moved_to was correctly set urlsrc = URLPath.get_by_path("/test0/test2/") urldst = URLPath.get_by_path("/test1new/") self.assertEqual(urlsrc.moved_to, urldst) # Check that moved_to was correctly set on the child's previous path urlsrc = URLPath.get_by_path("/test0/test2/test020/") urldst = URLPath.get_by_path("/test1new/test020/") self.assertEqual(urlsrc.moved_to, urldst) def test_translation(self): # Test that translation of "Be careful, links to this article" exists. self.client.post( resolve_url("wiki:create", path=""), {"title": "Test", "slug": "test0", "content": "Content"}, ) url = resolve_url("wiki:move", path="test0/") response_en = self.client.get(url) self.assertIn("Move article", response_en.rendered_content) self.assertIn("Be careful", response_en.rendered_content) with translation.override("da-DK"): response_da = self.client.get(url) self.assertNotIn("Move article", response_da.rendered_content) self.assertNotIn("Be careful", response_da.rendered_content) class DeleteViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_render_delete_view(self): """ Other tests do not render the delete view but just sends a POST """ self.client.post( resolve_url("wiki:create", path=""), { "title": "Test delete", "slug": "testdelete", "content": "To be deleted", }, ) response = self.client.get( resolve_url("wiki:delete", path="testdelete/"), ) # test the cache self.assertContains(response, "Delete article") def test_articles_cache_is_cleared_after_deleting(self): # That bug is tested by one individual test, otherwise it could be # revealed only by sequence of tests in some particular order response = self.client.post( resolve_url("wiki:create", path=""), { "title": "Test cache", "slug": "testcache", "content": "Content 1", }, ) self.assertRedirects( response, resolve_url("wiki:get", path="testcache/") ) response = self.client.post( resolve_url("wiki:delete", path="testcache/"), { "confirm": "on", "purge": "on", "revision": str( URLPath.objects.get( slug="testcache" ).article.current_revision.id ), }, ) self.assertRedirects(response, resolve_url("wiki:get", path="")) response = self.client.post( resolve_url("wiki:create", path=""), { "title": "Test cache", "slug": "TestCache", "content": "Content 2", }, ) self.assertRedirects( response, resolve_url("wiki:get", path="testcache/") ) self.assertContains(self.get_by_path("TestCache/"), "Content 2") def test_deleted_view(self): """ Test that a special page is shown for restoring/purging a deleted article. """ # 1. Create the article self.client.post( resolve_url("wiki:create", path=""), { "title": "Test delete", "slug": "testdelete", "content": "To be deleted", }, ) # 2. Soft delete it self.client.post( resolve_url("wiki:delete", path="testdelete/"), { "confirm": "on", "purge": "", "revision": str( URLPath.objects.get( slug="testdelete" ).article.current_revision.id ), }, ) # 3. Get and test that it redirects to the deleted page response = self.client.get( resolve_url("wiki:get", path="testdelete/"), follow=True, ) # test that it's the Deleted page self.assertContains(response, "Article deleted") # 4. Test that we can purge the page now self.client.post( resolve_url("wiki:deleted", path="testdelete/"), { "confirm": "on", "purge": "on", "revision": str( URLPath.objects.get( slug="testdelete" ).article.current_revision.id ), }, ) # 5. Test that it's not found anymore response = self.client.get( resolve_url("wiki:get", path="testdelete/"), follow=True, ) self.assertContains(response, "Add new article") # def test_delete_article_without_urlpath(self): # """ # We need a test that tests that articles without URLpaths are correctly # deleted. # """ # pass # def test_dont_delete_children(self): # Article.objects.create() class EditViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_preview_save(self): """Test edit preview, edit save and messages.""" example_data = { "content": "The modified text", "current_revision": str( URLPath.root().article.current_revision.id ), "preview": "1", # 'save': '1', # probably not too important "summary": "why edited", "title": "wiki test", } # test preview response = self.client.post( resolve_url("wiki:preview", path=""), example_data, # url: '/_preview/' ) self.assertContains(response, "The modified text") def test_preview_xframe_options_sameorigin(self): """Ensure that preview response has X-Frame-Options: SAMEORIGIN""" example_data = { "content": "The modified text", "current_revision": str( URLPath.root().article.current_revision.id ), "preview": "1", "summary": "why edited", "title": "wiki test", } response = self.client.post( resolve_url("wiki:preview", path=""), example_data ) self.assertEqual(response.get("X-Frame-Options"), "SAMEORIGIN") def test_revision_conflict(self): """ Test the warning if the same article is being edited concurrently. """ example_data = { "content": "More modifications", "current_revision": str( URLPath.root().article.current_revision.id ), "preview": "0", "save": "1", "summary": "why edited", "title": "wiki test", } response = self.client.post( resolve_url("wiki:edit", path=""), example_data ) self.assertRedirects(response, resolve_url("wiki:root")) response = self.client.post( resolve_url("wiki:edit", path=""), example_data ) self.assertContains( response, "While you were editing, someone else changed the revision.", ) class DiffViewTests(RequireRootArticleMixin, DjangoClientTestBase): def setUp(self): super().setUp() self.root_article.add_revision( ArticleRevision(title="New Revision"), save=True ) self.new_revision = self.root_article.current_revision def test_diff(self): response = self.client.get( reverse("wiki:diff", kwargs={"revision_id": self.root_article.pk}) ) diff = { "diff": ["+ root article content"], "other_changes": [["New title", "Root Article"]], } self.assertJSONEqual(str(response.content, encoding="utf8"), diff) self.assertIsInstance(response, JsonResponse) self.assertEqual(response.status_code, 200) class EditViewTestsBase(RequireRootArticleMixin, FuncBaseMixin): def test_edit_save(self): old_revision = URLPath.root().article.current_revision self.get_url("wiki:edit", path="") self.fill( { "#id_content": "Something 2", "#id_summary": "why edited", "#id_title": "wiki test", } ) self.submit("#id_save") self.assertTextPresent("Something 2") self.assertTextPresent("successfully added") new_revision = URLPath.root().article.current_revision self.assertIn("Something 2", new_revision.content) self.assertEqual( new_revision.revision_number, old_revision.revision_number + 1 ) class EditViewTestsWebTest(EditViewTestsBase, WebTestBase): pass class EditViewTestsSelenium(EditViewTestsBase, SeleniumBase): # Javascript only tests: def test_preview_and_save(self): self.get_url("wiki:edit", path="") self.fill( { "#id_content": "Some changed stuff", "#id_summary": "why edited", "#id_title": "wiki test", } ) self.click("#id_preview") self.submit("#id_preview_save_changes") new_revision = URLPath.root().article.current_revision self.assertIn("Some changed stuff", new_revision.content) class SearchViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_query_string(self): response = self.client.get( resolve_url("wiki:search"), {"q": "Article"} ) self.assertContains(response, "Root Article") def test_empty_query_string(self): response = self.client.get(resolve_url("wiki:search"), {"q": ""}) self.assertFalse(response.context["articles"]) def test_hierarchy_search(self): c = self.client c.post( resolve_url("wiki:create", path=""), {"title": "Test0", "slug": "test0", "content": "Content test0"}, ) c.post( resolve_url("wiki:create", path=""), {"title": "Test1", "slug": "test1", "content": "Content test1"}, ) c.post( resolve_url("wiki:create", path="test0/"), { "title": "Subtest0", "slug": "subtest0", "content": "Content test2", }, ) response = c.get( resolve_url("wiki:search", path="test0/"), {"q": "Content test"} ) articles = response.context["articles"] def contains_title(articles, title): return any( article.current_revision.title == title for article in articles ) self.assertIs(contains_title(articles, "Test0"), True) self.assertIs(contains_title(articles, "Test1"), False) self.assertIs(contains_title(articles, "Subtest0"), True) def test_hierarchy_search_404(self): c = self.client response = c.get( resolve_url("wiki:search", path="test0/"), {"q": "Content test"} ) self.assertEqual(response.status_code, 404) class DeletedListViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_deleted_articles_list(self): response = self.client.post( resolve_url("wiki:create", path=""), { "title": "Delete Me", "slug": "deleteme", "content": "delete me please!", }, ) self.assertRedirects( response, resolve_url("wiki:get", path="deleteme/") ) response = self.client.post( resolve_url("wiki:delete", path="deleteme/"), { "confirm": "on", "revision": URLPath.objects.get( slug="deleteme" ).article.current_revision.id, }, ) self.assertRedirects(response, resolve_url("wiki:get", path="")) response = self.client.get(resolve_url("wiki:deleted_list")) self.assertContains(response, "Delete Me") class MergeViewTest( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_merge_preview(self): """Test merge preview""" first_revision = self.root_article.current_revision example_data = { "content": "More modifications\n\nMerge new line", "current_revision": str(first_revision.id), "preview": "0", "save": "1", "summary": "testing merge", "title": "wiki test", } # save a new revision self.client.post(resolve_url("wiki:edit", path=""), example_data) new_revision = models.Article.objects.get( id=self.root_article.id ).current_revision response = self.client.get( resolve_url( "wiki:merge_revision_preview", article_id=self.root_article.id, revision_id=first_revision.id, ), ) self.assertContains(response, "Previewing merge between:") self.assertContains( response, f"#{first_revision.revision_number}", ) self.assertContains( response, f"#{new_revision.revision_number}", ) class SourceViewTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_template_used(self): response = self.client.get( reverse("wiki:source", kwargs={"article_id": self.root_article.pk}) ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name="wiki/source.html") def test_can_read_permission(self): # everybody can see the source of an article self.client.logout() response = self.client.get( reverse("wiki:source", kwargs={"article_id": self.root_article.pk}) ) self.assertEqual(response.status_code, 200) def test_content(self): response = self.client.get( reverse("wiki:source", kwargs={"article_id": self.root_article.pk}) ) self.assertIn("Source of ", str(response.content)) self.assertEqual(response.context["selected_tab"], "source") class HistoryViewTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_can_read_permission(self): response = self.client.get( reverse( "wiki:history", kwargs={"article_id": self.root_article.pk} ) ) self.assertEqual(response.status_code, 200) def test_content(self): response = self.client.get( reverse( "wiki:history", kwargs={"article_id": self.root_article.pk} ) ) self.assertContains(response, "History:") self.assertEqual(response.context["selected_tab"], "history") class DirViewTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_browse_root(self): response = self.client.get( reverse("wiki:dir", kwargs={"path": ""}), ) self.assertRegex( response.rendered_content, r'Browsing\s+<strong><a href=".+">/</a></strong>', ) def test_browse_root_query(self): self.client.post( resolve_url("wiki:create", path=""), {"title": "Test", "slug": "test0", "content": "Content .0."}, ) self.client.post( resolve_url("wiki:create", path="test0/"), {"title": "Test00", "slug": "test00", "content": "Content .00."}, ) response = self.client.get( reverse("wiki:dir", kwargs={"path": ""}), {"query": "Test"}, ) self.assertRegex(response.rendered_content, r"1 article") response = self.client.get( reverse("wiki:dir", kwargs={"path": "test0/"}), {"query": "Test00"}, ) self.assertRegex(response.rendered_content, r"1 article") class SettingsViewTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_change_group(self): group = CustomGroup.objects.create() response = self.client.post( resolve_url("wiki:settings", article_id=self.root_article.pk) + "?f=form0", {"group": group.pk, "owner_username": SUPERUSER1_USERNAME}, follow=True, ) self.root_article.refresh_from_db() self.assertEqual(self.root_article.group, group) self.assertEqual(self.root_article.owner, self.superuser1) messages = list(get_messages(response.wsgi_request)) self.assertEqual(len(messages), 1) message = messages[0] self.assertEqual(message.level, constants.SUCCESS) self.assertEqual( message.message, "Permission settings for the article were updated.", ) def test_change_invalid_owner(self): self.assertIsNone(self.root_article.owner) response = self.client.post( resolve_url("wiki:settings", article_id=self.root_article.pk) + "?f=form0", {"owner_username": "invalid"}, follow=True, ) self.assertEqual( response.context["forms"][0].errors["owner_username"], ["No user with that username"], ) def test_unchanged_message(self): # 1. This is not pretty: Constructs a request object to use to construct # the PermissionForm get_response = self.client.get( resolve_url("wiki:settings", article_id=self.root_article.pk) ) # 2. Construct a PermissionForm form = PermissionsForm(self.root_article, get_response.wsgi_request) # 3. ...in order to get the POST form values that will be transmitted form_values = {field.html_name: field.value() or "" for field in form} # 4. Send an unchanged form response = self.client.post( resolve_url("wiki:settings", article_id=self.root_article.pk) + "?f=form0", form_values, follow=True, ) messages = list(get_messages(response.wsgi_request)) self.assertEqual(len(messages), 1) message = messages[0] self.assertEqual(message.level, constants.SUCCESS) self.assertEqual( message.message, "Your permission settings were unchanged, so nothing saved.", ) @override_settings(ACCOUNT_HANDLING=True) def test_login_required(self): self.client.logout() response = self.client.get( reverse( "wiki:settings", kwargs={"article_id": self.root_article.pk} ) ) # it's redirecting self.assertEqual(response.status_code, 302) def test_auth_user(self): response = self.client.get( reverse( "wiki:settings", kwargs={"article_id": self.root_article.pk} ) ) self.assertEqual(response.status_code, 200) def test_normal_user(self): """ Tests that the settings view page renders for a normal user Regression test: https://github.com/django-wiki/django-wiki/issues/1058 """ response = self.client.post( resolve_url("wiki:create", path=""), { "title": "Level 1", "slug": "Level1", "content": "Content level 1", }, ) self.client.login( username=NORMALUSER1_USERNAME, password=NORMALUSER1_PASSWORD ) response = self.client.get( reverse("wiki:settings", kwargs={"path": "level1/"}) ) self.assertEqual(response.status_code, 200) def test_content(self): response = self.client.get( reverse( "wiki:settings", kwargs={"article_id": self.root_article.pk} ) ) self.assertEqual(response.context["selected_tab"], "settings")
33,367
Python
.py
855
28.614035
82
0.571808
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,248
test_models.py
django-wiki_django-wiki/tests/core/test_models.py
from django.apps import apps from django.contrib.auth import get_user_model from django.contrib.sites.models import Site from django.test.testcases import TestCase from django.urls import re_path from wiki.conf import settings from wiki.managers import ArticleManager from wiki.models import Article from wiki.models import ArticleRevision from wiki.models import URLPath from wiki.urls import WikiURLPatterns User = get_user_model() Group = apps.get_model(settings.GROUP_MODEL) class WikiCustomUrlPatterns(WikiURLPatterns): def get_article_urls(self): urlpatterns = [ re_path( "^my-wiki/(?P<article_id>[0-9]+)/$", self.article_view_class.as_view(), name="get", ), ] return urlpatterns def get_article_path_urls(self): urlpatterns = [ re_path( "^my-wiki/(?P<path>.+/|)$", self.article_view_class.as_view(), name="get", ), ] return urlpatterns class ArticleModelTest(TestCase): def test_default_fields_of_empty_article(self): a = Article.objects.create() self.assertIsNone(a.current_revision) self.assertIsNone(a.owner) self.assertIsNone(a.group) self.assertIsNotNone(a.created) self.assertIsNotNone(a.modified) self.assertIsNotNone(a.group_read) self.assertIsNotNone(a.group_write) self.assertIsNotNone(a.other_read) self.assertIsNotNone(a.other_write) # XXX maybe redundant test def test_model_manager_class(self): self.assertIsInstance(Article.objects, ArticleManager) def test_str_method_if_have_current_revision(self): title = "Test title" a = Article.objects.create() ArticleRevision.objects.create(article=a, title=title) self.assertEqual(str(a), title) def test_str_method_if_dont_have_current_revision(self): a = Article.objects.create() expected = "Article without content (1)" self.assertEqual(str(a), expected) def test_get_absolute_url_if_urlpath_set_is_exists(self): a1 = Article.objects.create() s1 = Site.objects.create(domain="something.com", name="something.com") u1 = URLPath.objects.create(article=a1, site=s1) a2 = Article.objects.create() s2 = Site.objects.create( domain="somethingelse.com", name="somethingelse.com" ) URLPath.objects.create( article=a2, site=s2, parent=u1, slug="test_slug" ) url = a2.get_absolute_url() expected = "/test_slug/" self.assertEqual(url, expected) def test_get_absolute_url_if_urlpath_set_is_not_exists(self): a = Article.objects.create() url = a.get_absolute_url() expected = "/1/" self.assertEqual(url, expected) def test_article_is_related_to_articlerevision(self): title = "Test title" a = Article.objects.create() r = ArticleRevision.objects.create(article=a, title=title) self.assertEqual(r.article, a) self.assertIn(r, a.articlerevision_set.all()) def test_article_is_related_to_owner(self): u = User.objects.create(username="Noman", password="pass") a = Article.objects.create(owner=u) self.assertEqual(a.owner, u) self.assertIn(a, u.owned_articles.all()) def test_article_is_related_to_group(self): g = Group.objects.create() a = Article.objects.create(group=g) self.assertEqual(a.group, g) self.assertIn(a, g.article_set.all()) def test_cache(self): a = Article.objects.create() ArticleRevision.objects.create( article=a, title="test", content="# header" ) expected = """<h1 id="wiki-toc-header">header""" """.*</h1>""" # cached content does not exist yet. this will create it self.assertRegex(a.get_cached_content(), expected) # actual cached content test self.assertRegex(a.get_cached_content(), expected) def test_articlerevision_presave_signals(self): a = Article.objects.create() ar1 = ArticleRevision(article=a, title="revision1") a.add_revision(ar1) self.assertEqual(ar1, a.current_revision) ar2 = ArticleRevision(article=a, title="revision2") ar2.save() self.assertEqual(ar2.previous_revision, ar1)
4,480
Python
.py
109
32.669725
78
0.648281
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,249
test_editor.py
django-wiki_django-wiki/tests/core/test_editor.py
import wiki.editors from django.forms import Textarea from wiki.editors.base import BaseEditor from ..base import RequireRootArticleMixin from ..base import WebTestBase from ..base import wiki_override_settings class CustomEditor(BaseEditor): def get_widget(self, revision=None): return Textarea(attrs={"data-revision": revision.pk}) def get_admin_widget(self, revision=None): return Textarea(attrs={"data-revision": revision.pk}) class EditorTest(RequireRootArticleMixin, WebTestBase): def setUp(self): super().setUp() # reset the cached editor class and instance wiki.editors._editor, wiki.editors._EditorClass = None, None def test_editor_widget_markitup(self): response = self.get_url("wiki:edit", path="") self.assertContains( response, '<textarea name="content" class="markItUp" rows="10" cols="40" id="id_content">', ) def test_admin_widget_markitup(self): response = self.get_url( "admin:wiki_articlerevision_change", object_id=self.root_article.current_revision.id, ) self.assertContains( response, '<textarea name="content" class="markItUp" rows="10" cols="40" id="id_content">', ) @wiki_override_settings(WIKI_EDITOR="wiki.editors.base.BaseEditor") def test_editor_widget_base(self): response = self.get_url("wiki:edit", path="") self.assertContains( response, '<textarea name="content" cols="40" rows="10" id="id_content">', ) @wiki_override_settings(WIKI_EDITOR="wiki.editors.base.BaseEditor") def test_admin_widget_base(self): response = self.get_url( "admin:wiki_articlerevision_change", object_id=self.root_article.current_revision.id, ) self.assertContains( response, '<textarea name="content" cols="40" rows="10" id="id_content">', ) @wiki_override_settings(WIKI_EDITOR="tests.core.test_editor.CustomEditor") def test_editor_widget_custom(self): response = self.get_url("wiki:edit", path="") self.assertContains( response, '<textarea name="content" cols="40" rows="10" data-revision="{}" id="id_content">'.format( self.root_article.current_revision.id ), ) @wiki_override_settings(WIKI_EDITOR="tests.core.test_editor.CustomEditor") def test_admin_widget_custom(self): response = self.get_url( "admin:wiki_articlerevision_change", object_id=self.root_article.current_revision.id, ) self.assertContains( response, '<textarea name="content" cols="40" rows="10" data-revision="{}" id="id_content">'.format( self.root_article.current_revision.id ), )
2,908
Python
.py
69
33.26087
102
0.633888
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,250
test_checks.py
django-wiki_django-wiki/tests/core/test_checks.py
import copy from django.conf import settings from django.core.checks import Error from django.core.checks import registry from django.test import TestCase from wiki.checks import FIELDS_IN_CUSTOM_USER_MODEL from wiki.checks import REQUIRED_CONTEXT_PROCESSORS from wiki.checks import REQUIRED_INSTALLED_APPS from wiki.checks import Tags from ..base import wiki_override_settings def _remove(settings, arg): return [setting for setting in settings if not setting.startswith(arg)] class CheckTests(TestCase): def test_required_installed_apps(self): for app in REQUIRED_INSTALLED_APPS: with self.settings( INSTALLED_APPS=_remove(settings.INSTALLED_APPS, app[0]) ): errors = registry.run_checks( tags=[Tags.required_installed_apps] ) expected_errors = [ Error( "needs %s in INSTALLED_APPS" % app[1], id="wiki.%s" % app[2], ) ] self.assertEqual(errors, expected_errors) def test_required_context_processors(self): for context_processor in REQUIRED_CONTEXT_PROCESSORS: TEMPLATES = copy.deepcopy(settings.TEMPLATES) TEMPLATES[0]["OPTIONS"]["context_processors"] = [ cp for cp in TEMPLATES[0]["OPTIONS"]["context_processors"] if cp != context_processor[0] ] with self.settings(TEMPLATES=TEMPLATES): errors = registry.run_checks(tags=[Tags.context_processors]) expected_errors = [ Error( "needs %s in TEMPLATES[*]['OPTIONS']['context_processors']" % context_processor[0], id="wiki.%s" % context_processor[1], ) ] self.assertEqual(errors, expected_errors) def test_custom_user_model_mitigation_required(self): """ Django check django.forms.ModelForm.Meta on definition, and raises an error if Meta.fields don't exist in Meta.model. This causes problems in wiki.forms.UserCreationForm and wiki.forms.UserUpdateForm when a custom user model doesn't have fields django-wiki assumes. There is some code in wiki.forms that detects this situation. This check asserts that Django are still raising an exception on definition, and asserts the mitigation code in wiki.forms, and that test_check_for_fields_in_custom_user_model below are required. """ from django.core.exceptions import FieldError from django import forms from ..testdata.models import VeryCustomUser with self.assertRaisesRegex( FieldError, "Unknown field\\(s\\) \\((email|username|, )+\\) specified for VeryCustomUser", ): class UserUpdateForm(forms.ModelForm): class Meta: model = VeryCustomUser fields = ["username", "email"] def test_check_for_fields_in_custom_user_model(self): from django.contrib.auth import get_user_model with wiki_override_settings( WIKI_ACCOUNT_HANDLING=False, AUTH_USER_MODEL="testdata.VeryCustomUser", ): errors = registry.run_checks( tags=[Tags.fields_in_custom_user_model] ) self.assertEqual(errors, []) with wiki_override_settings( WIKI_ACCOUNT_HANDLING=True, AUTH_USER_MODEL="testdata.VeryCustomUser", ): errors = registry.run_checks( tags=[Tags.fields_in_custom_user_model] ) expected_errors = [ Error( "%s.%s.%s refers to a field that is not of type %s" % ( get_user_model().__module__, get_user_model().__name__, field_fetcher, required_field_type, ), hint="If you have your own login/logout views, turn off settings.WIKI_ACCOUNT_HANDLING", obj=get_user_model(), id="wiki.%s" % error_code, ) for check_function_name, field_fetcher, required_field_type, error_code in FIELDS_IN_CUSTOM_USER_MODEL ] self.assertEqual(errors, expected_errors) with wiki_override_settings(WIKI_ACCOUNT_HANDLING=True): errors = registry.run_checks( tags=[Tags.fields_in_custom_user_model] ) self.assertEqual(errors, [])
4,756
Python
.py
103
32.786408
155
0.579186
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,251
test_links.py
django-wiki_django-wiki/tests/plugins/macros/test_links.py
from wiki.core import markdown from tests.base import RequireRootArticleMixin from tests.base import TestBase class WikiLinksTests(RequireRootArticleMixin, TestBase): def test_wikilink(self): md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert("[[Root Article]]") self.assertEqual( md_text, '<p><a class="wiki_wikilink wiki-broken" href="/Root_Article/">Root Article</a></p>', )
468
Python
.py
11
35.818182
97
0.693833
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,252
test_macro.py
django-wiki_django-wiki/tests/plugins/macros/test_macro.py
from wiki.core import markdown from tests.base import RequireRootArticleMixin from tests.base import TestBase class MacroTests(RequireRootArticleMixin, TestBase): def test_article_list(self): md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert("[article_list depth:2]") self.assertIn("Nothing below this level", md_text) self.assertNotIn("[article_list depth:2]", md_text) def test_escape(self): md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert("`[article_list depth:2]`") self.assertNotIn("Nothing below this level", md_text) self.assertIn("[article_list depth:2]", md_text)
707
Python
.py
14
44.071429
64
0.714078
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,253
test_toc.py
django-wiki_django-wiki/tests/plugins/macros/test_toc.py
from django.test import TestCase from markdown import Markdown from wiki.core import markdown from wiki.plugins.macros.mdx.toc import WikiTocExtension from tests.base import RequireRootArticleMixin from tests.base import TestBase class TocMacroTests(TestCase): maxDiff = None def test_toc_renders_table_of_content(self): """Verifies that the [TOC] wiki code renders a Table of Content""" md = Markdown(extensions=["extra", WikiTocExtension()]) text = ( "[TOC]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc">\n' "<ul>\n" '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.</h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection</h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_with_kwargs(self): """Verifies that the [TOC] wiki code renders a Table of Content""" md = Markdown(extensions=["extra", WikiTocExtension(title="test")]) text = ( "[TOC]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">test</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.</h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection</h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) class TocMacroTestsInWiki(RequireRootArticleMixin, TestBase): def test_toc_renders_table_of_content_in_wiki(self): md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">Contents</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_with_toc_class(self): md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC toc_class:'nontoc test']\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="nontoc test"><span class="toctitle">Contents</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_in_wiki_with_kwargs(self): md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC title:test]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">test</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_in_wiki_with_depth(self): md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC toc_depth:1]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">Contents</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a></li>\n' "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_in_wiki_with_multi_kwargs(self): md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC title:'test' toc_depth:'1' anchorlink:'True']\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">test</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a></li>\n' "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title"><a class="toclink" ' 'href="#wiki-toc-first-title">First title.</a><a ' 'class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection"><a class="toclink" ' 'href="#wiki-toc-subsection">Subsection</a><a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_in_wiki_wrong_type(self): md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC anchorlink:Yes]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">Contents</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_in_wiki_test_bool_one(self): # Test if the integer is 1 and should be True md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC anchorlink:1]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">Contents</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title"><a class="toclink" ' 'href="#wiki-toc-first-title">First title.</a><a ' 'class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection"><a class="toclink" ' 'href="#wiki-toc-subsection">Subsection</a><a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_in_wiki_test_bool_zero(self): # Test if the integer is zero and should be false md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC anchorlink:0]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">Contents</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output) def test_toc_renders_table_of_content_in_wiki_test_bool_wrong(self): # Test if the integer is wrong value md = markdown.ArticleMarkdown(article=self.root_article) text = ( "[TOC anchorlink:5]\n" "\n" "# First title.\n" "\n" "Paragraph 1\n" "\n" "## Subsection\n" "\n" "Paragraph 2" ) expected_output = ( '<div class="toc"><span class="toctitle">Contents</span><ul>\n' '<li><a href="#wiki-toc-first-title">First title.</a><ul>\n' '<li><a href="#wiki-toc-subsection">Subsection</a></li>\n' "</ul>\n" "</li>\n" "</ul>\n" "</div>\n" '<h1 id="wiki-toc-first-title">First title.<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-first-title/">[edit]</a></h1>\n' "<p>Paragraph 1</p>\n" '<h2 id="wiki-toc-subsection">Subsection<a class="article-edit-title-link" ' 'href="/_plugin/editsection/header/wiki-toc-subsection/">[edit]</a></h2>\n' "<p>Paragraph 2</p>" ) self.assertEqual(md.convert(text), expected_output)
13,554
Python
.py
330
29.469697
91
0.508214
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,254
test_forms.py
django-wiki_django-wiki/tests/plugins/images/test_forms.py
from django.test import TestCase from django.utils.translation import gettext from wiki.plugins.images.forms import PurgeForm class PurgeFormTest(TestCase): def test_not_sure(self): form = PurgeForm(data={"confirm": False}) self.assertIs(form.is_valid(), False) self.assertEqual( form.errors["confirm"], [gettext("You are not sure enough!")] ) def test_sure(self): form = PurgeForm(data={"confirm": True}) self.assertIs(form.is_valid(), True)
514
Python
.py
13
33.076923
73
0.676707
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,255
test_markdown.py
django-wiki_django-wiki/tests/plugins/images/test_markdown.py
import base64 from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from wiki.core import markdown from wiki.plugins.images import models from tests.base import RequireRootArticleMixin from tests.base import TestBase class ImageMarkdownTests(RequireRootArticleMixin, TestBase): def setUp(self): super().setUp() self.image_revision = models.ImageRevision( image=self._create_test_gif_file(), width=1, height=1 ) self.image = models.Image(article=self.root_article) self.image.add_revision(self.image_revision) self.assertEqual(1, self.image.id) def _create_test_gif_file(self): # A black 1x1 gif str_base64 = "R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=" filename = "test.gif" data = base64.b64decode(str_base64) filedata = BytesIO(data) return InMemoryUploadedFile( filedata, None, filename, "image", len(data), None ) def test_before_and_after(self): md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert( "before [image:%s align:left] after" % self.image.id ) before_pos = md_text.index("before") figure_pos = md_text.index("<figure") after_pos = md_text.index("after") self.assertTrue(before_pos < figure_pos < after_pos) def test_markdown(self): md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert("[image:%s align:left]" % self.image.id) self.assertIn("<figure", md_text) self.assertNotIn("[image:%s align:left]" % self.image.id, md_text) md_text = md.convert( "image: [image:%s align:left]\nadasd" % self.image.id ) self.assertIn("<figure", md_text) self.assertIn("<figcaption", md_text) md_text = md.convert( "image: [image:%s align:right size:medium]\nadasd" % self.image.id ) self.assertIn("<figure", md_text) self.assertIn("<figcaption", md_text) md_text = md.convert( "image: [image:123 align:left size:medium]\nadasd" ) self.assertIn("Image not found", md_text) self.assertIn("<figcaption", md_text) def test_caption(self): md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert( "[image:%s align:left]\n this is visual" % self.image.id ) self.assertIn("<figure", md_text) self.assertRegex( md_text, r'<figcaption class="caption">\s*this is visual\s*</figcaption>', ) md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert( "[image:%s align:left]\n this is visual\n second line" % self.image.id ) self.assertIn("<figure", md_text) self.assertRegex( md_text, r'<figcaption class="caption">\s*this is visual\s*second line\s*</figcaption>', ) def check_escape(self, text_to_escape): md = markdown.ArticleMarkdown(article=self.root_article) md_text = md.convert("`%s`" % text_to_escape) self.assertNotIn("<figure", md_text) self.assertIn(text_to_escape, md_text) def test_escape(self): self.check_escape("[image:%s align:left]" % self.image.id) self.check_escape("image tag: [image:%s]" % self.image.id)
3,482
Python
.py
82
33.817073
91
0.626734
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,256
test_views.py
django-wiki_django-wiki/tests/plugins/images/test_views.py
import base64 import os import re from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from django.urls import reverse from PIL import Image from wiki.core.plugins import registry as plugin_registry from wiki.models import URLPath from wiki.plugins.images import models from wiki.plugins.images.wiki_plugin import ImagePlugin from ...base import ArticleWebTestUtils from ...base import DjangoClientTestBase from ...base import RequireRootArticleMixin from ...base import wiki_override_settings class ImageTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def setUp(self): super().setUp() self.article = self.root_article # A black 1x1 gif self.test_data = "R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=" def _create_gif_filestream_from_base64(self, str_base64, **kwargs): """ Helper function to create filestream for upload. Parameters : strData : str, test string data Optional Arguments : filename : str, Defaults to 'test.txt' """ filename = kwargs.get("filename", "test.gif") data = base64.b64decode(str_base64) filedata = BytesIO(data) filestream = InMemoryUploadedFile( filedata, None, filename, "image", len(data), None ) return filestream def _create_test_image(self, path): # Get the form index plugin_index = -1 for cnt, plugin_instance in enumerate(plugin_registry.get_sidebar()): if isinstance(plugin_instance, ImagePlugin): plugin_index = cnt break self.assertGreaterEqual( plugin_index, 0, msg="Image plugin not activated" ) base_edit_url = reverse("wiki:edit", kwargs={"path": path}) url = base_edit_url + f"?f=form{plugin_index:d}" filestream = self._create_gif_filestream_from_base64(self.test_data) response = self.client.post( url, { "unsaved_article_title": self.article.current_revision.title, "unsaved_article_content": self.article.current_revision.content, "image": filestream, "images_save": "1", }, ) self.assertRedirects(response, base_edit_url) def test_index(self): url = reverse("wiki:images_index", kwargs={"path": ""}) response = self.client.get( url, ) self.assertContains(response, "Images") def test_upload(self): """ Tests that simple file upload uploads correctly Uploading a file should preserve the original filename. Uploading should not modify file in any way. """ self._create_test_image("") # Check the object was created. image = models.Image.objects.get() image_revision = image.current_revision.imagerevision self.assertEqual(image_revision.get_filename(), "test.gif") self.assertEqual( image_revision.image.file.read(), base64.b64decode(self.test_data) ) def get_article(self, cont, image): urlpath = URLPath.create_urlpath( URLPath.root(), "html_image", title="TestImage", content=cont ) if image: self._create_test_image(urlpath.path) return urlpath.article.render() def test_image_missing(self): output = self.get_article("[image:1]", False) expected = ( '<figure class="thumbnail"><a href="">' '<div class="caption"><em>Image not found</em></div>' '</a><figcaption class="caption"></figcaption></figure>' ) self.assertEqual(output, expected) def test_image_default(self): output = self.get_article("[image:1]", True) image_rev = models.Image.objects.get().current_revision.imagerevision expected = re.compile( r'<figure class="thumbnail">' r'<a href="' + re.escape(image_rev.image.url) + '">' r'<img src="/?cache/.*\.jpg" alt="test\.gif">' r'</a><figcaption class="caption"></figcaption></figure>' ) self.assertRegex(output, expected) def test_image_large_right(self): output = self.get_article("[image:1 align:right size:large]", True) image_rev = models.Image.objects.get().current_revision.imagerevision expected = re.compile( r'<figure class="thumbnail float-right">' r'<a href="' + re.escape(image_rev.image.url) + '">' r'<img src="/?cache/.*\.jpg" alt="test\.gif"></a>' r'<figcaption class="caption"></figcaption></figure>' ) self.assertRegex(output, expected) def test_image_orig(self): output = self.get_article("[image:1 size:orig]", True) image_rev = models.Image.objects.get().current_revision.imagerevision expected = ( '<figure class="thumbnail">' '<a href="' + image_rev.image.url + '">' '<img src="' + image_rev.image.url + '" alt="test.gif"></a>' '<figcaption class="caption"></figcaption></figure>' ) self.assertEqual(output, expected) # https://gist.github.com/guillaumepiot/817a70706587da3bd862835c59ef584e def generate_photo_file(self): file = BytesIO() image = Image.new("RGBA", size=(100, 100), color=(155, 0, 0)) image.save(file, "gif") file.name = "test.gif" file.seek(0) return file def test_add_revision(self): self._create_test_image(path="") image = models.Image.objects.get() before_edit_rev = image.current_revision.revision_number response = self.client.post( reverse( "wiki:images_add_revision", kwargs={ "article_id": self.root_article, "image_id": image.pk, "path": "", }, ), data={"image": self.generate_photo_file()}, ) self.assertRedirects( response, reverse("wiki:edit", kwargs={"path": ""}) ) image = models.Image.objects.get() self.assertEqual(models.Image.objects.count(), 1) self.assertEqual( image.current_revision.previous_revision.revision_number, before_edit_rev, ) def test_delete_restore_revision(self): self._create_test_image(path="") image = models.Image.objects.get() before_edit_rev = image.current_revision.revision_number response = self.client.get( reverse( "wiki:images_delete", kwargs={ "article_id": self.root_article, "image_id": image.pk, "path": "", }, ), ) self.assertRedirects( response, reverse("wiki:images_index", kwargs={"path": ""}) ) image = models.Image.objects.get() self.assertEqual(models.Image.objects.count(), 1) self.assertEqual( image.current_revision.previous_revision.revision_number, before_edit_rev, ) self.assertIs(image.current_revision.deleted, True) # RESTORE before_edit_rev = image.current_revision.revision_number response = self.client.get( reverse( "wiki:images_restore", kwargs={ "article_id": self.root_article, "image_id": image.pk, "path": "", }, ), ) self.assertRedirects( response, reverse("wiki:images_index", kwargs={"path": ""}) ) image = models.Image.objects.get() self.assertEqual(models.Image.objects.count(), 1) self.assertEqual( image.current_revision.previous_revision.revision_number, before_edit_rev, ) self.assertFalse(image.current_revision.deleted) def test_purge(self): """ Tests that an image is really purged """ self._create_test_image(path="") image = models.Image.objects.get() image_revision = image.current_revision.imagerevision f_path = image_revision.image.file.name self.assertIs(os.path.exists(f_path), True) response = self.client.post( reverse( "wiki:images_purge", kwargs={ "article_id": self.root_article, "image_id": image.pk, "path": "", }, ), data={"confirm": True}, ) self.assertRedirects( response, reverse("wiki:images_index", kwargs={"path": ""}) ) self.assertEqual(models.Image.objects.count(), 0) self.assertIs(os.path.exists(f_path), False) def test_add_revision_purge_image(self): """ Tests that an image with more than one revision is really purged """ # use another test to stage this one self.test_add_revision() image = models.Image.objects.get() image_revision = image.current_revision.imagerevision f_path = image_revision.image.file.name self.assertIs(os.path.exists(f_path), True) response = self.client.post( reverse( "wiki:images_purge", kwargs={ "article_id": self.root_article, "image_id": image.pk, "path": "", }, ), data={"confirm": True}, ) self.assertRedirects( response, reverse("wiki:images_index", kwargs={"path": ""}) ) self.assertEqual(models.Image.objects.count(), 0) self.assertIs(os.path.exists(f_path), False) @wiki_override_settings(ACCOUNT_HANDLING=True) def test_login_on_revision_add(self): self._create_test_image(path="") self.client.logout() image = models.Image.objects.get() url = reverse( "wiki:images_add_revision", kwargs={ "article_id": self.root_article, "image_id": image.pk, "path": "", }, ) response = self.client.post( url, data={"image": self.generate_photo_file()} ) self.assertRedirects( response, "{}?next={}".format(reverse("wiki:login"), url) )
10,645
Python
.py
274
28.372263
81
0.574357
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,257
test_editsection.py
django-wiki_django-wiki/tests/plugins/editsection/test_editsection.py
import re from django.urls import reverse from django_functest import FuncBaseMixin from wiki.models import URLPath from ...base import DjangoClientTestBase from ...base import RequireRootArticleMixin from ...base import WebTestBase TEST_CONTENT = ( "Title 1\n" "=======\n" "## Title 2\n" "Title 3\n" "-------\n" "a\n" "Paragraph\n" "-------\n" "### Title 4\n" "## Title 5\n" "# Title 6\n" ) TEST_CONTENT_SRC_COMMENT = """ # Section 1 Section 1 Lorem ipsum dolor sit amet ```python # hello world print("hello world") ``` # Section 2 Section 2 Lorem ipsum dolor sit amet """ class EditSectionTests(RequireRootArticleMixin, DjangoClientTestBase): def test_editsection(self): # Test creating links to allow editing all sections individually urlpath = URLPath.create_urlpath( URLPath.root(), "testedit", title="TestEdit", content=TEST_CONTENT ) output = urlpath.article.render() expected = ( r"(?s)" r'Title 1<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-1/">\[edit\]</a>.*' r'Title 2<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-2/">\[edit\]</a>.*' r'Title 3<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-3/">\[edit\]</a>.*' r'Title 4<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-4/">\[edit\]</a>.*' r'Title 5<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-5/">\[edit\]</a>.*' r'Title 6<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-6/">\[edit\]</a>.*' ) self.assertRegex(output, expected) # Test wrong header text. Editing should fail with a redirect. url = reverse( "wiki:editsection", kwargs={"path": "testedit/", "header": "does-not-exist"}, ) response = self.client.get(url) self.assertRedirects( response, reverse("wiki:get", kwargs={"path": "testedit/"}) ) # Test extracting sections for editing url = reverse( "wiki:editsection", kwargs={"path": "testedit/", "header": "wiki-toc-title-4"}, ) response = self.client.get(url) expected = ">### Title 4[\r\n]*" "<" self.assertRegex(response.rendered_content, expected) url = reverse( "wiki:editsection", kwargs={"path": "testedit/", "header": "wiki-toc-title-3"}, ) response = self.client.get(url) expected = ( ">Title 3[\r\n]*" "-------[\r\n]*" "a[\r\n]*" "Paragraph[\r\n]*" "-------[\r\n]*" "### Title 4[\r\n]*" "<" ) self.assertRegex(response.rendered_content, expected) def test_broken_content(self): # Regression test for https://github.com/django-wiki/django-wiki/issues/1094 TEST_CONTENT = "### [Here we go](#anchor)" urlpath = URLPath.create_urlpath( URLPath.root(), "testedit", title="TestEdit", content=TEST_CONTENT ) output = urlpath.article.render() print(output) def get_section_content(self, response): # extract actual section content from response (editor) m = re.search( r"<textarea[^>]+>(?P<content>[^<]+)</textarea>", response.rendered_content, re.DOTALL, ) if m: return m.group("content") else: return "" def test_sourceblock_with_comment(self): # https://github.com/django-wiki/django-wiki/issues/1246 URLPath.create_urlpath( URLPath.root(), "testedit_src", title="TestEditSourceComment", content=TEST_CONTENT_SRC_COMMENT, ) url = reverse( "wiki:editsection", kwargs={"path": "testedit_src/", "header": "wiki-toc-section-2"}, ) response = self.client.get(url) actual = self.get_section_content(response) expected = "# Section 2\r\nSection 2 Lorem ipsum dolor sit amet\r\n" self.assertEqual(actual, expected) def test_nonunique_headers(self): """test whether non-unique headers will be handled properly""" source = """# Investigation 1\n\n## Date\n2023-01-01\n\n# Investigation 2\n\n## Date\n2023-01-02""" URLPath.create_urlpath( URLPath.root(), "testedit_src", title="TestEditSourceComment", content=source, ) url = reverse( "wiki:editsection", kwargs={"path": "testedit_src/", "header": "wiki-toc-date"}, ) response = self.client.get(url) actual = self.get_section_content(response) expected = "## Date\r\n2023-01-01\r\n\r\n" self.assertEqual(actual, expected) url = reverse( "wiki:editsection", kwargs={"path": "testedit_src/", "header": "wiki-toc-date_1"}, ) response = self.client.get(url) actual = self.get_section_content(response) expected = "## Date\r\n2023-01-02" self.assertEqual(actual, expected) def test_underscore_and_dot(self): """test whether we can handle non-slug characters like dots in header IDs""" # Explanation: While autogenerated ids are slugified, Markdown allows to manually # specify the ID using the {#custom_id_value} syntax. As HTML5 only requires ID # values not to contain whitespace, we should be able to handle any valid HTML5 ID, too. source = """# Title 1 {#some_id_with.dot}\n\n""" urlpath = URLPath.create_urlpath( URLPath.root(), "testedit", title="TestEdit", content=source ) # rendering causes NoReverseMatch without the fix actual = urlpath.article.render() expected = '<h1 id="some_id_with.dot">Title 1<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/some_id_with.dot/">[edit]</a></h1>' self.assertEqual(actual, expected) class EditSectionEditBase(RequireRootArticleMixin, FuncBaseMixin): pass class EditSectionEditTests(EditSectionEditBase, WebTestBase): # Test editing a section def test_editsection_edit(self): urlpath = URLPath.create_urlpath( URLPath.root(), "testedit", title="TestEdit", content=TEST_CONTENT ) old_number = urlpath.article.current_revision.revision_number self.get_literal_url( reverse( "wiki:editsection", kwargs={"path": "testedit/", "header": "wiki-toc-title-3"}, ) ) self.fill({"#id_content": "# Header 1\nContent of the new section"}) self.submit("#id_save") expected = ( r"(?s)" r'Title 1<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-1/">\[edit\]</a>.*' r'Title 2<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-2/">\[edit\]</a>.*' r'Header 1<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-header-1/">\[edit\]</a>.*' r"Content of the new section.*" r'Title 5<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-5/">\[edit\]</a>.*' r'Title 6<a class="article-edit-title-link" href="/testedit/_plugin/editsection/header/wiki-toc-title-6/">\[edit\]</a>.*' ) self.assertRegex(self.last_response.content.decode("utf-8"), expected) new_number = URLPath.objects.get( slug="testedit" ).article.current_revision.revision_number self.assertEqual(new_number, old_number + 1)
8,050
Python
.py
183
34.989071
166
0.603723
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,258
test_redlinks.py
django-wiki_django-wiki/tests/plugins/redlinks/test_redlinks.py
from django.urls import reverse from wiki.core import markdown from wiki.models import URLPath from ...base import wiki_override_settings from tests.base import RequireRootArticleMixin from tests.base import TestBase class RedlinksTests(RequireRootArticleMixin, TestBase): def setUp(self): super().setUp() self.child = URLPath.create_urlpath(self.root, "child") def test_root_to_self(self): self.assert_internal(self.root, "[Internal](./)") def test_root_to_child(self): self.assert_internal(self.root, "[Child](child/)") def test_child_to_self(self): self.assert_internal(self.child, "[Child](../child/)") def test_child_to_self_no_slash(self): self.assert_internal(self.child, "[Child](../child)") def test_root_to_outside(self): self.assert_external( self.root, "[Outside](http://outside.example.org/)" ) def test_absolute_external(self): if reverse("wiki:get", kwargs={"path": ""}) == "/": # All absolute paths could be wiki-internal, and the server root is # the the wiki root, which is bound to exist. self.assert_internal(self.root, "[Server Root](/)") else: # The wiki root is below the server root, so the server root is an # external link. self.assert_external(self.root, "[Server Root](/)") self.assert_external(self.root, "[Static File](/static/)") def test_absolute_internal(self): wiki_root = reverse("wiki:get", kwargs={"path": ""}) self.assert_internal(self.root, f"[Server Root]({wiki_root})") def test_child_to_broken(self): self.assert_broken(self.child, "[Broken](../broken/)") def test_root_to_broken(self): self.assert_broken(self.root, "[Broken](broken/)") def test_not_a_link(self): self.assert_none(self.root, '<a id="anchor">old-style anchor</a>') def test_invalid_url(self): self.assert_none(self.root, "[Invalid](http://127[.500.20.1/)") def test_mailto(self): self.assert_none(self.root, "<foo@example.com>") def assert_none(self, urlpath, md_text): md = markdown.ArticleMarkdown(article=urlpath.article) html = md.convert(md_text) self.assertNotIn("wiki-internal", html) self.assertNotIn("wiki-external", html) self.assertNotIn("wiki-broken", html) self.assertIn("<a", html) def assert_internal(self, urlpath, md_text): md = markdown.ArticleMarkdown(article=urlpath.article) html = md.convert(md_text) self.assertIn("wiki-internal", html) self.assertNotIn("wiki-external", html) self.assertNotIn("wiki-broken", html) def assert_external(self, urlpath, md_text): md = markdown.ArticleMarkdown(article=urlpath.article) html = md.convert(md_text) self.assertNotIn("wiki-internal", html) self.assertIn("wiki-external", html) self.assertNotIn("wiki-broken", html) def assert_broken(self, urlpath, md_text): md = markdown.ArticleMarkdown(article=urlpath.article) html = md.convert(md_text) self.assertNotIn("wiki-internal", html) self.assertNotIn("wiki-external", html) self.assertIn("wiki-broken", html) @wiki_override_settings( WIKI_URL_CONFIG_CLASS="tests.core.test_models.WikiCustomUrlPatterns", ROOT_URLCONF="tests.core.test_urls", ) class RedLinksWithChangedBaseURL(RedlinksTests): pass
3,518
Python
.py
76
38.697368
79
0.657995
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,259
test_pymdown.py
django-wiki_django-wiki/tests/plugins/pymdown/test_pymdown.py
from django.test import TestCase from markdown import Markdown from wiki.core import markdown from wiki.plugins.pymdown import wiki_plugin from tests.base import RequireRootArticleMixin from tests.base import TestBase class TocMacroTests(TestCase): """ This is used to test the PyMdown extensions module independently of Django Wiki. If this fails it should because something has changed on with PyMdown or Markdown itself. """ def test_pymdown_renders_block_details(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = "/// details | Some summary\n" "\n" "Some content\b" "///\n" expected_output = ( "<details>\n" "<summary>Some summary</summary>\n" "<p>Some content\x08///</p>\n" "</details>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_renders_block_details_with_type(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = ( "/// details | Some summary\n" " type: warning\n" "\n" "Some content\b" "///\n" ) expected_output = ( '<details class="warning">\n' "<summary>Some summary</summary>\n" "<p>Some content\x08///</p>\n" "</details>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_renders_block_admonition(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = "/// admonition | Some summary\n" "Some content\b" "///\n" expected_output = ( '<div class="admonition">\n' '<p class="admonition-title">Some summary</p>\n' "<p>Some content\x08///</p>\n" "</div>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_renders_block_admonition_with_type(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = ( "/// admonition | Some summary\n" " type: warning\n" "Some content\b" "///\n" ) expected_output = ( '<div class="admonition warning">\n' '<p class="admonition-title">Some summary</p>\n' "<p>Some content\x08///</p>\n" "</div>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_renders_block_definition(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = ( "/// define\n" "Apple\n" "\n" "- Pomaceous fruit of plants of the genus Malu in the family Rosaceae.\n" "///\n" ) expected_output = ( "<dl>\n" "<dt>Apple</dt>\n" "<dd>Pomaceous fruit of plants of the genus Malu in the family " "Rosaceae.</dd>\n" "</dl>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_renders_block_definition_multiples(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = ( "/// define\n" "Apple\n" "\n" "- Pomaceous fruit of plants of the genus Malu in the family Rosaceae.\n" "\n" "Orange\n" "\n" "- The fruit of an evergreen tree of hte genus Citrus.\n" "///\n" ) expected_output = ( "<dl>\n" "<dt>Apple</dt>\n" "<dd>Pomaceous fruit of plants of the genus Malu in the family " "Rosaceae.</dd>\n" "<dt>Orange</dt>\n" "<dd>The fruit of an evergreen tree of hte genus Citrus.</dd>\n" "</dl>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_renders_block_definition_multiple_terms(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = ( "/// define\n" "Term 1\n" "\n" "Term 2\n" "- Definition a\n" "\n" "Term 3\n" "\n" "- Definition b\n" "///\n" ) expected_output = ( "<dl>\n" "<dt>Term 1</dt>\n" "<dt>Term 2\n" "- Definition a</dt>\n" "<dt>Term 3</dt>\n" "<dd>Definition b</dd>\n" "</dl>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_renders_block_html_wrap(self): extensions = ["extra"] extensions.extend(wiki_plugin.PymdownPlugin.markdown_extensions) md = Markdown(extensions=extensions) text = ( "/// html | div[stype='border: 1px solid red;']\n" "some *markdown* content\n" "///\n" ) expected_output = ( '<div stype="border: 1px solid red;">\n' "<p>some <em>markdown</em> content</p>\n" "</div>" ) self.assertEqual(expected_output, md.convert(text)) class TocMacroTestsInWiki(RequireRootArticleMixin, TestBase): def test_pymdown_in_wiki_renders_block_details(self): wiki_plugin.settings.update_whitelist() # Fixes testing bug md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = "/// details | Some summary\n" "\n" "Some content\n" "///\n" expected_output = ( "<details>\n" "<summary>Some summary</summary>\n" "<p>Some content</p>\n" "</details>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_details_with_type(self): wiki_plugin.settings.update_whitelist() # Fixes testing bug md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = ( "/// details | Some summary\n" " type: warning\n" "Some content\n" "///\n" ) expected_output = ( '<details class="warning">\n' "<summary>Some summary</summary>\n" "<p>Some content</p>\n" "</details>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_admonition(self): md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = "/// admonition | Some summary\n" "Some content.\n" "///\n" expected_output = ( '<div class="admonition">\n' '<p class="admonition-title">Some summary</p>\n' "<p>Some content.</p>\n" "</div>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_admonition_with_type(self): md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = ( "/// admonition | Some summary\n" " type: warning\n" "Some content.\n" "///\n" ) expected_output = ( '<div class="admonition warning">\n' '<p class="admonition-title">Some summary</p>\n' "<p>Some content.</p>\n" "</div>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_definition(self): md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = ( "/// define\n" "Apple\n" "\n" "- Pomaceous fruit of plants of the genus Malu in the family Rosaceae.\n" "///\n" ) expected_output = ( "<dl>\n" "<dt>Apple</dt>\n" "<dd>Pomaceous fruit of plants of the genus Malu in the family " "Rosaceae.</dd>\n" "</dl>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_definition_multiples(self): md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = ( "/// define\n" "Apple\n" "\n" "- Pomaceous fruit of plants of the genus Malu in the family Rosaceae.\n" "\n" "Orange\n" "\n" "- The fruit of an evergreen tree of hte genus Citrus.\n" "///\n" ) expected_output = ( "<dl>\n" "<dt>Apple</dt>\n" "<dd>Pomaceous fruit of plants of the genus Malu in the family " "Rosaceae.</dd>\n" "<dt>Orange</dt>\n" "<dd>The fruit of an evergreen tree of hte genus Citrus.</dd>\n" "</dl>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_definition_multiple_terms(self): md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = ( "/// define\n" "Term 1\n" "\n" "Term 2\n" "- Definition a\n" "\n" "Term 3\n" "\n" "- Definition b\n" "///\n" ) expected_output = ( "<dl>\n" "<dt>Term 1</dt>\n" "<dt>Term 2\n" "- Definition a</dt>\n" "<dt>Term 3</dt>\n" "<dd>Definition b</dd>\n" "</dl>" ) self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_html_wrap(self): md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = "/// html | div.my-class\n" "some *markdown* content\n" "///\n" expected_output = '<div class="my-class">\n<p>some <em>markdown</em> content</p>\n</div>' self.assertEqual(expected_output, md.convert(text)) def test_pymdown_in_wiki_renders_block_html_wrap_test_bleach(self): """ The tags get bleached and thus this doesn't work. """ md = markdown.ArticleMarkdown( article=self.root_article, extensions=wiki_plugin.PymdownPlugin.markdown_extensions, ) text = ( "/// html | div[stype='border: 1px solid red;']\n" "some *markdown* content\n" "///\n" ) expected_output = ( "<div>\n<p>some <em>markdown</em> content</p>\n</div>" ) self.assertEqual(expected_output, md.convert(text))
11,824
Python
.py
318
26.531447
98
0.542969
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,260
test_globalhistory.py
django-wiki_django-wiki/tests/plugins/globalhistory/test_globalhistory.py
from django.urls import reverse from django.utils import translation from wiki.models import URLPath from ...base import ArticleWebTestUtils from ...base import DjangoClientTestBase from ...base import RequireRootArticleMixin class GlobalhistoryTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def test_history(self): url = reverse("wiki:globalhistory") url0 = reverse("wiki:globalhistory", kwargs={"only_last": "0"}) url1 = reverse("wiki:globalhistory", kwargs={"only_last": "1"}) response = self.client.get(url) expected = "(?s).*Root Article.*no log message.*" self.assertRegex(response.rendered_content, expected) URLPath.create_urlpath( URLPath.root(), "testhistory1", title="TestHistory1", content="a page", user_message="Comment 1", ) response = self.client.get(url) expected = ( "(?s).*TestHistory1.*Comment 1.*" "Root Article.*no log message.*" ) self.assertRegex(response.rendered_content, expected) urlpath = URLPath.create_urlpath( URLPath.root(), "testhistory2", title="TestHistory2", content="a page", user_message="Comment 2", ) expected = ( "(?s).*TestHistory2.*Comment 2.*" "TestHistory1.*Comment 1.*" "Root Article.*no log message.*" ) response = self.client.get(url) self.assertRegex(response.rendered_content, expected) response = self.client.get(url0) self.assertRegex(response.rendered_content, expected) response = self.client.get(url1) self.assertRegex(response.rendered_content, expected) response = self.client.post( reverse("wiki:edit", kwargs={"path": "testhistory2/"}), { "content": "a page modified", "current_revision": str(urlpath.article.current_revision.id), "preview": "0", "save": "1", "summary": "Testing Revision", "title": "TestHistory2Mod", }, ) expected = ( "(?s).*TestHistory2Mod.*Testing Revision.*" "TestHistory2.*Comment 2.*" "TestHistory1.*Comment 1.*" "Root Article.*no log message.*" ) response = self.client.get(url) self.assertRegex(response.rendered_content, expected) response = self.client.get(url0) self.assertRegex(response.rendered_content, expected) expected = ( "(?s).*TestHistory2Mod.*Testing Revision.*" "TestHistory1.*Comment 1.*" "Root Article.*no log message.*" ) response = self.client.get(url1) self.assertRegex(response.rendered_content, expected) def test_translation(self): # Test that translation of "List of %s changes in the wiki." exists. url = reverse("wiki:globalhistory") response_en = self.client.get(url) self.assertIn("Global history", response_en.rendered_content) self.assertIn("in the wiki", response_en.rendered_content) with translation.override("da-DK"): response_da = self.client.get(url) self.assertNotIn("Global history", response_da.rendered_content) self.assertNotIn("in the wiki", response_da.rendered_content)
3,496
Python
.py
84
31.488095
78
0.605829
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,261
test_forms.py
django-wiki_django-wiki/tests/plugins/notifications/test_forms.py
from django.test import TestCase from wiki.plugins.notifications.forms import SettingsFormSet from tests.base import RequireSuperuserMixin class SettingsFormTests(RequireSuperuserMixin, TestCase): def test_formset(self): SettingsFormSet(user=self.superuser1)
274
Python
.py
6
42.166667
60
0.845283
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,262
test_views.py
django-wiki_django-wiki/tests/plugins/notifications/test_views.py
from django.shortcuts import resolve_url from django_nyt.models import Settings from tests.base import ArticleWebTestUtils from tests.base import DjangoClientTestBase from tests.base import RequireRootArticleMixin class NotificationSettingsTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def setUp(self): super().setUp() def test_login_required(self): self.client.logout() response = self.client.get(resolve_url("wiki:notification_settings")) self.assertEqual(response.status_code, 302) def test_when_logged_in(self): response = self.client.get(resolve_url("wiki:notification_settings")) self.assertEqual(response.status_code, 200) self.assertTemplateUsed( response, "wiki/plugins/notifications/settings.html" ) def test_change_settings(self): self.settings, __ = Settings.objects.get_or_create( user=self.superuser1, is_default=True ) url = resolve_url("wiki:notification_settings") response = self.client.get(url) self.assertEqual(response.status_code, 200) data = {"csrf_token": response.context["csrf_token"]} # management form information, needed because of the formset management_form = response.context["form"].management_form for i in ( "TOTAL_FORMS", "INITIAL_FORMS", "MIN_NUM_FORMS", "MAX_NUM_FORMS", ): data[f"{management_form.prefix}-{i}"] = management_form[i].value() for i in range(response.context["form"].total_form_count()): # get form index 'i' current_form = response.context["form"].forms[i] # retrieve all the fields for field_name in current_form.fields: value = current_form[field_name].value() data[f"{current_form.prefix}-{field_name}"] = ( value if value is not None else "" ) data["form-TOTAL_FORMS"] = 1 data["form-0-email"] = 2 data["form-0-interval"] = 0 # post the request without any change response = self.client.post(url, data, follow=True) self.assertEqual(len(response.context.get("messages")), 1) message = response.context.get("messages")._loaded_messages[0] self.assertIn( message.message, "You will receive notifications instantly for 0 articles", ) # Ensure we didn't create redundant Settings objects assert self.superuser1.nyt_settings.all().count() == 1
2,628
Python
.py
59
35.050847
78
0.640282
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,263
test_links.py
django-wiki_django-wiki/tests/plugins/links/test_links.py
import markdown from ddt import data from ddt import ddt from ddt import unpack from django.test import TestCase from django.urls import reverse_lazy from wiki.models import URLPath from wiki.plugins.links.mdx.djangowikilinks import WikiPathExtension from tests.base import wiki_override_settings FIXTURE_POSITIVE_MATCHES_TRAILING_SLASH = [ ( "[Français](wiki:/fr)", '<p><a class="wikipath linknotfound" href="/fr/">Français</a></p>', ), ( # Link to an existing page "[Test link](wiki:/linktest)", '<p><a class="wikipath" href="/linktest/">Test link</a></p>', ), ( # Link with an empty fragment "[Test link](wiki:/linktest#)", '<p><a class="wikipath" href="/linktest/#/">Test link</a></p>', ), ( # Link to a header in an existing page "[Test head](wiki:/linktest#wiki-toc-a-section)", '<p><a class="wikipath" href="/linktest/#wiki-toc-a-section/">Test head</a></p>', ), ( # Link to a header in a non existing page "[Test head nonExist](wiki:/linktesterr#wiki-toc-a-section)", '<p><a class="wikipath linknotfound" href="/linktesterr#wiki-toc-a-section/">Test head nonExist</a></p>', ), ( # Invalid Wiki link: The default markdown link parser takes over "[Test head err](wiki:/linktest#wiki-toc-a-section#err)", '<p><a href="wiki:/linktest#wiki-toc-a-section#err">Test head err</a></p>', ), ] FIXTURE_POSITIVE_MATCHES_NO_TRAILING_SLASH = [ ( "[Français](wiki:/fr)", '<p><a class="wikipath linknotfound" href="/fr">Français</a></p>', ), ( # Link to an existing page "[Test link](wiki:/linktest)", '<p><a class="wikipath" href="/linktest">Test link</a></p>', ), ( # Relative path "[Test link](wiki:linktest)", '<p><a class="wikipath" href="/linktest">Test link</a></p>', ), ( # Link with an empty fragment "[Test link](wiki:/linktest#)", '<p><a class="wikipath" href="/linktest/#">Test link</a></p>', ), ( # Link to a header in an existing page "[Test head](wiki:/linktest#wiki-toc-a-section)", '<p><a class="wikipath" href="/linktest/#wiki-toc-a-section">Test head</a></p>', ), ( # Link to a header in a non existing page "[Test head nonExist](wiki:/linktesterr#wiki-toc-a-section)", '<p><a class="wikipath linknotfound" href="/linktesterr#wiki-toc-a-section">Test head nonExist</a></p>', ), ( # Invalid Wiki link: The default markdown link parser takes over "[Test head err](wiki:/linktest#wiki-toc-a-section#err)", '<p><a href="wiki:/linktest#wiki-toc-a-section#err">Test head err</a></p>', ), ] @ddt class WikiPathExtensionTests(TestCase): """ Test the wikilinks markdown plugin. I could not get it to work with `@pytest.mark.parametrize` so using `ddt` instead """ def setUp(self): config = (("base_url", reverse_lazy("wiki:get", kwargs={"path": ""})),) URLPath.create_root() urlpath = URLPath.create_urlpath( URLPath.root(), "linktest", title="LinkTest", content="A page\n#A section\nA line", user_message="Comment1", ) # TODO: Use wiki.core.markdown.article_markdown self.md = markdown.Markdown( extensions=["extra", WikiPathExtension(config)] ) self.md.article = urlpath.article @wiki_override_settings(WIKI_WIKILINKS_TRAILING_SLASH=True) @data(*FIXTURE_POSITIVE_MATCHES_TRAILING_SLASH) @unpack def test_works_with_lazy_functions_slashes( self, markdown_input, expected_output ): self.assertEqual( self.md.convert(markdown_input), expected_output, ) @wiki_override_settings(WIKI_WIKILINKS_TRAILING_SLASH=False) @data(*FIXTURE_POSITIVE_MATCHES_NO_TRAILING_SLASH) @unpack def test_works_with_lazy_functions_no_slashes( self, markdown_input, expected_output ): self.assertEqual( self.md.convert(markdown_input), expected_output, )
4,235
Python
.py
117
29.188034
113
0.611152
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,264
test_urlize.py
django-wiki_django-wiki/tests/plugins/links/test_urlize.py
import html import markdown import pytest from wiki.plugins.links.mdx.urlize import makeExtension from wiki.plugins.links.mdx.urlize import UrlizeExtension # Template accepts two strings - href value and link text value. EXPECTED_LINK_TEMPLATE = ( '<a href="%s" rel="nofollow" target="_blank">' '<span class="fa fa-external-link-alt">' "</span>" "<span>" " %s" "</span>" "</a>" ) # Template accepts two strings - href value and link text value. EXPECTED_PARAGRAPH_TEMPLATE = "<p>%s</p>" % EXPECTED_LINK_TEMPLATE FIXTURE_POSITIVE_MATCHES = [ # Test surrounding begin/end characters. ( "(example.com)", "<p>(" + EXPECTED_LINK_TEMPLATE % ("http://example.com", "example.com") + ")</p>", ), ( "<example.com>", "<p>&lt;" + EXPECTED_LINK_TEMPLATE % ("http://example.com", "example.com") + "&gt;</p>", ), # Test protocol specification. ( "http://example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("http://example.com", "http://example.com"), ), ( "https://example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("https://example.com", "https://example.com"), ), ( "ftp://example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("ftp://example.com", "ftp://example.com"), ), ( "ftps://example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("ftps://example.com", "ftps://example.com"), ), ( "example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("http://example.com", "example.com"), ), ( "onion://example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("onion://example.com", "onion://example.com"), ), ( "onion9+.-://example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("onion9+.-://example.com", "onion9+.-://example.com"), ), # Test various supported host variations. ( "10.10.1.1", EXPECTED_PARAGRAPH_TEMPLATE % ("http://10.10.1.1", "10.10.1.1"), ), ( "1122:3344:5566:7788:9900:aabb:ccdd:eeff", EXPECTED_PARAGRAPH_TEMPLATE % ( "http://1122:3344:5566:7788:9900:aabb:ccdd:eeff", "1122:3344:5566:7788:9900:aabb:ccdd:eeff", ), ), ( "1122:3344:5566:7788:9900:AaBb:cCdD:EeFf", EXPECTED_PARAGRAPH_TEMPLATE % ( "http://1122:3344:5566:7788:9900:AaBb:cCdD:EeFf", "1122:3344:5566:7788:9900:AaBb:cCdD:EeFf", ), ), ("::1", EXPECTED_PARAGRAPH_TEMPLATE % ("http://::1", "::1")), ("1::2:3", EXPECTED_PARAGRAPH_TEMPLATE % ("http://1::2:3", "1::2:3")), ("1::", EXPECTED_PARAGRAPH_TEMPLATE % ("http://1::", "1::")), ("::", EXPECTED_PARAGRAPH_TEMPLATE % ("http://::", "::")), ( "example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("http://example.com", "example.com"), ), ( "example.horse", EXPECTED_PARAGRAPH_TEMPLATE % ("http://example.horse", "example.horse"), ), ( "my.long.domain.example.com", EXPECTED_PARAGRAPH_TEMPLATE % ("http://my.long.domain.example.com", "my.long.domain.example.com"), ), # Test port section. ( "10.1.1.1:8000", EXPECTED_PARAGRAPH_TEMPLATE % ("http://10.1.1.1:8000", "10.1.1.1:8000"), ), # Test trailing path specification. ( "http://example.com/", EXPECTED_PARAGRAPH_TEMPLATE % ("http://example.com/", "http://example.com/"), ), ( "http://example.com/my/path", EXPECTED_PARAGRAPH_TEMPLATE % ("http://example.com/my/path", "http://example.com/my/path"), ), ( "http://example.com/my/path?param1=value1&param2=value2", EXPECTED_PARAGRAPH_TEMPLATE % ( "http://example.com/my/path?param1=value1&amp;param2=value2", "http://example.com/my/path?param1=value1&amp;param2=value2", ), ), # Link positioned somewhere within the text, but around whitespace boundary. ( "This is link myhost.example.com", "<p>This is link " + EXPECTED_LINK_TEMPLATE % ("http://myhost.example.com", "myhost.example.com") + "</p>", ), ( "myhost.example.com is the link", "<p>" + EXPECTED_LINK_TEMPLATE % ("http://myhost.example.com", "myhost.example.com") + " is the link</p>", ), ( "I have best myhost.example.com link ever", "<p>I have best " + EXPECTED_LINK_TEMPLATE % ("http://myhost.example.com", "myhost.example.com") + " link ever</p>", ), ( "I have best\nmyhost.example.com link ever", "<p>I have best\n" + EXPECTED_LINK_TEMPLATE % ("http://myhost.example.com", "myhost.example.com") + " link ever</p>", ), ] FIXTURE_NEGATIVE_MATCHES = [ # localhost as part of another word. ("localhosts", "<p>localhosts</p>"), ("localhost", "<p>localhost</p>"), ("localhost:8000", "<p>localhost:8000</p>"), # Incomplete FQDNs. ("example.", "<p>example.</p>"), (".example .com", "<p>.example .com</p>"), # Invalid FQDNs. ("example-.com", "<p>example-.com</p>"), ("-example.com", "<p>-example.com</p>"), ("my.-example.com", "<p>my.-example.com</p>"), # Invalid IPv6 patterns. ( "1:2:3:4:5:6:7:8:a", # Use :a, because using a number would match as optional port "<p>1:2:3:4:5:6:7:8:a</p>", ), ( "1::2::3", "<p>1::2::3</p>", ), ( "::::1", "<p>::::1</p>", ), ( "1::::", "<p>1::::</p>", ), # Invalid IPv4 patterns. ( "1.2.3.4.5", "<p>1.2.3.4.5</p>", ), # Invalid protocols. ( "9onion://example.com", "<p>9onion://example.com</p>", ), ( "-onion://example.com", "<p>-onion://example.com</p>", ), ( "+onion://example.com", "<p>+onion://example.com</p>", ), ( ".onion://example.com", "<p>.onion://example.com</p>", ), ] class TestUrlizeExtension: def setup_method(self): self.md = markdown.Markdown(extensions=[UrlizeExtension()]) @pytest.mark.parametrize( "markdown_text, expected_output", FIXTURE_POSITIVE_MATCHES ) def test_positive_matches(self, markdown_text, expected_output): assert self.md.convert(markdown_text) == expected_output @pytest.mark.parametrize( "markdown_text, expected_output", FIXTURE_NEGATIVE_MATCHES ) def test_negative_matches(self, markdown_text, expected_output): assert self.md.convert(markdown_text) == expected_output def test_url_with_non_matching_begin_and_end_ignored(self): assert self.md.convert("(example.com>") == "<p>%s</p>" % html.escape( "(example.com>" ) assert self.md.convert("<example.com)") == "<p>%s</p>" % html.escape( "<example.com)" ) assert self.md.convert("(example.com") == "<p>%s</p>" % html.escape( "(example.com" ) assert self.md.convert("example.com)") == "<p>%s</p>" % html.escape( "example.com)" ) assert self.md.convert("<example.com") == "<p>%s</p>" % html.escape( "<example.com" ) assert self.md.convert("example.com>") == "<p>%s</p>" % html.escape( "example.com>" ) def test_makeExtension_return_value(): extension = makeExtension() assert isinstance(extension, UrlizeExtension)
7,617
Python
.py
247
23.801619
91
0.544935
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,265
test_commands.py
django-wiki_django-wiki/tests/plugins/attachments/test_commands.py
import os import tempfile from wiki.models import URLPath from wiki.plugins.attachments import models from tests.core.test_commands import TestManagementCommands class TestAttachmentManagementCommands(TestManagementCommands): """ Add some more data """ def setUp(self): super().setUp() self.test_file = tempfile.NamedTemporaryFile( "w", delete=False, suffix=".txt" ) self.test_file.write("test") self.child1 = URLPath.create_urlpath( self.root, "test-slug", title="Test 1" ) self.attachment1 = models.Attachment.objects.create( article=self.child1.article ) self.attachment1_revision1 = models.AttachmentRevision.objects.create( attachment=self.attachment1, file=self.test_file.name, ) def tearDown(self): os.unlink(self.test_file.name) super().tearDown()
942
Python
.py
28
26
78
0.661504
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,266
test_views.py
django-wiki_django-wiki/tests/plugins/attachments/test_views.py
from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from django.urls import reverse from wiki.models import URLPath from ...base import ArticleWebTestUtils from ...base import DjangoClientTestBase from ...base import RequireRootArticleMixin class AttachmentTests( RequireRootArticleMixin, ArticleWebTestUtils, DjangoClientTestBase ): def setUp(self): super().setUp() self.article = self.root_article self.test_data = "This is a plain text file" self.test_description = "My file" def _createTxtFilestream(self, strData, **kwargs): """ Helper function to create filestream for upload. Parameters : strData : str, test string data Optional Arguments : filename : str, Defaults to 'test.txt' """ filename = kwargs.get("filename", "test.txt") data = strData.encode("utf-8") filedata = BytesIO(data) filestream = InMemoryUploadedFile( filedata, None, filename, "text", len(data), None ) return filestream def _create_test_attachment(self, path): url = reverse("wiki:attachments_index", kwargs={"path": path}) filestream = self._createTxtFilestream(self.test_data) response = self.client.post( url, { "description": self.test_description, "file": filestream, "save": "1", }, ) self.assertRedirects(response, url) def test_upload(self): """ Tests that simple file upload uploads correctly Uploading a file should preserve the original filename. Uploading should not modify file in any way. """ self._create_test_attachment("") # Check the object was created. attachment = self.article.shared_plugins_set.all()[0].attachment self.assertEqual(attachment.original_filename, "test.txt") self.assertEqual( attachment.current_revision.file.file.read(), self.test_data.encode("utf-8"), ) def test_replace(self): """ Tests that previous revisions are not deleted Tests that only the most recent revision is deleted when "replace" is checked. """ # Upload initial file url = reverse("wiki:attachments_index", kwargs={"path": ""}) data = "This is a plain text file" filestream = self._createTxtFilestream(data) self.client.post( url, {"description": "My file", "file": filestream, "save": "1"} ) attachment = self.article.shared_plugins_set.all()[0].attachment # uploading for the first time should mean that there is only one revision. self.assertEqual(attachment.attachmentrevision_set.count(), 1) # Change url to replacement page. url = reverse( "wiki:attachments_replace", kwargs={ "attachment_id": attachment.id, "article_id": self.article.id, }, ) # Upload replacement without removing revisions replacement_data = data + " And this is my edit" replacement_filestream = self._createTxtFilestream(replacement_data) self.client.post( url, { "description": "Replacement upload", "file": replacement_filestream, }, ) attachment = self.article.shared_plugins_set.all()[0].attachment # Revision count should be two self.assertEqual(attachment.attachmentrevision_set.count(), 2) # Original filenames should not be modified self.assertEqual(attachment.original_filename, "test.txt") # Latest revision should equal replacment_data self.assertEqual( attachment.current_revision.file.file.read(), replacement_data.encode("utf-8"), ) first_replacement = attachment.current_revision # Upload another replacement, this time removing most recent revision replacement_data2 = data + " And this is a different edit" replacement_filestream2 = self._createTxtFilestream(replacement_data2) self.client.post( url, { "description": "Replacement upload", "file": replacement_filestream2, "replace": "on", }, ) attachment = self.article.shared_plugins_set.all()[0].attachment # Revision count should still be two self.assertEqual(attachment.attachmentrevision_set.count(), 2) # Latest revision should equal replacment_data2 self.assertEqual( attachment.current_revision.file.file.read(), replacement_data2.encode("utf-8"), ) # The first replacement should no longer be in the filehistory self.assertNotIn( first_replacement, attachment.attachmentrevision_set.all() ) def test_search(self): """ Call the search view """ self._create_test_attachment("") url = reverse("wiki:attachments_search", kwargs={"path": ""}) response = self.client.get(url, {"query": self.test_description}) self.assertContains(response, self.test_description) def get_article(self, cont): urlpath = URLPath.create_urlpath( URLPath.root(), "html_attach", title="TestAttach", content=cont ) self._create_test_attachment(urlpath.path) return urlpath.article.render() def test_render(self): output = self.get_article("[attachment:1]") expected = ( r'<span class="attachment"><a href=".*attachments/download/1/"' r' title="Click to download test\.txt">\s*test\.txt\s*</a>' ) self.assertRegex(output, expected) def test_render_missing(self): output = self.get_article("[attachment:2]") expected = r'<span class="attachment attachment-deleted">\s*Attachment with ID #2 is deleted.\s*</span>' self.assertRegex(output, expected) def test_render_title(self): output = self.get_article('[attachment:1 title:"Test title"]') expected = ( r'<span class="attachment"><a href=".*attachments/download/1/"' r' title="Click to download test\.txt">\s*Test title\s*</a>' ) self.assertRegex(output, expected) def test_render_title_size(self): output = self.get_article('[attachment:1 title:"Test title 2" size]') expected = ( r'<span class="attachment"><a href=".*attachments/download/1/"' r' title="Click to download test\.txt">\s*Test title 2 \[25[^b]bytes\]\s*</a>' ) self.assertRegex(output, expected)
6,852
Python
.py
163
32.472393
112
0.620183
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,267
test_models.py
django-wiki_django-wiki/tests/plugins/attachments/test_models.py
from wiki.plugins.attachments.models import Attachment from wiki.plugins.attachments.models import AttachmentRevision from tests.base import RequireRootArticleMixin from tests.base import TestBase class AttachmentRevisionTests(RequireRootArticleMixin, TestBase): def setUp(self): super().setUp() self.attachment = Attachment.objects.create( article=self.root_article, original_filename="blah.txt", ) self.revision = AttachmentRevision.objects.create( attachment=self.attachment, file=None, description="muh", revision_number=1, ) def test_revision_no_file(self): # Intentionally, there are no asserts, as the test just needs to # target an if-branch in the pre-delete signal for AttachmentRevision self.revision.delete() def test_revision_file_size(self): self.assertIsNone(self.revision.get_size()) def test_get_filename_no_file(self): self.assertIsNone(self.revision.get_filename()) def test_str(self): self.assertEqual( str(self.revision), "%s: %s (r%d)" % ( "Root Article", "blah.txt", 1, ), )
1,289
Python
.py
35
27.514286
77
0.630313
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,268
manage.py
django-wiki_django-wiki/testproject/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
254
Python
.py
7
33.142857
75
0.741803
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,269
urls.py
django-wiki_django-wiki/testproject/testproject/urls.py
from django.conf import settings from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http.response import HttpResponse from django.urls import include from django.urls import re_path from django.views.static import serve as static_serve admin.autodiscover() urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^robots.txt", lambda _: HttpResponse("User-agent: *\nDisallow: /")), ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() urlpatterns += [ re_path( r"^media/(?P<path>.*)$", static_serve, {"document_root": settings.MEDIA_ROOT}, ), ] if settings.DEBUG: try: import debug_toolbar urlpatterns = [ re_path("__debug__/", include(debug_toolbar.urls)), # For django versions before 2.0: # url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns except ImportError: pass urlpatterns += [ re_path(r"^notify/", include("django_nyt.urls")), re_path(r"", include("wiki.urls")), ] handler500 = "testproject.views.server_error" handler404 = "testproject.views.page_not_found"
1,226
Python
.py
37
27.72973
82
0.664975
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,270
middleware.py
django-wiki_django-wiki/testproject/testproject/middleware.py
from django.contrib import messages MSG = ( "This is a Django-Wiki demo, every 2 hours all data is removed from the server. " "If you want to test something try login with admin:admin - " "Please be respectful with the other visitors." ) class DemoMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. demo_message_exists = False storage = messages.get_messages(request) for message in storage: if str(message) == MSG: demo_message_exists = True storage.used = False if not demo_message_exists: messages.add_message(request, messages.WARNING, MSG) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response
989
Python
.py
24
33.333333
85
0.655858
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,271
wsgi.py
django-wiki_django-wiki/testproject/testproject/wsgi.py
""" WSGI config for testproject project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import sys from django.core.wsgi import get_wsgi_application # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. PROJECT_PATH = os.path.abspath(os.path.split(__file__)[0]) PROJECT_PARENT = os.path.abspath(os.path.split(PROJECT_PATH)[0]) sys.path.append(PROJECT_PATH) sys.path.append(PROJECT_PARENT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
1,344
Python
.py
27
48.444444
79
0.81422
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,272
views.py
django-wiki_django-wiki/testproject/testproject/views.py
from django.conf import settings from django.shortcuts import render from django.views.decorators.csrf import requires_csrf_token @requires_csrf_token def server_error(request, template_name="500.html", **param_dict): return render( request, template_name, context={ "MEDIA_URL": settings.MEDIA_URL, "STATIC_URL": settings.STATIC_URL, "request": request, }, status=500, ) def page_not_found(request, template_name="404.html", exception=None): response = server_error(request, template_name=template_name, exception=exception) response.status_code = 404 return response
669
Python
.py
19
28.947368
86
0.688854
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,273
demo.py
django-wiki_django-wiki/testproject/testproject/settings/demo.py
from .base import * # noqa DEBUG = False ALLOWED_HOSTS = [".demo.django-wiki.org"] SESSION_COOKIE_DOMAIN = ".demo.django-wiki.org" SESSION_COOKIE_SECURE = True MIDDLEWARE += ["testproject.middleware.DemoMiddleware"]
220
Python
.py
6
35.166667
55
0.763033
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,274
local.py
django-wiki_django-wiki/testproject/testproject/settings/local.py
# Add your own changes here -- but do not push to remote!! # After changing the file, from root of repository execute: # git update-index --assume-unchanged testproject/testproject/settings/local.py from .dev import * # noqa @UnusedWildImport
244
Python
.py
4
60
79
0.779167
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,275
dev.py
django-wiki_django-wiki/testproject/testproject/settings/dev.py
from .base import * # noqa @UnusedWildImport from .demo import * # noqa @UnusedWildImport DEBUG = True for template_engine in TEMPLATES: template_engine["OPTIONS"]["debug"] = True EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" # Used by debug_toolbar INTERNAL_IPS = ["127.0.0.1"] ALLOWED_HOSTS = [ "localhost", "0.0.0.0", "127.0.0.1", ] # Removed. # See: https://forum.djangoproject.com/t/why-are-cookie-secure-settings-defaulted-to-false/1133/4 # and https://github.com/django-wiki/django-wiki/pull/1325 # SESSION_COOKIE_DOMAIN = ".localhost" SESSION_COOKIE_SECURE = False try: import debug_toolbar # @UnusedImport MIDDLEWARE = list(MIDDLEWARE) + [ "debug_toolbar.middleware.DebugToolbarMiddleware", ] INSTALLED_APPS = list(INSTALLED_APPS) + ["debug_toolbar"] DEBUG_TOOLBAR_CONFIG = {"INTERCEPT_REDIRECTS": False} except ImportError: pass
917
Python
.py
27
30.888889
97
0.725624
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,276
codehilite.py
django-wiki_django-wiki/testproject/testproject/settings/codehilite.py
from testproject.settings import * from testproject.settings.local import * # Test codehilite with pygments WIKI_MARKDOWN_KWARGS = { "extensions": [ "codehilite", "footnotes", "attr_list", "headerid", "extra", ] }
264
Python
.py
12
16.833333
40
0.628
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,277
sendfile.py
django-wiki_django-wiki/testproject/testproject/settings/sendfile.py
from .base import * # noqa @UnusedWildImport INSTALLED_APPS += ["sendfile"] WIKI_ATTACHMENTS_USE_SENDFILE = True SENDFILE_BACKEND = "sendfile.backends.development" # SENDFILE_URL = None #Not needed # SENDFILE_ROOT = None #Not needed
238
Python
.py
6
38
50
0.77193
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,278
__init__.py
django-wiki_django-wiki/testproject/testproject/settings/__init__.py
try: from .local import * except ImportError: from .base import *
74
Python
.py
4
15.5
24
0.7
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,279
base.py
django-wiki_django-wiki/testproject/testproject/settings/base.py
import os from django.urls import reverse_lazy PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "b^fv_)t39h%9p40)fnkfblo##jkr!$0)lkp6bpy!fi*f$4*92!" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.humanize.apps.HumanizeConfig", "django.contrib.auth.apps.AuthConfig", "django.contrib.contenttypes.apps.ContentTypesConfig", "django.contrib.sessions.apps.SessionsConfig", "django.contrib.sites.apps.SitesConfig", "django.contrib.messages.apps.MessagesConfig", "django.contrib.staticfiles.apps.StaticFilesConfig", "django.contrib.admin.apps.AdminConfig", "django.contrib.admindocs.apps.AdminDocsConfig", "sekizai", "sorl.thumbnail", "django_nyt.apps.DjangoNytConfig", "wiki.apps.WikiConfig", "wiki.plugins.images.apps.ImagesConfig", "wiki.plugins.links.apps.LinksConfig", "wiki.plugins.macros.apps.MacrosConfig", "wiki.plugins.attachments.apps.AttachmentsConfig", "wiki.plugins.notifications.apps.NotificationsConfig", "wiki.plugins.editsection.apps.EditSectionConfig", "wiki.plugins.globalhistory.apps.GlobalHistoryConfig", "wiki.plugins.pymdown.apps.PyMdownConfig", "wiki.plugins.help.apps.HelpConfig", "mptt", ] TEST_RUNNER = "django.test.runner.DiscoverRunner" MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "testproject.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(PROJECT_DIR, "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.contrib.auth.context_processors.auth", "django.template.context_processors.debug", "django.template.context_processors.i18n", "django.template.context_processors.request", "django.template.context_processors.tz", "django.contrib.messages.context_processors.messages", "sekizai.context_processors.sekizai", ], "debug": DEBUG, }, }, ] WSGI_APPLICATION = "testproject.wsgi.application" LOGIN_REDIRECT_URL = reverse_lazy("wiki:get", kwargs={"path": ""}) # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(PROJECT_DIR, "db.sqlite3"), } } # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ TIME_ZONE = "Europe/Berlin" # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = "en-US" SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = "/static/" STATIC_ROOT = os.path.join(PROJECT_DIR, "static") MEDIA_ROOT = os.path.join(PROJECT_DIR, "media") MEDIA_URL = "/media/" WIKI_ANONYMOUS_WRITE = True WIKI_ANONYMOUS_CREATE = False SESSION_COOKIE_SECURE = True DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
3,874
Python
.py
98
34.530612
73
0.719284
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,280
customauthuser.py
django-wiki_django-wiki/testproject/testproject/settings/customauthuser.py
import os # noqa @UnusedImport import sys from .base import * # noqa @UnusedWildImport from .dev import * # Append testdata path sys.path.append(os.path.join(os.path.dirname(os.path.dirname(PROJECT_DIR)), "tests")) DATABASES = { "default": { # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. "ENGINE": "django.db.backends.sqlite3", # Or path to database file if using sqlite3. "NAME": os.path.join(PROJECT_DIR, "prepopulated-customauthuser.sqlite3"), } } INSTALLED_APPS = INSTALLED_APPS + [ # Test application for testing custom users "testdata", ] AUTH_USER_MODEL = "testdata.CustomUser"
656
Python
.py
19
30.684211
85
0.697306
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,281
_stacked.scss
django-wiki_django-wiki/src/wiki/static/wiki/font-awesome/scss/_stacked.scss
// Stacked Icons // ------------------------- .#{$fa-css-prefix}-stack { display: inline-block; height: 2em; line-height: 2em; position: relative; vertical-align: middle; width: ($fa-fw-width*2); } .#{$fa-css-prefix}-stack-1x, .#{$fa-css-prefix}-stack-2x { left: 0; position: absolute; text-align: center; width: 100%; } .#{$fa-css-prefix}-stack-1x { line-height: inherit; } .#{$fa-css-prefix}-stack-2x { font-size: 2em; } .#{$fa-css-prefix}-inverse { color: $fa-inverse; }
505
Python
.tac
26
17.230769
29
0.620253
django-wiki/django-wiki
1,819
569
48
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,282
build.py
simonwagner_mergepbx/build.py
#! /usr/bin/env python #This script builds a standalone version of mergepbx.py #all scripts are bundled into one single file that can be easily distributed #the user will only need the file generated by this script and he can execute #it like any other program #idea: http://code.activestate.com/recipes/215301/ import zipfile import tempfile from ConfigParser import SafeConfigParser from ConfigParser import NoOptionError from collections import namedtuple import os import stat import sys import fnmatch #templates HEADER = \ """\ #!/bin/sh PYTHON=$(which python 2>/dev/null) if [ ! -x "$PYTHON" ] ; then echo "Python executable not found - can't continue!" echo "Please install Python (>= 2.3) to run this program" exit 1 fi read -r -d '' PYTHON_CODE << END_OF_PYTHON_CODE import sys sys.path.insert(0, sys.argv[1]) del sys.argv[0:1] import %(mainmodule)s %(mainmodule)s.main() END_OF_PYTHON_CODE exec $PYTHON -c "${PYTHON_CODE}" "${0}" "${@}" """ class Manifest(object): ModuleFile = namedtuple("ModuleFile", ("file_path", "egg_path")) def __init__(self, mainmodule, files, default_target=None): self.mainmodule = mainmodule self.files = files self._default_target = default_target def iterfiles(self): return iter(self.files) def default_target(self): return self._default_target @staticmethod def read(fpath): config = SafeConfigParser() config.read(fpath) mainmodule = config.get("build", "mainmodule") mainmodule_path = config.get("build", "mainmodule_path") modules = config.get("build", "modules").split(",") try: default_target = config.get("build", "default_target") except NoOptionError: default_target = None print modules #add modules files = [] for module in modules: path = config.get(module, "path") files += Manifest._get_module_files(module, path) #add main module files += [Manifest.ModuleFile(mainmodule_path, mainmodule + ".py")] return Manifest(mainmodule, files, default_target) @staticmethod def _get_module_files(module, path): module_files = [] for (dir_path, dirs, files) in os.walk(path): python_files = fnmatch.filter(files, "*.py") python_files = [os.path.join(dir_path, file) for file in python_files] egg_python_files = [Manifest._get_egg_path(module, path, python_file) for python_file in python_files] module_files += [Manifest.ModuleFile(python_file, egg_python_file) for python_file, egg_python_file in zip(python_files, egg_python_files)] return module_files @staticmethod def _get_egg_path(module, module_path, file_path): rel_file_path = os.path.relpath(file_path, module_path) rel_file_path = os.path.normpath(rel_file_path) egg_path_components = [module] + rel_file_path.split(os.sep) egg_path = str.join("/", egg_path_components) return egg_path def main(): #default settings target_file = None manifest_file = "MANIFEST" if len(sys.argv) >= 2: target_file = sys.argv[1] if len(sys.argv) >= 3: manifest_file = sys.argv[2] manifest = Manifest.read(manifest_file) if not target_file: target_file = manifest.default_target() if not target_file: sys.stderr.write("please specify a target by using: ./build.py target\n") sys.exit(os.EX_USAGE) build(target_file, manifest) def build(target_file, manifest): pack_egg(target_file, manifest) def pack_egg(target_file, manifest): zip_fd, zip_path = tempfile.mkstemp() egg = zipfile.ZipFile(zip_path, "w") for file_path, egg_path in manifest.iterfiles(): print "adding %s as %s" % (file_path, egg_path) egg.write(file_path, egg_path) egg.close() target = open(target_file, "w") eggf = open(zip_path, "r") target.write(HEADER % { "mainmodule" : manifest.mainmodule }) target.write(eggf.read()) target.close() eggf.close() egg_permissions = os.stat(target_file).st_mode os.chmod(target_file, egg_permissions | (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)) if __name__ == "__main__": main()
4,344
Python
.py
116
31.525862
151
0.659752
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,283
test_pbxmerge.py
simonwagner_mergepbx/test/test_pbxmerge.py
import sys if sys.version_info >= (2,7): import unittest else: import unittest2 as unittest import os try: from cStringIO import StringIO except: from StringIO import StringIO import difflib from itertools import chain import pbxproj import pbxproj.merge.pbxmerge as pbxmerge from pbxproj.merge import merge_pbxs import pbxproj.isa as isa from testhelpers import fixture_path, make_logger, listpath, wrap_with_codec def first(iterable, predicate, default=None): for item in iterable: if predicate(item): return item return default def load_merge_task(files_to_be_merged): postfixes = (".base", ".mine", ".theirs", ".merged") base, mine, theirs, merged = (first( files_to_be_merged, lambda file: file.endswith(postfix), None) for postfix in postfixes) return (base, mine, theirs, merged) class PBXMergeTest(unittest.TestCase): def __init__(self, *args, **kwargs): super(PBXMergeTest, self).__init__(*args, **kwargs) self.logger = make_logger(self.__class__) def test_check_available_merger(self): isa_names = isa.ISA_MAPPING.keys() expected_mergers = set(isa_name + "Merger3" for isa_name in isa_names) - set(("PBXISAMerger3",)) available_merger_names = set(pbxmerge.MERGER_MAPPING.keys()) for expected_merger in expected_mergers: self.assertIn(expected_merger, available_merger_names, "Missing merger %s" % expected_merger) def test_merge_fixtures(self): merge_fixtures_path = fixture_path("merge") merge_projects = listpath(merge_fixtures_path) merge_tasks = [listpath(merge_project) for merge_project in merge_projects] for merge_task in chain.from_iterable(merge_tasks): task_files = listpath(merge_task) project_files = load_merge_task(task_files) self.logger.info("merging base %s with my %s and their %s and comparing with %s..." % project_files) projects = [pbxproj.read(project_file) for project_file in project_files] base, mine, theirs, merged = projects merged_buffer = StringIO() merged_buffer = wrap_with_codec(merged_buffer, codec=base.get_encoding()) merged_project = merge_pbxs(base, mine, theirs) pbxproj.write(merged_buffer, merged_project) #now compare the content of the written file with the original file #this should stay the same expected_merged_content = open(project_files[-1]).read() merged_content = merged_buffer.getvalue() merged_buffer.close() #if assert will fail, generate a diff for this failure if not merged_content == expected_merged_content: self.logger.error("failed to generate an exact replica, diff follows:") diff_lines = difflib.unified_diff(expected_merged_content.splitlines(), merged_content.splitlines()) for line in diff_lines: self.logger.error(line) self.assertEquals(merged_content, expected_merged_content, "%s was not correctly merged" % merge_task) if __name__ == '__main__': unittest.main()
3,376
Python
.py
69
38.811594
116
0.638298
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,284
test_pbxparsing.py
simonwagner_mergepbx/test/test_pbxparsing.py
import sys import logging import os try: from cStringIO import StringIO except: from StringIO import StringIO if sys.version_info >= (2,7): import unittest else: import unittest2 as unittest import pbxproj from testhelpers import fixture_path, make_logger, listpath, wrap_with_codec from orderedset import OrderedSet from collections import OrderedDict import difflib class PBXParsingTest(unittest.TestCase): def __init__(self, *args, **kwargs): super(PBXParsingTest, self).__init__(*args, **kwargs) self.logger = make_logger(self.__class__) def test_fixtures(self): parsing_fixtures_path = fixture_path("parse") project_files = [file for file in listpath(parsing_fixtures_path) if file.endswith(".pbxproj")] self.logger.debug("parsing %d files..." % len(project_files)) for project_file in project_files: self.logger.debug("trying to parse file %s" % project_file) data = pbxproj.read(project_file) f_o = wrap_with_codec(StringIO(), data.get_encoding()) pbxproj.write(f_o, data) #now compare the content of the written file with the original file #this should stay the same original_content = open(project_file).read() new_content = f_o.getvalue() f_o.close() #if assert will fail, generate a diff for this failure if not new_content == original_content: self.logger.error("failed to generate an exact replica, diff follows:") diff_lines = difflib.unified_diff(original_content.splitlines(), new_content.splitlines()) for line in diff_lines: self.logger.error(line) self.assertEquals(new_content, original_content, "%s was not correctly parsed" % project_file)
1,857
Python
.py
41
37.097561
106
0.664266
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,285
test_dictionaryboundobject.py
simonwagner_mergepbx/test/test_dictionaryboundobject.py
import sys if sys.version_info >= (2,7): import unittest else: import unittest2 as unittest from pbxproj.core import DictionaryBoundObject class DictionaryBoundObjectTest(unittest.TestCase): def test_readValue(self): data = {"a": "hello", "b" : "world"} boundObj = DictionaryBoundObject(data) self.assertEquals("hello", boundObj.a) self.assertEquals("world", boundObj.b) def test_writeValue(self): data = {"a": "hello", "b" : "world"} boundObj = DictionaryBoundObject(data) boundObj.b = "simon" self.assertEquals("simon", boundObj.b) self.assertEquals("simon", data["b"])
665
Python
.py
18
30.777778
51
0.665109
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,286
test_orderedset.py
simonwagner_mergepbx/test/test_orderedset.py
from orderedset import OrderedSet import sys if sys.version_info >= (2,7): import unittest else: import unittest2 as unittest class TokenStreamTest(unittest.TestCase): def test_clear(self): s = OrderedSet((1,2,3,4)) s.clear() def test_weakref(self): s = OrderedSet((1,2,3,4)) actual = list(s) self.assertEqual(actual , [1,2,3,4]) if __name__ == '__main__': unittest.main()
438
Python
.py
16
22.3125
44
0.633094
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,287
test_plist_nextstep.py
simonwagner_mergepbx/test/test_plist_nextstep.py
import sys from StringIO import StringIO if sys.version_info >= (2,7): import unittest else: import unittest2 as unittest import plist.nextstep from plist.nextstep import NSPlistReader class ParserTest(unittest.TestCase): def test_simple_dict(self): input = """{a = valuea; b = valueb;}""" expected = {"a" : "valuea", "b" : "valueb"} self.assertPlistEquals(input, expected) def test_simple_array(self): input = """(a,b,c)""" expected = ["a", "b", "c"] self.assertPlistEquals(input, expected) def test_complex_string(self): input = """{a = "\\"abc\\"\\nlinebreak"; b = valueb;}""" expected = {"a" : "\"abc\"\nlinebreak", "b" : "valueb"} self.assertPlistEquals(input, expected) def assertPlistEquals(self, input, expected, msg=None): r = NSPlistReader(StringIO(input)) actual = r.read() self.assertEquals(actual, expected, msg)
957
Python
.py
25
32.04
64
0.630836
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,288
testhelpers.py
simonwagner_mergepbx/test/testhelpers.py
import os import logging import codecs TEST_DIR = os.path.dirname(__file__) FIXTURES_DIR = os.path.join(TEST_DIR, "fixtures") def fixture_path(path): return os.path.join(FIXTURES_DIR, path) def make_logger(clazz): logger_name = "test.%s.%s" % (clazz.__module__, clazz.__name__) return logging.getLogger(logger_name) def listpath(dir): return [os.path.join(dir, entry) for entry in os.listdir(dir) if not entry.startswith(".")] def wrap_with_codec(f, codec): codecinfo = codecs.lookup(codec) wrapper = codecs.StreamReaderWriter(f, codecinfo.streamreader, codecinfo.streamwriter) return wrapper
639
Python
.py
17
33.882353
95
0.719156
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,289
test_coremerge.py
simonwagner_mergepbx/test/test_coremerge.py
import sys import logging if sys.version_info >= (2,7): import unittest else: import unittest2 as unittest from pbxproj.merge.coremerge import * from orderedset import OrderedSet from collections import OrderedDict class CoreMergeTest(unittest.TestCase): def test_diff_dict_keys(self): base = { "a" : "base", "b" : "base", "c" : "base" } mine = { "a" : "base", "c" : "mine_conflict", "d" : "mine_new" } expected_added = set(("d",)) expected_deleted = set(("b",)) expected_common = set(("a", "c")) diff = diff_dict_keys(base, mine) self.assertEquals(expected_added, diff.added) self.assertEquals(expected_deleted, diff.deleted) self.assertEquals(expected_common, diff.common) def test_diff3_dict_keys(self): base = { "a" : "base", "b" : "base", "c" : "base", "e" : "base", "g" : "base", } mine = { "a" : "base", "c" : "mine_conflict", "d" : "mine_new", "e" : "base", "g" : "mine_conflict", } theirs = { "a" : "base", "c" : "theirs_conflict", "f" : "theirs_new", } expected_mine_added = set(("d",)) expected_theirs_added = set(("f",)) expected_deleted = set(("b",)) expected_conflicting_deleted = set(("g", "e")) expected_common = set(("a", "c")) diff = diff3_dict_keys(base, mine, theirs) self.assertEquals(expected_mine_added, diff.mine_added) self.assertEquals(expected_theirs_added, diff.theirs_added) self.assertEquals(expected_conflicting_deleted, diff.conflicting_deleted) self.assertEquals(expected_deleted, diff.deleted) self.assertEquals(expected_common, diff.common) def test_diff_dict(self): base = { "a" : "base", "b" : "base", "c" : "base" } mine = { "a" : "base", "c" : "mine_updated", "d" : "mine_new" } expected_added = set(("d",)) expected_updated = set(("c",)) expected_deleted = set(("b",)) expected_common = set(("a",)) diff = diff_dict(base, mine) self.assertEquals(expected_added, diff.added) self.assertEquals(expected_updated, diff.updated) self.assertEquals(expected_deleted, diff.deleted) self.assertEquals(expected_common, diff.common) def test_diff3_dict(self): base = { "a" : "base", "b" : "base", "c" : "base", "e" : "base", "g" : "base", "h" : "base" } mine = { "a" : "base", "c" : "mine_conflict", "d" : "mine_new", "e" : "base", "g" : "mine_conflict", "h" : "mine" } theirs = { "a" : "base", "c" : "theirs_conflict", "f" : "theirs_new", "h" : "base" } expected_mine_added = set(("d",)) expected_theirs_added = set(("f",)) expected_mine_updated = set(("h",)) expected_theirs_updated = set() expected_deleted = set(("b","e")) expected_conflicting = set(("c","g")) expected_common = set(("a",)) diff = diff3_dict(base, mine, theirs) self.assertEquals(expected_mine_added, diff.mine_added) self.assertEquals(expected_mine_updated, diff.mine_updated) self.assertEquals(expected_theirs_added, diff.theirs_added) self.assertEquals(expected_theirs_updated, diff.theirs_updated) self.assertEquals(expected_conflicting, diff.conflicting) self.assertEquals(expected_deleted, diff.deleted) self.assertEquals(expected_common, diff.common) def test_diff_set(self): base = set(( "a", "b", "c" )) mine = set(( "a", "e", "d" )) theirs = set(( "a", "f", "b", "c" )) expected_added = set(( "e", "d", "f" )) expected_deleted = set(( "b", "c" )) expected_common = set(( "a" )) diff = diff3_set(base, mine, theirs) self.assertEquals(expected_added, diff.added) self.assertEquals(expected_deleted, diff.deleted) self.assertEquals(expected_common, diff.common) def test_merge_set(self): logger = logging.getLogger("test.CoreMergeTest.test_merge_set") base = set(( "a", "b", "c" )) mine = set(( "a", "e", "d" )) theirs = set(( "a", "f", "b", "c" )) expected_merged = set(( "a", "e", "d", "f" )) diff = diff3_set(base, mine, theirs) merged = merge_set(diff, base, mine, theirs) self.assertEquals(expected_merged, merged) def test_merge_ordered_set(self): logger = logging.getLogger("test.CoreMergeTest.test_merge_ordered_set") base = OrderedSet(( "a", "b", "c" )) mine = OrderedSet(( "a", "e", "d" )) theirs = OrderedSet(( "a", "f", "b", "c" )) expected_merged = OrderedSet(( "a", "e", "d", "f" )) diff = diff3_set(base, mine, theirs) merged = merge_ordered_set(diff, base, mine, theirs) self.assertEquals(tuple(expected_merged), tuple(merged)) #test if we can apply it cleanly to theirs diff_theirs = diff3_set(theirs, theirs, merged) merged_theirs = merge_ordered_set(diff, theirs, theirs, merged) self.assertEquals(tuple(merged), tuple(merged_theirs)) def test_merge_dict(self): base = { "a" : "base", "b" : "base", "c" : "base", "e" : "base", "g" : "base", "h" : "base" } mine = { "a" : "base", "c" : "base", "d" : "mine_new", "e" : "base", "g" : "base", "h" : "mine" } theirs = { "a" : "base", "c" : "theirs", "f" : "theirs_new", "h" : "base" } expected_merged = { "a" : "base", "c" : "theirs", "d" : "mine_new", "f" : "theirs_new", "h" : "mine" } diff = diff3_dict(base, mine, theirs) merged = merge_dict(diff, base, mine, theirs) self.assertEqual(merged, expected_merged) def test_merge_ordered_dict(self): base = OrderedDict(( ("a", "base"), ("b", "base"), ("c", "base"), ("e", "base"), ("g", "base"), ("h", "base") )) mine = OrderedDict(( ("a", "base"), ("c", "base"), ("d", "mine_new"), ("e", "base"), ("g", "base"), ("h", "mine") )) theirs = OrderedDict(( ("a", "base"), ("c", "theirs"), ("f", "theirs_new"), ("h", "base"), )) expected_merged = OrderedDict(( ("a", "base"), ("c", "theirs"), ("d", "mine_new"), ("f", "theirs_new"), ("h", "mine") )) diff = diff3_dict(base, mine, theirs) merged = merge_ordered_dict(diff, base, mine, theirs) self.assertEqual(merged, expected_merged) def test_pbx_merge(self): mine = OrderedSet(( "a", "b" )) theirs = OrderedSet(( "a", )) base = OrderedSet(( "a", )) expected_merged = OrderedSet(( "a", "b" )) diff = diff3_set(base, mine, theirs) merged = merge_ordered_set(diff, base, mine, theirs) self.assertEquals(tuple(expected_merged), tuple(merged)) #test if we can apply it cleanly to theirs diff_theirs = diff3_set(theirs, theirs, merged) merged_theirs = merge_ordered_set(diff, theirs, theirs, merged) self.assertEquals(tuple(merged), tuple(merged_theirs))
8,478
Python
.py
266
21.612782
81
0.473135
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,290
get_fixtures.py
simonwagner_mergepbx/tools/get_fixtures.py
#! /usr/bin/env python import os import sys from collections import namedtuple from git import Repo, GitCmdObjectDB def main(): repo_path, file_path, destination = sys.argv[1:4] collector = MergeCollector(repo_path) for hashes, file_contents in collector.itermerges(file_path): print "saving merge of %s and %s with %s as base" % (hashes.mine, hashes.theirs, hashes.base) dirname = str.join("-", hashes) full_dir_path = os.path.join(destination, dirname) os.mkdir(full_dir_path) for (name, file_content) in zip(("project.pbxproj.base", "project.pbxproj.mine", "project.pbxproj.theirs"), file_contents): full_file_path = os.path.join(full_dir_path, name) f = open(full_file_path, "w") f.write(file_content) f.close() Merge = namedtuple("Merge", ("base", "mine", "theirs")) class MergeCollector(object): def __init__(self, repo_path): repo = Repo(repo_path, odbt=GitCmdObjectDB) self.git = repo.git self.repo_path = repo_path def itermerges(self, filename): merges_with_base_iter = self._git_iter_merges_with_base_on_file(filename) for merge in merges_with_base_iter: base_content, mine_content, theirs_content = (self._git_show(commit, filename) for commit in merge) content_merge = Merge(base_content, mine_content, theirs_content) yield merge, content_merge def _git_iter_merges_with_base_on_file(self, filename): for (mine, theirs) in self._git_iter_merges_on_file(filename): base = self._git_get_merge_base(mine, theirs) yield Merge(base, mine, theirs) def _git_iter_merges_on_file(self, filename): log = self.git.log(filename) for line in log.splitlines(): if line.startswith("Merge: "): line = line.replace("Merge: ", "", 1) parents = line.split() yield parents def _git_get_merge_base(self, a,b): return self.git.merge_base(a,b)[:7] def _git_show(self, commit, fname): file_repo_path = os.path.relpath(fname, self.repo_path) return self.git.show("%s:%s" % (commit, file_repo_path)) if __name__ == "__main__": main()
2,275
Python
.py
48
39.041667
131
0.631222
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,291
profile_merging.py
simonwagner_mergepbx/tools/profile_merging.py
#!/usr/bin/env python import sys from argparse import ArgumentParser try: import cProfile as profile except: import profile from . import helpers from . import TEST_DIR helpers.setup_path() import pbxproj from pbxproj.merge import merge_pbxs def get_argument_parser(): parser = ArgumentParser() parser.add_argument("base", help="base for merging") parser.add_argument("mine", help="mine for merging") parser.add_argument("theirs", help="theirs for merging") parser.add_argument("-p", "--profile", help="store profile under this file path", default=None) parser.add_argument("-r", "--runs", type=int, help="how often should we parse the file", default=1) return parser def main(): parser = get_argument_parser() args = parser.parse_args() profile.runctx("for i in range(args.runs): merge_pbx_files(args.base, args.mine, args.theirs)", globals(), locals(), args.profile) def merge_pbx_files(basef, minef, theirsf): base, mine, theirs = (pbxproj.read(f) for f in (basef, minef, theirsf)) merged_project = merge_pbxs(base, mine, theirs) if __name__ == "__main__": main()
1,331
Python
.py
37
27.837838
134
0.609984
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,292
scan_isa.py
simonwagner_mergepbx/tools/scan_isa.py
#!/usr/bin/env python import logging import sys import os from . import helpers helpers.setup_path() from plist.nextstep import NSPlistReader, NSPlistWriter from pbxproj.isa import ISA_MAPPING fname = sys.argv[1] f = open(fname) r = NSPlistReader(f, name=fname) project = r.read() objects = project["objects"] isas = set(object["isa"] for object_id, object in objects.iteritems()) isas_known = set(ISA_MAPPING.iterkeys()) isas_unknown = isas - isas_known if len(isas_unknown) == 0: print "no unknown objects" else: for isa in sorted(isas_unknown): print isa
582
Python
.py
21
25.571429
70
0.754069
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,293
test.py
simonwagner_mergepbx/tools/test.py
#!/usr/bin/env python import sys import os import logging from argparse import ArgumentParser if sys.version_info >= (2,7): import unittest else: import unittest2 as unittest from . import helpers from . import TEST_DIR helpers.setup_path() class OnlyTestLogsFilter(logging.Filter): def filter(self, record): return record.name.startswith("test.") def get_argument_parser(): parser = ArgumentParser() parser.add_argument("--logging", help="show all log messages", action="store_true") parser.add_argument("--test-logging", help="show only log messages from test cases", action="store_true") parser.add_argument("--debug", help="start the debugger when an exception is thrown", action="store_true") return parser def setup_logging(): logger = logging.getLogger() logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(name)s: %(message)s') ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) return ch def install_pdb_exception_handler(): def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type, value, tb) else: import traceback, pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type, value, tb) print # ...then start the debugger in post-mortem mode. pdb.pm() sys.excepthook = info if __name__ == '__main__': log_handler = None parser = get_argument_parser() args = parser.parse_args() if args.logging: setup_logging() if args.test_logging and log_handler == None: handler = setup_logging() handler.addFilter(OnlyTestLogsFilter()) if args.debug: install_pdb_exception_handler() loader = unittest.TestLoader() tests = loader.discover(TEST_DIR) if args.debug: print "Running tests in debug mode..." for test in tests: test.debug() else: testRunner = unittest.runner.TextTestRunner() testRunner.run(tests)
2,415
Python
.py
70
26.928571
78
0.632031
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,294
reloader.py
simonwagner_mergepbx/tools/reloader.py
# Python Module Reloader # # Copyright (c) 2009-2014 Jon Parise <jon@indelible.org> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #Edited by Simon Wagner, to serve the needs of mergepbx: # * Turn blacklist into a callable, that decides, whether the module is loaded or not """Python Module Reloader""" try: import builtins except ImportError: import __builtin__ as builtins import imp import sys import types __author__ = 'Jon Parise <jon@indelible.org>' __version__ = '0.5' __all__ = ('enable', 'disable', 'get_dependencies', 'reload') _baseimport = builtins.__import__ _default_blacklist = lambda name: False _blacklist = _default_blacklist _dependencies = dict() _parent = None # Jython doesn't have imp.reload(). if not hasattr(imp, 'reload'): imp.reload = reload # PEP 328 changed the default level to 0 in Python 3.3. _default_level = -1 if sys.version_info < (3, 3) else 0 def enable(blacklist=_default_blacklist): """Enable global module dependency tracking. A blacklist can be specified to exclude specific modules (and their import hierachies) from the reloading process. The blacklist can be any iterable listing the fully-qualified names of modules that should be ignored. Note that blacklisted modules will still appear in the dependency graph; they will just not be reloaded. """ global _blacklist builtins.__import__ = _import if callable(blacklist): _blacklist = blacklist else: raise ValueError("blacklist must be a callable") def disable(): """Disable global module dependency tracking.""" global _blacklist, _parent builtins.__import__ = _baseimport _blacklist = _default_blacklist _dependencies.clear() _parent = None def get_dependencies(m): """Get the dependency list for the given imported module.""" name = m.__name__ if isinstance(m, types.ModuleType) else m return _dependencies.get(name, None) def _deepcopy_module_dict(m): """Make a deep copy of a module's dictionary.""" import copy # We can't deepcopy() everything in the module's dictionary because some # items, such as '__builtins__', aren't deepcopy()-able. To work around # that, we start by making a shallow copy of the dictionary, giving us a # way to remove keys before performing the deep copy. d = vars(m).copy() del d['__builtins__'] return copy.deepcopy(d) def _reload(m, visited): """Internal module reloading routine.""" name = m.__name__ # If this module's name appears in our blacklist, skip its entire # dependency hierarchy. global _blacklist if _blacklist(m): return # Start by adding this module to our set of visited modules. We use this # set to avoid running into infinite recursion while walking the module # dependency graph. visited.add(m) # Start by reloading all of our dependencies in reverse order. Note that # we recursively call ourself to perform the nested reloads. deps = _dependencies.get(name, None) if deps is not None: for dep in reversed(deps): if dep not in visited: _reload(dep, visited) # Clear this module's list of dependencies. Some import statements may # have been removed. We'll rebuild the dependency list as part of the # reload operation below. try: del _dependencies[name] except KeyError: pass # Because we're triggering a reload and not an import, the module itself # won't run through our _import hook below. In order for this module's # dependencies (which will pass through the _import hook) to be associated # with this module, we need to set our parent pointer beforehand. global _parent _parent = name # If the module has a __reload__(d) function, we'll call it with a copy of # the original module's dictionary after it's been reloaded. callback = getattr(m, '__reload__', None) if callback is not None: d = _deepcopy_module_dict(m) imp.reload(m) callback(d) else: imp.reload(m) # Reset our parent pointer now that the reloading operation is complete. _parent = None def reload(m): """Reload an existing module. Any known dependencies of the module will also be reloaded. If a module has a __reload__(d) function, it will be called with a copy of the original module's dictionary after the module is reloaded.""" _reload(m, set()) def _import(name, globals=None, locals=None, fromlist=None, level=_default_level): """__import__() replacement function that tracks module dependencies.""" # Track our current parent module. This is used to find our current place # in the dependency graph. global _parent parent = _parent _parent = _resolve_relative(parent, name, fromlist) # Perform the actual import work using the base import function. base = _baseimport(name, globals, locals, fromlist, level) if base is not None and parent is not None: m = base # We manually walk through the imported hierarchy because the import # function only returns the top-level package reference for a nested # import statement (e.g. 'package' for `import package.module`) when # no fromlist has been specified. if fromlist is None: for component in name.split('.')[1:]: m = getattr(m, component) # If we have a relative import, we need to do the same if name == "": relm_name = fromlist[0] m = getattr(m, relm_name) # If this is a nested import for a reloadable (source-based) module, # we append ourself to our parent's dependency list. if hasattr(m, '__file__'): l = _dependencies.setdefault(parent, []) l.append(m) # Lastly, we always restore our global _parent pointer. _parent = parent return base def _resolve_relative(parent, name, fromlist): if not name == "": return name #this is an absolute namen, no need to resolve return parent + "." + fromlist[0]
7,106
Python
.py
162
39.08642
85
0.706138
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,295
nsplist.py
simonwagner_mergepbx/tools/nsplist.py
#!/usr/bin/env python import logging import sys import os from . import helpers helpers.setup_path() from plist.nextstep import NSPlistReader, NSPlistWriter fname = sys.argv[1] f = open(fname) r = NSPlistReader(f, name=fname) w = NSPlistWriter(sys.stdout) w.write_plist(r.read())
285
Python
.py
12
22.333333
55
0.794776
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,296
merge_pbxproj_fixtures.py
simonwagner_mergepbx/tools/merge_pbxproj_fixtures.py
#!/usr/bin/env python import logging import sys import os from StringIO import StringIO import os.path from . import helpers helpers.setup_path() from plist.nextstep import NSPlistReader import pbxproj from pbxproj.pbxobjects import PBXProjFile from pbxproj.merge import get_project_file_merger def main(): print sys.argv for directory in sys.argv[1:]: print "merging files in %s" % directory merge_fixtures(directory) def read_pbxs(pbx_files): projects = [] for pbx_file in pbx_files: f = open(pbx_file) r = NSPlistReader(f, name=pbx_file) plist = r.read() projects.append(PBXProjFile(plist)) return projects def merge_pbxs(base, mine, theirs): merger = get_project_file_merger() return merger.merge(base, mine, theirs) def merge_pbx_files(basef, minef, theirsf, mergedf): base, mine, theirs = read_pbxs((basef, minef, theirsf)) merged_project = merge_pbxs(base, mine, theirs) pbxproj.write(mergedf, merged_project) def find_fixtures(path): dirlist = [os.path.join(path, entry) for entry in os.listdir(path)] directories = [entry for entry in dirlist if os.path.isdir(entry)] for directory in directories: merged_files = [os.path.join(directory, file) for file in ("project.pbxproj.base", "project.pbxproj.mine", "project.pbxproj.theirs")] files_exist = [os.path.exists(file) for file in merged_files] merged_files += [os.path.join(directory, "project.pbxproj.merged")] if reduce(lambda a, b: a and b, files_exist): yield tuple(merged_files) else: print "could not find files, skipping %s (%r)" % (directory, files_exist) return def merge_fixtures(fixtures_dir): fixtures = find_fixtures(fixtures_dir) for fixture in fixtures: print \ ("Merging \n" + \ "\tbase: %s\n" + \ "\tmine: %s\n" + \ "\ttheirs: %s\n" + \ "\tmerged: %s\n") % (fixture[0], fixture[1], fixture[2], fixture[3]) merge_pbx_files(*fixture) if __name__ == "__main__": main()
2,132
Python
.py
56
31.892857
141
0.654519
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,297
benchmark.py
simonwagner_mergepbx/tools/benchmark.py
from argparse import ArgumentParser import csv import os from subprocess import check_output from tempfile import mkdtemp import shutil import time import sys import gc import numpy as np import scipy from scipy.stats import t try: import cProfile as profile except: print "WARNING: could not load cProfile, results may not be comparable!" import profile import pstats from . import reloader from . import helpers from . import PROJECT_DIR, TEST_DIR #files that are used for the benchmark BENCHMARK_FILES = ( [os.path.join(TEST_DIR, file) for file in ( "fixtures/merge/iosbsh/c95f65c-86c9e3b-fdcc4a7/project.pbxproj.base", "fixtures/merge/iosbsh/c95f65c-86c9e3b-fdcc4a7/project.pbxproj.mine", "fixtures/merge/iosbsh/c95f65c-86c9e3b-fdcc4a7/project.pbxproj.theirs" )], ) def get_argument_parser(): parser = ArgumentParser() parser.add_argument("--start", help="ref where to start", default="HEAD") parser.add_argument("--stop", help="ref where to stop", default="origin/master") parser.add_argument("-o", help="benchmark outputfile", default="benchmark.csv") return parser def main(): parser = get_argument_parser() args = parser.parse_args() repo = Repo(PROJECT_DIR) tmp_repo = clone_repository(PROJECT_DIR) tmp_project = tmp_repo.working_dir tmp_src = os.path.join(tmp_project, "src") #add the temporary repository to the #load path. Add it to the beginning, #so we are sure that our modules #are loaded first sys.path = [tmp_src] + sys.path #enable reloader now reloader.enable( blacklist=lambda module: not module.__file__.startswith(tmp_src) ) #import module to benchmark import pbxproj #now execute the benchmark for each commit for commit in walk_history(repo, args.start, args.stop): sys.stdout.write("Benchmarking %s" % commit) sys.stdout.flush() checkout_commit(tmp_repo, commit) clean_pyc(tmp_src) #first reload to get all new dependencies pbxproj = reload_pbxproj(repo, pbxproj) #then reload for real pbxproj = reload_pbxproj(repo, pbxproj) sys.stdout.write("...") sys.stdout.flush() result = run_benchmark(pbxproj, BENCHMARK_FILES, timer_impl=ClockTimer) sys.stdout.write(" [%gs, %gs]\n" % result.confidence_interval()) reloader.disable() #delete temporary repo shutil.rmtree(tmp_repo.git_dir) shutil.rmtree(tmp_repo.working_dir) class ProfileTimer(object): def __enter__(self): self._profile = profile.Profile() self._profile.enable() def __exit__(self, type, value, traceback): # Error handling here self._profile.disable() self._profile.create_stats() def duration_in_seconds(self): stats = pstats.Stats(self._profile) return stats.total_tt class ClockTimer(object): def __enter__(self): self._start = time.time() def __exit__(self, type, value, traceback): # Error handling here self._finish = time.time() def duration_in_seconds(self): return self._finish - self._start class BenchmarkResult(object): def __init__(self, results): self.results = results def avg(self): return sum(self.results)/len(self.results) def confidence_interval(self, confidence=0.95): a = 1.0*np.array(self.results) n = len(a) m, se = np.mean(a), scipy.stats.sem(a) h = se * scipy.stats.t._ppf((1+confidence)/2., n-1) return m-h, m+h class Repo(object): def __init__(self, working_dir, git_dir=None): if git_dir is None: git_dir = os.path.join(working_dir, ".git") self.working_dir = working_dir self.git_dir = git_dir def cmd(self, git_cmd, git_cmd_args): args = [ "git", "--git-dir", self.git_dir, "--work-tree", self.working_dir, git_cmd ] + git_cmd_args return check_output(args) def clone_repository(orig_repro): temp_repro = mkdtemp() args = ["git", "clone", "-s", "-q", orig_repro, temp_repro ] check_output(args) return Repo(temp_repro) def walk_history(repo, start, stop): args = [ "--format=format:%h", "--topo-order", "--reverse", "%s..%s" % (start, stop) ] log = repo.cmd("log", args) return (sha for sha in log.splitlines()) def checkout_commit(repo, commit): repo.cmd("checkout", ["-q", commit]) def clean_pyc(path): for root, dirs, files in os.walk('/home/paulo-freitas'): pyc_files = (file for file in files if file.endswith(".pyc")) for pyc_file in pyc_files: os.remove(os.path.join(root, pyc_file)) def reload_pbxproj(repo, pbxproj): reloader.reload(pbxproj) return pbxproj def run_benchmark(pbxproj, test_files, runs=10, timer_impl=ProfileTimer): timer = timer_impl() results = [-1.0]*runs for i in range(runs): gc.collect() with timer: for test_file in test_files: basef, minef, theirsf = test_file base, mine, theirs = (pbxproj.read(f) for f in (basef, minef, theirsf)) pbxproj.merge.merge_pbxs(base, mine, theirs) results[i] = timer.duration_in_seconds() return BenchmarkResult(results) if __name__ == "__main__": main()
5,620
Python
.py
163
27.429448
87
0.628075
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,298
profile_parsing.py
simonwagner_mergepbx/tools/profile_parsing.py
#!/usr/bin/env python import sys from argparse import ArgumentParser try: import cProfile as profile except: import profile from . import helpers from . import TEST_DIR helpers.setup_path() import pbxproj def get_argument_parser(): parser = ArgumentParser() parser.add_argument("file", help="file to be parsed during the profiling") parser.add_argument("-p", "--profile", help="store profile under this file path", default=None) parser.add_argument("-r", "--runs", type=int, help="how often should we merge the file", default=1) return parser def main(): parser = get_argument_parser() args = parser.parse_args() profile.runctx("for i in range(runs): pbxproj.read(file)", globals={}, locals=dict( pbxproj=pbxproj, file=args.file, runs=args.runs ), filename=args.profile) if __name__ == "__main__": main()
1,048
Python
.py
34
22.676471
70
0.589232
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)
20,299
__init__.py
simonwagner_mergepbx/tools/__init__.py
import os PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) SRC_DIR = os.path.join(PROJECT_DIR, "src") TEST_DIR = os.path.join(PROJECT_DIR, "test") from . import helpers
200
Python
.py
5
38.6
77
0.699482
simonwagner/mergepbx
1,037
46
14
GPL-3.0
9/5/2024, 5:12:30 PM (Europe/Amsterdam)