root/trunk/pylucid_project/tests/unittest_plugin/unittest_plugin.py

Revision 1725, 9.7 kB (checked in by JensDiemer, 4 months ago)

* merge some redirect code together
* work-a-round for restricted plugin method and settings.TEMPLATE_DEBUG is on.
* add a unittest for this.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author
Line 
1# -*- coding: utf-8 -*-
2
3"""
4    PyLucid Plugin API example
5    ~~~~~~~~~~~~~~~~~~~~~~~~~~
6
7    Pseudocode!
8
9    Last commit info:
10    ~~~~~~~~~~~~~~~~~
11    $LastChangedDate$
12    $Rev$
13    $Author$
14
15    :copyleft: 2008 by the PyLucid team, see AUTHORS for more details.
16    :license: GNU GPL v3, see LICENSE.txt for more details.
17"""
18
19from pprint import pformat
20
21from PyLucid.system.BasePlugin import PyLucidBasePlugin
22
23from django.conf import settings
24from django.db import models
25from django.contrib.auth.models import User
26
27
28#_____________________________________________________________________________
29# Test Plugin models
30
31
32class TestArtist(models.Model):
33    name = models.CharField(max_length=100)
34
35    class Meta:
36        app_label = 'PyLucidPlugins'
37
38class TestAlbum(models.Model):
39    artist = models.ForeignKey(TestArtist)
40    name = models.CharField(max_length=100)
41    num_stars = models.IntegerField()
42
43    createtime = models.DateTimeField(auto_now_add=True)
44    lastupdatetime = models.DateTimeField(auto_now=True)
45
46    createby = models.ForeignKey(User, related_name="test_createby",
47        null=True, blank=True
48    )
49    class Meta:
50        app_label = 'PyLucidPlugins'
51
52    def __unicode__(self):
53        return u"TestAlbum '%s', ID %s, createby: %s" % (
54            self.name, self.id, self.createby
55        )
56
57PLUGIN_MODELS = (TestArtist, TestAlbum)
58
59#_____________________________________________________________________________
60# Plugin
61
62
63class unittest_plugin(PyLucidBasePlugin):
64    def lucidTag(self, *args, **kwargs):
65        """
66        Test if arguments in lucidTag would be parsed right in
67        PyLucid.template_addons.lucidTag
68        """
69        self.response.write("<pre>\n")
70        self.response.write("args:\n")
71        self.response.write("%s\n" % pformat(args))
72        self.response.write("pformarted kwargs:\n")
73        self.response.write("%s\n" % pformat(kwargs))
74        self.response.write("</pre>")
75
76    def hello_world(self):
77        """
78        Test if arguments in a lucidTag
79        """
80        self.response.write("Hello world!")
81
82    def test_restricted_method(self):
83        """
84        TODO: Must be update if ticket:199 is implemented!
85        ticket: "change plugin_manager_data (must_login and must_admin)"
86        """
87        self.response.write("<pre>This is restricted!</pre>")
88
89    def test_attributes(self, attr_name):
90        self.response.write(getattr(self, attr_name))
91
92    def test_page_msg(self):
93        # Normal ouput in blue color
94        self.page_msg("page_msg test:")
95
96        # A black colored messages:
97        self.page_msg.black("I am black")
98
99        # A error in red color
100        self.page_msg.red("RedError!")
101
102        # Successfull messages should be geen:
103        self.page_msg.green("and green")
104
105    def plugin_models(self):
106        """
107        Plays with the two local plugin models.
108        """
109        self.response.write("<pre>\n")
110        self.response.write("Test the plugin models\n")
111        self.response.write("Create TestArtist\n")
112        artist = TestArtist(name="A test Artist\n")
113        artist.save()
114        self.response.write("entry with ID '%s' created\n" % artist.id)
115        self.response.write("Create TestAlbum\n")
116        album = TestAlbum(
117            artist = artist,
118            name = "A test Album",
119            num_stars = 10,
120            createby = self.request.user
121        )
122        album.save()
123        self.response.write("entry with ID '%s' created:\n" % album.id)
124        self.response.write(u"%s\n" % album)
125        self.response.write("</pre>")
126
127    def all_models(self):
128        """
129        Display all existing models
130        """
131        self.response.write("<pre>\n")
132        self.response.write("All Albums:\n")
133        albums = TestAlbum.objects.all()
134        for album in albums:
135            self.response.write(u"%s: %s\n" % (album.id, album))
136
137        self.response.write("</pre>")
138
139
140
141    #__________________________________________________________________________
142    # PREFERENCES
143    #
144    def test_preferences(self):
145        """
146        Test the preferences API.
147
148        more info about plugin preferences:
149            http://www.pylucid.org/_goto/153/preferences/
150
151        TODO: Add more tests here. Test to change the preferences.
152        """
153        # Get the preferences from the database:
154        preferences = self.get_preferences()
155
156        self.response.write("<pre>\n")
157        self.response.write(repr(preferences))
158        self.response.write("</pre>")
159
160        assert(preferences,
161            {
162                'index': u'Index', 'print_index': False,
163                'print_last_page': True, 'index_url': u'/'
164            }
165        )
166
167        # Change a preference entry
168        new_preference_dict = self.set_preferences('print_index', True)
169        assert(new_preference_dict['print_index'], True)
170
171        # Get the preference from the database again and check
172        preferences = self.get_preferences()
173        assert(preferences['print_index'], True)
174
175        self.response.write("test preferences END")
176
177
178#    """
179#    We inherit from the base plugin.
180#    """
181#    def global_objects(self):
182#        """
183#        A list of all global plugin objects how inherit from the base plugin.
184#        """
185#        # The plugin name as a String:
186#        self.plugin_name
187#
188#        # Interface to the internal pages (only for special needs)
189#        # PyLucid.system.internal_page.InternalPage()
190#        self.internal_page
191#
192#        # The global context
193#        self.context
194#
195#        # A response object (only for special needs)
196#        self.response
197#
198#        # The django request object
199#        # see http://www.djangoproject.com/documentation/request_response/
200#        self.request
201#
202#        # Interface to the PyLucid page message system
203#        self.page_msg
204#
205#        # object to build URLs:
206#        # comes from PyLucid.system.URLs
207#        self.URLs
208#
209#        # database instance of the cms page object:
210#        self.current_page
211#
212#    #__________________________________________________________________________
213#    # URLs
214#    #
215#    # How to build urls
216#    #
217#    def building_urls(self):
218#        """
219#        You should never building urls "by hand". You should use URLs!
220#        In the most case you need only methodLink() and commandLink().
221#
222#        In special cases you can some other methods. Please look into the
223#        source code PyLucid.system.URLs
224#        """
225#        # mostly you will create a link to a other method of the current plugin
226#        # Use methodLink() for this:
227#        link = self.URLs.methodLink("method_name")
228#
229#        # In special cases you would like to insert a link to a other plugin.
230#        # Use commandLink() for this:
231#        link = self.URLs.commandLink("page_admin", "edit_page")
232#
233#        # The URLs object is a dictionary like object. You can display the
234#        # content of it into the page_msg with:
235#        self.URLs.debug()
236#
237#
238#    #__________________________________________________________________________
239#    # OUTPUT
240#    #
241#    # How a Plugin can create a response
242#    #
243#    def render_a_internal_page(self):
244#        """
245#        Normal way to create output into the content area with a existing
246#        internal page.
247#
248#        See also: http://pylucid.org/_goto/142/internal-pages/
249#        """
250#        # Example:
251#        context = {
252#            # Building a template context for the internal page
253#            "key": value,
254#            "Foo": Bar,
255#        }
256#        # Render the template with the context and write the result into the
257#        # response object:
258#        self._render_template("InternalPageName", context)
259#
260#    def page_msg(self):
261#        """
262#        With the global self.page_msg object a plugin can easy send short
263#        messages to the user.
264#        You can call page_msg several times and everywhere.
265#        All messages would be inserted in the generated page.
266#
267#        Note:
268#            The page message object is good for debugging. List and Dictioaries
269#            would be formatted with pprint.
270#
271#        More info in PyLucid.system.page_msg
272#        """
273#        # Examples:
274#
275#        # Normal ouput in blue color
276#        self.page_msg("The shorted way...")
277#
278#        # A error in red color
279#        self.page_msg.red("Error!")
280#
281#        # A black colored messages:
282#        self.page_msg.black("I am black")
283#
284#        # Successfull messages should be geen:
285#        self.page_msg.geen("Update XY successfull")
286#
287#    def return_a_response(self):
288#        """
289#        A Plugin method can return a django HttpResponse object directy back.
290#        e.g. send files to the client or a Redirect
291#        """
292#        # send the XML file to the client
293#        from django.http import HttpResponse
294#        response = HttpResponse()
295#        response['Content-Type'] = 'application/xml; charset=utf-8'
296#        response.write(FooBar)
297#        return response
298#
299#    def change_page_title(self):
300#        """
301#        If a plugin creates his own response page, it should be change the
302#        current displayed page title, so it makes more sense for the user.
303#        """
304#        self.context["PAGE"].title = "The Plugin Title"
305
306#
307#
308#    #__________________________________________________________________________
309#    # ENVIRONMENT
310#    #
311#    # Some needfull information
312#    #
313#    def on_request_object(self):
314#        """
315#        Some needfull objects from the request object.
316#        """
317#        # Is debug on? If you will display information only if debug is on, you
318#        # should not use settings.DEBUG directly!
319#        # Use request.debug, because it is true if settings.DEBUG if true *or*
320#        # if the client IP is in settings.INTERNAL_IPS
321#        # This is append to the request object in
322#        # PyLucid.system.utils.setup_debug
323#        if self.request.debug:
324#            self.page_msg("Debug is on.")
Note: See TracBrowser for help on using the browser.