Best JavaScript code snippet using playwright-internal
reportbuilder.py
Source:reportbuilder.py
1# -*- coding: utf-8 -*-2##Copyright (C) [2005] [Jürgen Hamel, D-32584 Löhne]3##This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as4##published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.5##This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied6##warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License7##for more details.8##You should have received a copy of the GNU General Public License along with this program; if not, write to the9##Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. 10import sys11import os12import os.path13import types14import pygtk15pygtk.require('2.0')16import gtk17import gtk.glade18import gobject19import string20import logging21import cPickle22#import cuon.OpenOffice.letter23# localisation24import locale, gettext25locale.setlocale (locale.LC_NUMERIC, '')26import threading27import datetime as DateTime28import drawingReport29import cuon.Misc.cuon_dialog30from modifyEntry import modifyEntryWindow31class reportbuilderwindow(modifyEntryWindow):32 33 def __init__(self, dicFilename = None):34 35 modifyEntryWindow.__init__(self)36 self.dicPage = {}37 self.dicText = {}38 # self.setLogLevel(self.INFO)39 40 self.dicText['class'] = 'Label'41 self.dicText['text'] = 'NoTitle'42 self.dicText['x1'] = 043 self.dicText['x1'] = 044 self.dicText['y1'] = 045 self.dicText['x2'] = 046 self.dicText['y2'] = 047 self.dicText['font'] = 'courier'48 self.dicText['fontsize'] = 1249 self.dicText['kursiv'] = 'no'50 self.dicText['bold'] = 'no'51 self.dicText['underline'] = 'no'52 self.dicText['subscript'] = 'no'53 self.dicText['fontjustification'] = 'left'54 self.dicText['yOffSet'] = 2055 self.dicText['Papersize'] = self.pagesizes['A4']56 self.dicText['Papersize_Width'], self.dicText['Papersize_Height'] = self.dicText['Papersize']57 58 self.dicText['Orientation'] = 'Portrait' # 'Landscape' # 'Portrait'59 60 self.dicPage['ReportFootAppendToGroup'] = 0 61 self.dicPage['PageFootAppendToGroup'] = 0 62 63 self.dicText['TopMargin'] = 3064 self.activeRegion = 165 self.activeGroup = 066 self.activeDA = None67 self.drawReportHeader = {}68 self.drawPageHeader = {}69 self.drawGroup = {}70 self.drawPageFooter = {}71 self.drawReportFooter = {}72 self.reportHeaderDA = None73 self.PageHeaderDA = None74 self.reportGroupsDA = []75 self.PageFooterDA = None76 self.reportFooterDA = None77 78 79 daR = self.getWidget('daReportHeader')80 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)81 82 daR = self.getWidget('daPageHeader')83 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)84 85 daR = self.getWidget('daGroups')86 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)87 88 daR = self.getWidget('daPageFooter')89 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)90 91 daR = self.getWidget('daReportFooter')92 daR.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)93 94 95 96 #self.loadGlade('reportbuilder.xml')97 98 self.win1 = self.getWidget('reportbuildermainwindow')99 self.win1.show()100 101 #self.setStatusBar()102 103 print 'dicFilename at reportbuilder', dicFilename104 if dicFilename:105 self.dicCurrentFilename = dicFilename106 self.readReportDocument(dicFilename)107 else:108 self.dicCurrentFilename = {'TYPE':'FILE','NAME':'./new.txt'}109 110 111 # menu File112 def on_save_activate(self, event):113 print 'save clicked'114 self.saveFile()115 116 117 #Events118 119 # Report Header120 121 122 123 def on_daReportHeader_button_press_event(self, oWidget, data):124 125 print 'mouse button = ', oWidget , data, data.x, data.y126 self.activateClick("rRHactive", "clicked")127 if data.button == 3:128 liEntries = self.reportHeaderDA.getEntryAtPosition(data.x, data.y)129 if liEntries:130 self.chooseFromEntries(liEntries)131 132 133 134 def on_daReportHeader_key_press_event(self, oWidget, data ):135 print 'key = ', oWidget, data136 137 138 139 # Page Header140 141 142 143 def on_daPageHeader_button_press_event(self, oWidget, data):144 145 print 'mouse button = ', oWidget , data, data.x, data.y146 self.activateClick("rPHactive", "clicked")147 if data.button == 3:148 liEntries = self.PageHeaderDA.getEntryAtPosition(data.x, data.y)149 150 if liEntries:151 self.chooseFromEntries(liEntries)152 153 def on_daPageHeader_key_press_event(self, oWidget, data ):154 print 'key = ', oWidget, data155 156 # Report Groups157 158 159 160 def on_daGroups_button_press_event(self, oWidget, data):161 162 print 'mouse button = ', oWidget , data, data.x, data.y163 self.activateClick("rGactive", "clicked")164 if data.button == 3:165 liEntries = self.reportGroupsDA[0].getEntryAtPosition(data.x, data.y)166 167 if liEntries:168 self.chooseFromEntries(liEntries)169 170 171 def on_daGroups_key_press_event(self, oWidget, data ):172 print 'key = ', oWidget, data173 174 # Page Footer175 176 177 178 def on_daPageFooter_button_press_event(self, oWidget, data):179 180 print 'mouse button = ', oWidget , data, data.x, data.y181 self.activateClick("rPFactive", "clicked")182 if data.button == 3:183 liEntries = self.PageFooterDA.getEntryAtPosition(data.x, data.y)184 185 if liEntries:186 self.chooseFromEntries(liEntries)187 188 189 190 191 def on_daPageFooter_key_press_event(self, oWidget, data ):192 print 'key = ', oWidget, data193 194 # Report Footer195 196 197 198 def on_daReportFooter_button_press_event(self, oWidget, data):199 200 print 'mouse button = ', oWidget , data, data.x, data.y201 self.activateClick("rRFactive", "clicked")202 if data.button == 3:203 liEntries = self.reportFooterDA.getEntryAtPosition(data.x, data.y)204 self.chooseFromEntries(self, liEntries) 205 206 207 208 209 210 211 def on_daReportFooter_key_press_event(self, oWidget, data ):212 print 'key = ', oWidget, data213 214 215 216 217 # toggle report part218 219 def on_rAll_toggled(self, event):220 print 'radiobutton toggled'221 liButtons = ['rRHactive', 'rPHactive','rGactive','rPFactive','rRFactive']222 for l in range (len(liButtons)):223 rAll = self.getWidget(liButtons[l])224 if rAll.get_active():225 self.activeRegion = l+1226 print 'active = ', self.activeRegion227 228 # functions229 def chooseFromEntries(self, liEntries): 230 #print liEntries, len(liEntries)231 if len(liEntries)> 1:232 sText = 'Choose: \n'233 for l in range(0, len(liEntries)):234 sText += `l` + " " + liEntries[l]['name'] + "\n"235 236 cd = cuon.Misc.cuon_dialog.cuon_dialog()237 ok, res = cd.inputLine( 'choose', sText)238 print 'ok = ', ok, 'Res = ', res239 if ok and res: 240 try:241 self.modifyEntry(liEntries[int(res)])242 except:243 pass244 245 246 247 else:248 self.modifyEntry(liEntries[0]) 249 def modifyEntry(self, dicEntry):250 self.ModifyEntryShow(dicEntry)251 252 def on_bRefresh_clicked(self, event):253 print 'bRefresh clicked'254 self.activeDA.area_expose_cb(None, event)255 256 257 def on_tbSave_clicked(self, event):258 self.activateClick('save')259 #self.saveFile()260 261 def replaceEntry(self, dicEntry):262 263 print 'active Region = ', self.activeRegion264 self.activeDA = None265 if self.activeRegion == 1:266 self.activeDA = self.reportHeaderDA267 elif self.activeRegion == 2:268 self.activeDA= self.PageHeaderDA269 elif self.activeRegion == 3:270 self.activeDA = self.reportGroupsDA[self.activeGroup]271 elif self.activeRegion == 4:272 self.activeDA = self.PageFooterDA273 elif self.activeRegion == 5:274 self.activeDA = self.reportFooterDA 275 276 self.activeDA.replaceEntryByName(dicEntry)277 def save_file(self, dicFilename, data):278 "Saves the data to the file located by the filename"279 print 'save this ', dicFilename280 281 if dicFilename['TYPE'] == 'SSH':282 sFile = dicFilename['TMPNAME']283 else:284 sFile = dicFilename['NAME']285 outfile = open(sFile, "w")286 if outfile:287 outfile.write(data)288 outfile.close() 289 #mark as unmodified since last save290 #self.textbuffer.set_modified(False)291 292 if dicFilename['TYPE'] == 'SSH':293 os.system('cp -f ' + dicFilename['TMPNAME'] +' ' + os.path.basename(dicFilename['NAME'] ) )294 s1 = 'scp -P ' + dicFilename['PORT'] + ' ' + os.path.basename(dicFilename['NAME'] ) + ' ' + dicFilename['USER'] + '@' + dicFilename['HOST'] + '://' 295 s1 += os.path.dirname(dicFilename['NAME'] )296 print s1297 298 os.system(s1)299 os.system('rm ' + os.path.basename(dicFilename['NAME'] ) )300 print 'Files saved' 301 def saveFile(self): 302 liEntry, liReport = self.reportValues.getEntries()303 304 # report Head305 sDoc = "<report>\n"306 if liReport:307 308 sDoc = self.addList(sDoc, liReport)309 310 311 312 # report header313 liEntry, liReport = self.reportHeaderDA.getEntries()314 if liReport:315 print liReport316 sDoc += "<reportHeader>\n"317 sDoc = self.addList(sDoc, liReport)318 319 if liEntry:320 #print liEntry321 #print sDoc 322 sDoc = self.addList(sDoc, liEntry, sEntry="entry")323 324 325 sDoc += "</reportHeader>\n" 326 327 328 #doc = self.dic2xml(doc, liEntry, "reportHeader")329 330 # Page Header331 liEntry, liReport = self.PageHeaderDA.getEntries()332 if liReport:333 print liReport334 sDoc += "<pageHeader>\n"335 sDoc = self.addList(sDoc, liReport)336 337 if liEntry:338 #print liEntry339 #print sDoc 340 sDoc = self.addList(sDoc, liEntry, sEntry="entry")341 342 343 sDoc += "</pageHeader>\n" 344 # page groups345 sDoc += "<groups>\n" 346 sDoc += "<count>" + `self.dicPage['count']` + "</count>"347 348 for k in range(len(self.reportGroupsDA)):349 liEntry, liReport = self.reportGroupsDA[k].getEntries()350 if liReport:351 print liReport352 353 354 355 if liEntry:356 #print liEntry357 #print sDoc 358 sDoc += "<groupEntry>\n"359 sDoc += "\t<number>" + `self.dicPage[`k` + '_groupNumber']` + "</number>\n"360 sDoc += "\t<resultSet>" + `self.dicPage[`k` + '_groupResultSet']` + "</resultSet>\n"361 sDoc += "\t<pageDetails>\n"362 sDoc += "\t\t<posX1>" + str(self.dicPage[`k` + '_detailsX1']) + "</posX1>\n"363 sDoc += "\t\t<posX2>" + str(self.dicPage[`k` + '_detailsX2']) + "</posX2>\n"364 sDoc += "\t\t<posY1>" + str(self.dicPage[`k` + '_detailsY1']) + "</posY1>\n"365 sDoc += "\t\t<posY2>" + str(self.dicPage[`k` + '_detailsY2']) + "</posY2>\n"366 sDoc += "\t\t<lineY>" + str(self.dicPage[`k` + '_detailslineY']) + "</lineY>\n"367 368 sDoc = self.addList(sDoc, liReport)369 370 sDoc = self.addList(sDoc, liEntry, sEntry="entry")371 372 sDoc += "</pageDetails>\n"373 sDoc += "</groupEntry>\n"374 375 376 sDoc += "</groups>\n" 377 378 # page Footer379 liEntry, liReport = self.PageFooterDA.getEntries()380 if liReport:381 print liReport382 sDoc += "\n<pageFooter>\n"383 sDoc = self.addList(sDoc, liReport)384 385 if liEntry:386 #print liEntry387 #print sDoc 388 sDoc = self.addList(sDoc, liEntry, sEntry="entry")389 390 391 sDoc += "</pageFooter>\n" 392 393 394 #doc = self.dic2xml(doc, liEntry, "reportHeader")395 396 397 # report Footer398 liEntry, liReport = self.reportFooterDA.getEntries()399 if liReport:400 print liReport401 sDoc += "\n<reportFooter>\n"402 sDoc = self.addList(sDoc, liReport)403 404 if liEntry:405 #print liEntry406 #print sDoc 407 sDoc = self.addList(sDoc, liEntry, sEntry="entry")408 409 410 sDoc += "</reportFooter>\n" 411 412 413 #doc = self.dic2xml(doc, liEntry, "reportHeader") 414 sDoc += "</report> "415 print sDoc416 self.save_file(self.dicCurrentFilename, sDoc)417 418 419 def addList(self, sDoc, liReport, sEntry=None):420 for i in liReport:421 if sEntry:422 423 sDoc += "\t<entry>\n"424 425 for key in ['name', 'posX1', 'posX2', 'posY1', 'posY2', 'class', 'value', 'type','resultSet', 'format', 'variable', 'memory', 'formula', 'property','font', 'fontsize', 'fontjustification', 'foregroundColor' , 'backgroundColor', 'grayScale']:426 if i.has_key(key):427 if sEntry:428 sDoc += "\t"429 430 sDoc += "\t<" + key +">"431 sValue = i[key]432 sValue = self.checkXmlValue(sValue)433 sDoc += sValue434 sDoc += "</" + key +">\n"435 436 sDoc += "\t</entry>\n"437 438 else:439 for key in i.keys():440 if sEntry:441 sDoc += "\t"442 sDoc += "\t<" + key +">"443 sValue = i[key]444 sValue = self.checkXmlValue(sValue)445 sDoc += sValue446 sDoc += "</" + key +">\n"447 return sDoc448 449 450 451 452 def readReportDocument(self, dicFilename):453 "Opens the file given in filename and reads it in"454 print 'dicFilename = ', dicFilename 455 if dicFilename['TYPE'] == 'SSH':456 dicFilename['TMPNAME'] = 'tmp_editor_ssh_tab_GUI_0' 457 s1 = 'scp -P ' + dicFilename['PORT'] + ' ' + dicFilename['USER'] + '@' + dicFilename['HOST'] + ':/' 458 s1 += dicFilename['NAME'] + ' ' + dicFilename['TMPNAME']459 print 's1 = ' , s1460 os.system(s1)461 filename = dicFilename['TMPNAME']462 463 else:464 465 filename = dicFilename['NAME']466 467 print 'filename to read xml', filename 468 doc = self.readDocument(filename)469 470 print `doc`471 cyRootNode = self.getRootNode(doc)472 473 self.setReportValues(cyRootNode)474 475 self.reportValues = drawingReport.drawingReport() 476 477 self.reportValues.setReportEntry({'topMargin':self.dicPage['topMargin']})478 self.reportValues.setReportEntry({'bottomMargin':self.dicPage['bottomMargin']})479 self.reportValues.setReportEntry({'rightMargin':self.dicPage['rightMargin']})480 self.reportValues.setReportEntry({'leftMargin':self.dicPage['leftMargin']})481 self.reportValues.setReportEntry({'papersizeX':self.dicPage['papersizeX']})482 self.reportValues.setReportEntry({'papersizeY':self.dicPage['papersizeY']})483 self.reportValues.setReportEntry({'orientation':self.dicPage['orientation']})484 if self.dicPage.has_key('SiteBackground_URL'):485 self.reportValues.setReportEntry({'SiteBackground_URL':self.dicPage['SiteBackground_URL']})486 self.reportValues.setReportEntry({'SiteBackgroundHeight':self.dicPage['SiteBackgroundHeight']})487 self.reportValues.setReportEntry({'SiteBackgroundWidth':self.dicPage['SiteBackgroundWidth']})488 self.reportValues.setReportEntry({'SiteBackgroundX':self.dicPage['SiteBackgroundX']})489 self.reportValues.setReportEntry({'SiteBackgroundY':self.dicPage['SiteBackgroundY']})490 491 if self.dicPage.has_key('SiteBackground_URL2'):492 self.reportValues.setReportEntry({'SiteBackground_URL2':self.dicPage['SiteBackground_URL2']})493 self.reportValues.setReportEntry({'SiteBackgroundHeight2':self.dicPage['SiteBackgroundHeight2']})494 self.reportValues.setReportEntry({'SiteBackgroundWidth2':self.dicPage['SiteBackgroundWidth2']})495 self.reportValues.setReportEntry({'SiteBackgroundX2':self.dicPage['SiteBackgroundX2']})496 self.reportValues.setReportEntry({'SiteBackgroundY2':self.dicPage['SiteBackgroundY2']})497 if self.dicPage.has_key('SiteBackground_URL3'):498 self.reportValues.setReportEntry({'SiteBackground_URL3':self.dicPage['SiteBackground_URL3']})499 self.reportValues.setReportEntry({'SiteBackgroundHeight3':self.dicPage['SiteBackgroundHeight3']})500 self.reportValues.setReportEntry({'SiteBackgroundWidth3':self.dicPage['SiteBackgroundWidth3']})501 self.reportValues.setReportEntry({'SiteBackgroundX3':self.dicPage['SiteBackgroundX3']})502 self.reportValues.setReportEntry({'SiteBackgroundY3':self.dicPage['SiteBackgroundY3']})503 cyReportHeaderNode = self.getNode(cyRootNode, 'reportHeader')504 #print 'node = ', cyReportHeaderNode[0].toxml()505 506 cyReportHeaderEntries = self.getNodes(cyReportHeaderNode[0], 'entry')507 508 509 if cyReportHeaderEntries:510 511 width = self.dicPage['headerX2'] - self.dicPage['headerX1'] 512 height = self.dicPage['headerY2'] - self.dicPage['headerY1']513 514 self.reportHeaderDA = drawingReport.drawingReport()515 self.reportHeaderDA.createDA( self.getWidget('scReportHeader'), self.getWidget('vpReportHeader'), self.getWidget('daReportHeader'), width, height)516 self.reportHeaderDA.setReportEntry({'posX1':self.dicPage['headerX1'] })517 self.reportHeaderDA.setReportEntry({'posX2':self.dicPage['headerX2'] })518 self.reportHeaderDA.setReportEntry({'posY1':self.dicPage['headerY1'] })519 self.reportHeaderDA.setReportEntry({'posY2':self.dicPage['headerY2'] })520 521 for i in cyReportHeaderEntries:522 523 print i.toxml()524 self.reportHeaderDA.setEntry(self.getXmlEntry(i))525 #print 'dicEntry = ', dicEntry526 527 528 cyReportPageHeaderNode = self.getNode(cyRootNode, 'pageHeader')529 cyPageHeaderEntries = self.getNodes(cyReportPageHeaderNode[0], 'entry')530 if cyPageHeaderEntries:531 532 width = self.dicPage['pageX2'] - self.dicPage['pageX1'] 533 height = self.dicPage['pageY2'] - self.dicPage['pageY1']534 535 self.PageHeaderDA = drawingReport.drawingReport()536 self.PageHeaderDA.createDA( self.getWidget('scPageHeader'), self.getWidget('vpPageHeader'), self.getWidget('daPageHeader'), width, height)537 self.PageHeaderDA.setReportEntry({'posX1':self.dicPage['pageX1'] })538 self.PageHeaderDA.setReportEntry({'posX2':self.dicPage['pageX2'] })539 self.PageHeaderDA.setReportEntry({'posY1':self.dicPage['pageY1'] })540 self.PageHeaderDA.setReportEntry({'posY2':self.dicPage['pageY2'] })541 542 for i in cyPageHeaderEntries:543 544 #print i.toxml()545 self.PageHeaderDA.setEntry(self.getXmlEntry(i))546 #print 'dicEntry = ', dicEntry547 548 549 cyReportGroupsNodes = self.getNode(cyRootNode, 'groups')550 551 552 553 if cyReportGroupsNodes:554 for k in range(len(cyReportGroupsNodes)):555 cyGroupsEntries = self.getNodes(cyReportGroupsNodes[k], 'entry')556 557 558 # cyPageDetailsNodes = self.getNodes(cyGroupEntry, 'pageDetails')559 # print'+++++++ cyPageDetailsNodes = ', cyPageDetailsNodes560 # 561 # for i in range(len(cyPageDetailsNodes)):562 width = self.dicPage[`k` + '_detailsX2'] - self.dicPage[`k` + '_detailsX1'] 563 height = self.dicPage[`k` + '_detailsY2'] - self.dicPage[`k` + '_detailsY1']564 565 self.reportGroupsDA.append(drawingReport.drawingReport())566 self.reportGroupsDA[k].createDA( self.getWidget('scGroups'), self.getWidget('vpGroups'), self.getWidget('daGroups'), width, height)567 self.reportGroupsDA[k].setReportEntry({'posX1':self.dicPage[`k` + '_detailsX1'] })568 self.reportGroupsDA[k].setReportEntry({'posX2':self.dicPage[`k` + '_detailsX2'] })569 self.reportGroupsDA[k].setReportEntry({'posY1':self.dicPage[`k` + '_detailsY1'] })570 self.reportGroupsDA[k].setReportEntry({'posY2':self.dicPage[`k` + '_detailsY2'] })571 self.reportGroupsDA[k].setReportEntry({'posY2':self.dicPage[`k` + '_detailsY2'] })572 self.reportGroupsDA[k].setReportEntry({'lineY':self.dicPage[`k` + '_detailslineY'] })573 #print cyGroupEntry.toxml()574 575 for i in cyGroupsEntries:576 #print i.toxml()577 self.reportGroupsDA[k].setEntry(self.getXmlEntry(i))578 #print 'dicEntry = ', dicEntry579 580 cyReportPageFooterNode = self.getNode(cyRootNode, 'pageFooter')581 cyPageFooterEntries = self.getNodes(cyReportPageFooterNode[0], 'entry')582 if cyPageFooterEntries:583 584 width = self.dicPage['pageFooterX2'] - self.dicPage['pageFooterX1'] 585 height = self.dicPage['pageFooterY2'] - self.dicPage['pageFooterY1']586 587 self.PageFooterDA = drawingReport.drawingReport()588 self.PageFooterDA.createDA( self.getWidget('scPageFooter'), self.getWidget('vpPageFooter'), self.getWidget('daPageFooter'), width, height)589 self.PageFooterDA.setReportEntry({'posX1':self.dicPage['pageFooterX1'] })590 self.PageFooterDA.setReportEntry({'posX2':self.dicPage['pageFooterX2'] })591 self.PageFooterDA.setReportEntry({'posY1':self.dicPage['pageFooterY1'] })592 self.PageFooterDA.setReportEntry({'posY2':self.dicPage['pageFooterY2'] })593 594 for i in cyPageFooterEntries:595 596 #print i.toxml()597 self.PageFooterDA.setEntry(self.getXmlEntry(i))598 #print 'dicEntry = ', dicEntry599 cyReportFooterNode = self.getNode(cyRootNode, 'reportFooter')600 601 cyReportFooterEntries = self.getNodes(cyReportFooterNode[0], 'entry')602 603 604 if cyReportFooterEntries:605 606 width = self.dicPage['footerX2'] - self.dicPage['footerX1'] 607 height = self.dicPage['footerY2'] - self.dicPage['footerY1']608 609 self.reportFooterDA = drawingReport.drawingReport()610 self.reportFooterDA.createDA( self.getWidget('scReportFooter'), self.getWidget('vpReportFooter'), self.getWidget('daReportFooter'), width, height)611 self.reportFooterDA.setReportEntry({'posX1':self.dicPage['footerX1'] })612 self.reportFooterDA.setReportEntry({'posX2':self.dicPage['footerX2'] })613 self.reportFooterDA.setReportEntry({'posY1':self.dicPage['footerY1'] })614 self.reportFooterDA.setReportEntry({'posY2':self.dicPage['footerY2'] })615 for i in cyReportFooterEntries:616 617 #print i.toxml()618 self.reportFooterDA.setEntry(self.getXmlEntry(i))619 #print 'dicEntry = ', dicEntry620 621 622 def getXmlEntry(self, cyNode):623 624 dicEntry = {}625 # set some defaults626 dicEntry['Property'] = '0'627 628 dicEntry['name'] = self.getEntrySpecification(cyNode,'name').encode('ascii')629 try:630 dicEntry['width'] = int(self.getEntrySpecification(cyNode,'width'))631 except:632 dicEntry['width'] = 0633 try:634 dicEntry['height'] = int(self.getEntrySpecification(cyNode,'height'))635 except:636 dicEntry['height'] = 0637 638 dicEntry['posX1'] = int(self.getEntrySpecification(cyNode,'posX1'))639 dicEntry['posX2'] = int(self.getEntrySpecification(cyNode,'posX2'))640 dicEntry['posY1'] = int(self.getEntrySpecification(cyNode,'posY1'))641 dicEntry['posY2'] = int(self.getEntrySpecification(cyNode,'posY2'))642 643 dicEntry['type'] = self.getEntrySpecification(cyNode,'type').encode('ascii')644 645 dicEntry['class'] = self.getEntrySpecification(cyNode,'class').encode('utf-8')646 dicEntry['value'] = self.getEntrySpecification(cyNode,'value')647 dicEntry['format'] = self.getEntrySpecification(cyNode,'format')648 if dicEntry['format']:649 dicEntry['format'] = dicEntry['format'].encode('ascii')650 dicEntry['formula'] = self.getEntrySpecification(cyNode,'formula')651 if dicEntry['formula']:652 dicEntry['formula'] = dicEntry['formula'].encode('utf-8')653 else:654 dicEntry['formula'] = None655 dicEntry['memory'] = self.getEntrySpecification(cyNode,'memory')656 if dicEntry['memory']:657 dicEntry['memory'] = dicEntry['memory'].encode('ascii')658 else:659 dicEntry['memory'] = None660 661 dicEntry['type'] = self.getEntrySpecification(cyNode,'type')662 sResultSet = self.getEntrySpecification(cyNode,'resultSet')663 if sResultSet:664 sResultSet = sResultSet.encode('ascii')665 dicEntry['resultSet'] = sResultSet666 else:667 dicEntry['resultSet'] = 'zero'668 sVariable = self.getEntrySpecification(cyNode,'variable')669 if sVariable:670 sVariable = sVariable.encode('ascii')671 dicEntry['variable'] = sVariable672 else:673 dicEntry['variable'] = None 674 675 sFont = self.getEntrySpecification(cyNode,'font')676 liFont = sFont.split(';')677 678 dicEntry['font'] = liFont[0]679 if len(liFont)> 1:680 if liFont[1] == 'TTF':681 print liFont[0], type(liFont[0])682 print liFont[2], type(liFont[2])683 pdfmetrics.registerFont( TTFont( liFont[0].encode('ascii'),liFont[2].encode('ascii')))684 685 dicEntry['fontsize'] = int( self.getEntrySpecification(cyNode,'fontsize'))686 sColor = self.getEntrySpecification(cyNode,'foregroundColor').encode('ascii')687 #print sColor688 iFind = sColor.find(',')689 # print iFind690 rColor = float(sColor[0:iFind])691 iFind2 = sColor.find(',', iFind+1)692 gColor = float(sColor[iFind+1:iFind2])693 bColor = float(sColor[iFind2+1:len(sColor)])694 695 dicEntry['foregroundColor'] = {'rColor' : rColor, 'gColor' : gColor, 'bColor' : bColor}696 #print dicEntry['foregroundColor']697 698 sColor = self.getEntrySpecification(cyNode,'backgroundColor').encode('ascii')699 #print sColor700 iFind = sColor.find(',')701 # print iFind702 rColor = float(sColor[0:iFind])703 iFind2 = sColor.find(',', iFind+1)704 gColor = float(sColor[iFind+1:iFind2])705 bColor = float(sColor[iFind2+1:len(sColor)])706 707 dicEntry['backgroundColor'] = {'rColor' : rColor, 'gColor' : gColor, 'bColor' : bColor}708 sGray = self.getEntrySpecification(cyNode,'grayScale')709 if sGray:710 dicEntry['grayScale'] = float(sGray.encode('ascii'))711 else:712 dicEntry['grayScale'] = 0.0713 714 fj = self.getEntrySpecification(cyNode,'fontJustification')715 if fj:716 fj = fj.encode('ascii')717 dicEntry['fontjustification'] = fj718 else:719 dicEntry['fontjustification'] = None720 dicEntry['property'] = self.getEntrySpecification(cyNode,'property')721 722 723 return dicEntry724 725 726 def setReportValues(self, cyRootNode):727 # Papersizes728 729 self.dicPage['topMargin'] = int(self.getEntrySpecification(cyRootNode[0],'topMargin'))730 self.dicPage['bottomMargin'] = int(self.getEntrySpecification(cyRootNode[0],'bottomMargin'))731 self.dicPage['leftMargin'] = int(self.getEntrySpecification(cyRootNode[0],'leftMargin'))732 self.dicPage['rightMargin'] = int(self.getEntrySpecification(cyRootNode[0],'rightMargin'))733 734 sPapersize = 'A4'735 try:736 sPapersize = self.getEntrySpecification(cyRootNode[0],'paperSize')737 except:738 sPapersize = 'A4'739 if sPapersize == 'A5':740 self.dicText['Papersize'] = self.pagesizes['A5']741 elif sPapersize == 'A6':742 self.dicText['Papersize'] = self.pagesizes['A6']743 else:744 self.dicText['Papersize'] = self.pagesizes['A4']745 746 747 self.dicPage['orientation'] = self.getEntrySpecification(cyRootNode[0],'orientation').encode('ascii')748 if self.dicPage['orientation'] =='Portrait':749 self.dicPage['papersizeX'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeX'))750 self.dicPage['papersizeY'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeY'))751 elif self.dicPage['orientation'] =='Landscape':752 self.dicPage['papersizeX'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeY'))753 self.dicPage['papersizeY'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeX'))754 else:755 self.dicPage['papersizeX'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeX'))756 self.dicPage['papersizeY'] = int(self.getEntrySpecification(cyRootNode[0],'papersizeY'))757 758 try:759 760 self.dicPage['SiteBackground_URL'] = self.getEntrySpecification(cyRootNode[0],'sitebackground_url').encode('ascii')761 self.dicPage['SiteBackgroundX'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_x'))762 self.dicPage['SiteBackgroundY'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_y'))763 self.dicPage['SiteBackgroundWidth'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_width'))764 self.dicPage['SiteBackgroundHeight'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_height'))765 self.dicPage['PropertyBG'] = self.getEntrySpecification(cyRootNode[0],'PropertyBG')766 except Exception, params:767 print Exception, params768 769 try:770 771 self.dicPage['SiteBackground_URL2'] = self.getEntrySpecification(cyRootNode[0],'sitebackground_url2').encode('ascii')772 self.dicPage['SiteBackgroundX2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_x2'))773 self.dicPage['SiteBackgroundY2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_y2'))774 self.dicPage['SiteBackgroundWidth2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_width2'))775 self.dicPage['SiteBackgroundHeight2'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_height2'))776 self.dicPage['PropertyBG2'] = self.getEntrySpecification(cyRootNode[0],'PropertyBG2')777 except Exception, params:778 print Exception, params779 780 try:781 782 self.dicPage['SiteBackground_URL3'] = self.getEntrySpecification(cyRootNode[0],'sitebackground_url3').encode('ascii')783 self.dicPage['SiteBackgroundX3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_x3'))784 self.dicPage['SiteBackgroundY3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_y3'))785 self.dicPage['SiteBackgroundWidth3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_width3'))786 self.dicPage['SiteBackgroundHeight3'] = int(self.getEntrySpecification(cyRootNode[0],'sitebackground_height3'))787 self.dicPage['PropertyBG3'] = self.getEntrySpecification(cyRootNode[0],'PropertyBG3')788 except Exception, params:789 print Exception, params790 791 792 793 #794 # Report Header795 #796 cyReportHeaderNode = self.getNode(cyRootNode, 'reportHeader')797 #print '------------------'798 #print cyReportHeaderNode799 #print cyReportHeaderNode[0].toxml()800 801 cyReportHeaderEntries = self.getNodes(cyReportHeaderNode[0], 'entry')802 #print '+++++++'803 #print cyReportHeaderEntries804 liRecord = []805 self.dicPage['headerX1'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posX1'))806 self.dicPage['headerX2'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posX2'))807 self.dicPage['headerY1'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posY1'))808 self.dicPage['headerY2'] = int(self.getEntrySpecification(cyReportHeaderNode[0],'posY2'))809 self.dicPage['beginReportHeaderX'] = self.dicPage['leftMargin'] + self.dicPage['headerX1']810 self.dicPage['endReportHeaderX'] = self.dicPage['headerX2']811 812 self.dicPage['beginReportHeaderY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['headerY1']813 self.dicPage['endReportHeaderY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['headerY2']814 self.dicPage['beginReportFooterX'] = self.dicPage['leftMargin'] 815 self.dicPage['endReportFooterX'] = self.dicPage['papersizeX'] - self.dicPage['rightMargin']816 817 self.dicPage['beginReportFooterY'] = self.dicPage['bottomMargin'] 818 self.dicPage['endReportFooterY'] = self.dicPage['bottomMargin'] 819 #820 # PageHeader821 #822 cyReportPageNode = self.getNode(cyRootNode, 'pageHeader')823 #print '------------------'824 #print cyReportPageNode825 #print cyReportPageNode[0].toxml()826 827 cyReportPageEntries = self.getNodes(cyReportPageNode[0], 'entry')828 #print '+++++++'829 #print cyReportPageEntries830 liRecord = []831 self.dicPage['pageX1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX1'))832 self.dicPage['pageX2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX2'))833 self.dicPage['pageY1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY1'))834 self.dicPage['pageY2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY2'))835 self.dicPage['beginPageHeaderX'] = self.dicPage['leftMargin'] + self.dicPage['pageX1']836 self.dicPage['endPageHeaderX'] = self.dicPage['pageX2']837 self.dicPage['beginPageHeaderY'] = self.dicPage['endReportHeaderY'] - self.dicPage['pageY1']838 self.dicPage['endPageHeaderY'] = self.dicPage['endReportHeaderY'] - self.dicPage['pageY2']839 840 841 #842 # Report-footer843 #844 cyReportFooterNode = self.getNode(cyRootNode, 'reportFooter')845 #print '------------------'846 #print cyReportFooterNode847 #print cyReportFooterNode[0].toxml()848 849 cyReportFooterEntries = self.getNodes(cyReportFooterNode[0], 'entry')850 #print '+++++++'851 #print cyReportFooterEntries852 liRecord = []853 854 self.dicPage['footerX1'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posX1'))855 self.dicPage['footerX2'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posX2'))856 self.dicPage['footerY1'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posY1'))857 self.dicPage['footerY2'] = int(self.getEntrySpecification(cyReportFooterNode[0],'posY2'))858 try:859 self.dicPage['ReportFootAppendToGroup'] = int(self.getEntrySpecification(cyReportFooterNode[0],'appendtogroup'))860 except:861 self.dicPage['ReportFootAppendToGroup'] = 0862 863 self.dicPage['beginReportFooterX'] = self.dicPage['leftMargin'] + self.dicPage['footerX1']864 self.dicPage['endReportFooterX'] = self.dicPage['footerX2']865 866 self.dicPage['beginReportFooterY'] = self.dicPage['bottomMargin'] + self.dicPage['footerY1']867 self.dicPage['endReportFooterY'] = self.dicPage['bottomMargin'] + self.dicPage['footerY2']868 869 #870 # Page -footer871 #872 cyReportPageNode = self.getNode(cyRootNode, 'pageFooter')873 874 #print '------------------'875 #print cyReportPageNode876 #print cyReportPageNode[0].toxml()877 878 cyReportPageEntries = self.getNodes(cyReportPageNode[0], 'entry')879 #print '+++++++'880 #print cyReportPageEntries881 liRecord = []882 self.dicPage['pageFooterX1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX1'))883 self.dicPage['pageFooterX2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posX2'))884 self.dicPage['pageFooterY1'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY1'))885 self.dicPage['pageFooterY2'] = int(self.getEntrySpecification(cyReportPageNode[0],'posY2'))886 try:887 self.dicPage['PageFootAppendToGroup'] = int(self.getEntrySpecification(cyReportPageNode[0],'appendtogroup'))888 except:889 self.dicPage['PageFootAppendToGroup'] = 0890 891 self.dicPage['beginPageFooterX'] = self.dicPage['leftMargin'] + self.dicPage['pageFooterX1']892 self.dicPage['endPageFooterX'] = self.dicPage['pageFooterX2']893 self.dicPage['beginPageFooterY'] = self.dicPage['pageFooterY2'] + self.dicPage['bottomMargin'] + self.dicPage['pageFooterY1']894 self.dicPage['beginPageFooterY_LastPage'] = self.dicPage['endReportFooterY'] + self.dicPage['pageFooterY2']895 self.dicPage['endPageFooterY'] = self.dicPage['bottomMargin'] + self.dicPage['pageFooterY1']896 self.dicPage['PrintRangeFirstSite'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['bottomMargin'] -self.dicPage['headerY1'] - self.dicPage['headerY2'] - self.dicPage['pageY1'] - self.dicPage['pageY2'] - self.dicPage['pageFooterY1'] - self.dicPage['pageFooterY2'] 897 self.dicPage['PrintRangeNextSites'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['bottomMargin'] - self.dicPage['pageY1'] - self.dicPage['pageY2'] - self.dicPage['pageFooterY1'] - self.dicPage['pageFooterY2'] 898 899 self.dicPage['beginPageHeaderOtherSitesY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['pageY1'] 900 self.dicPage['endPageHeaderOtherSitesY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['pageY2']901 #902 # calculate Sides903 #904 print "Side Values = ", self.dicPage['papersizeY'] , self.dicPage['topMargin'] , self.dicPage['headerY2'] , self.dicPage['endPageFooterY'] , self.dicPage['bottomMargin'] , self.dicPage['pageFooterY1']905 self.dicPage['reportDetailsY'] = self.dicPage['papersizeY'] - self.dicPage['topMargin'] - self.dicPage['headerY2'] - self.dicPage['bottomMargin'] - self.dicPage['pageFooterY2']906 907 908 909 910 911 #print "appendtogroup page, report = ", self.dicPage['PageFootAppendToGroup'] , self.dicPage['ReportFootAppendToGroup'] 912 913 cyGroupNode = self.getNode(cyRootNode, 'groups')914 915 self.dicPage['count'] = self.getEntrySpecification(cyGroupNode[0],'count')916 cyGroupEntries = self.getNodes(cyGroupNode[0], 'groupEntry')917 #print cyGroupEntries918 for k in range(len(cyGroupEntries)):919 cyGroupEntry = cyGroupEntries[k]920 self.dicPage[`k` + '_ChangeGroupBy'] = self.getEntrySpecification(cyGroupEntry,'changeGroupBy')921 self.dicPage[`k` + '_groupNumber'] = int(self.getEntrySpecification(cyGroupEntry,'number'))922 self.dicPage[`k` + '_groupResultSet'] = self.getEntrySpecification(cyGroupEntry,'resultSet')923 924 cyPageDetailsNodes = self.getNodes(cyGroupEntry, 'pageDetails')925 print'+++++++ cyPageDetailsNodes = ', cyPageDetailsNodes926 927 for i in range(len(cyPageDetailsNodes)):928 cyReportDetailsNode = cyPageDetailsNodes[i]929 cyReportDetailsEntries = self.getNodes(cyReportDetailsNode, 'entry')930 931 self.dicPage[`i` + '_detailsX1'] = int(self.getEntrySpecification(cyReportDetailsNode,'posX1'))932 self.dicPage[`i` + '_detailsX2'] = int(self.getEntrySpecification(cyReportDetailsNode,'posX2'))933 self.dicPage[`i` + '_detailsY1'] = int(self.getEntrySpecification(cyReportDetailsNode,'posY1'))934 self.dicPage[`i` + '_detailsY2'] = int(self.getEntrySpecification(cyReportDetailsNode,'posY2'))935 self.dicPage[`i` + '_detailslineY'] = int(self.getEntrySpecification(cyReportDetailsNode,'lineY'))...
permmod.py
Source:permmod.py
...62 self.user_staff.save()63 64 with self.login_user_context(self.user_super):65 66 self._home_page = create_page("home", "nav_playground.html", "en",67 created_by=self.user_super)68 69 # master page & master user70 71 self._master_page = create_page("master", "nav_playground.html", "en")72 73 # create master user74 master = User(username="master", email="master@django-cms.org", is_staff=True, is_active=True)75 master.set_password('master')76 master.save()77 master.user_permissions.add(Permission.objects.get(codename='add_text'))78 master.user_permissions.add(Permission.objects.get(codename='delete_text'))79 master.user_permissions.add(Permission.objects.get(codename='change_text'))80 81 self.user_master = create_page_user(self.user_super, master, grant_all=True)82 # create non global, non staff user83 self.user_non_global = User(username="nonglobal", is_active=True)84 self.user_non_global.set_password("nonglobal")85 self.user_non_global.save()86 87 # assign master user under home page88 assign_user_to_page(self.home_page, self.user_master,89 grant_on=ACCESS_DESCENDANTS, grant_all=True)90 91 # and to master page92 assign_user_to_page(self.master_page, self.user_master,93 grant_on=ACCESS_PAGE_AND_DESCENDANTS, grant_all=True)94 95 # slave page & slave user96 97 self._slave_page = create_page("slave-home", "nav_playground.html", "en",98 parent=self.master_page, created_by=self.user_super)99 100 slave = User(username='slave', email='slave@django-cms.org', is_staff=True)101 slave.set_password('slave')102 slave.save()103 slave.user_permissions.add(Permission.objects.get(codename='add_text'))104 slave.user_permissions.add(Permission.objects.get(codename='delete_text'))105 slave.user_permissions.add(Permission.objects.get(codename='change_text'))106 107 self.user_slave = create_page_user(self.user_super, slave, can_add_page=True,108 can_change_page=True, can_delete_page=True)109 110 assign_user_to_page(self.slave_page, self.user_slave, grant_all=True)111 112 # create page_b113 page_b = create_page("pageB", "nav_playground.html", "en", created_by=self.user_super)114 # Normal user115 normal = User(username='normal', email='normal@django-cms.org', is_active=True)116 normal.set_password('normal')117 normal.save()118 self.user_normal = create_page_user(self.user_master, normal)119 # it's allowed for the normal user to view the page120 assign_user_to_page(page_b, self.user_normal, can_view=True)121 self.user_normal = self.reload(self.user_normal)122 # create page_a - sample page from master123 124 page_a = create_page("pageA", "nav_playground.html", "en",125 created_by=self.user_super)126 assign_user_to_page(page_a, self.user_master, 127 can_add=True, can_change=True, can_delete=True, can_publish=True, 128 can_move_page=True, can_moderate=True)129 # publish after creating all drafts130 publish_page(self.home_page, self.user_super)131 132 publish_page(self.master_page, self.user_super)133 134 self.page_b = publish_page(page_b, self.user_super)135 # logg in as master, and request moderation for slave page and descendants136 self.request_moderation(self.slave_page, 7)137 138 @property139 def master_page(self):140 return self.reload(self._master_page)141 142 @property143 def slave_page(self):144 return self.reload(self._slave_page)145 146 @property147 def home_page(self):148 return self.reload(self._home_page)149 150 def _add_plugin(self, user, page):151 """152 Add a plugin using the test client to check for permissions.153 """154 with self.login_user_context(user):155 placeholder = page.placeholders.all()[0]156 post_data = {157 'language': 'en',158 'page_id': page.pk,159 'placeholder': placeholder.pk,160 'plugin_type': 'TextPlugin'161 }162 url = URL_CMS_PLUGIN_ADD % page.pk163 response = self.client.post(url, post_data)164 self.assertEqual(response.status_code, 200)165 self.assertTrue(response.content.isdigit())166 return response.content167 def test_super_can_add_page_to_root(self):168 with self.login_user_context(self.user_super):169 response = self.client.get(URL_CMS_PAGE_ADD)170 self.assertEqual(response.status_code, 200)171 172 def test_master_can_add_page_to_root(self):173 with self.login_user_context(self.user_master):174 response = self.client.get(URL_CMS_PAGE_ADD)175 self.assertEqual(response.status_code, 403)176 177 def test_slave_can_add_page_to_root(self):178 with self.login_user_context(self.user_slave):179 response = self.client.get(URL_CMS_PAGE_ADD)180 self.assertEqual(response.status_code, 403)181 182 def test_moderation_on_slave_home(self):183 self.assertEqual(self.slave_page.get_moderator_queryset().count(), 1)184 185 def test_slave_can_add_page_under_slave_home(self):186 with self.login_user_context(self.user_slave):187 # move to admin.py?188 # url = URL_CMS_PAGE_ADD + "?target=%d&position=last-child" % slave_page.pk189 190 # can he even access it over get?191 # response = self.client.get(url)192 # self.assertEqual(response.status_code, 200)193 194 # add page195 page = create_page("page", "nav_playground.html", "en",196 parent=self.slave_page, created_by=self.user_slave)197 # adds user_slave as page moderator for this page198 # public model shouldn't be available yet, because of the moderation199 # removed test cases since Title object does not inherit from Publisher anymore200 #self.assertObjectExist(Title.objects, slug=page_data['slug'])201 #self.assertObjectDoesNotExist(Title.objects.public(), slug=page_data['slug'])202 203 # moderators and approvement ok?204 self.assertEqual(page.get_moderator_queryset().count(), 1)205 self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)206 207 # must not have public object yet208 self.assertFalse(page.publisher_public)209 210 self.assertTrue(has_generic_permission(page.pk, self.user_slave, "publish", 1))211 212 # publish as slave, published as user_master before 213 publish_page(page, self.user_slave)214 215 # user_slave is moderator for this page216 # approve / publish as user_slave217 # user master should be able to approve aswell218 page = approve_page(page, self.user_slave)219 def test_page_added_by_slave_can_be_published_approved_by_user_master(self):220 # add page221 page = create_page("page", "nav_playground.html", "en",222 parent=self.slave_page, created_by=self.user_slave)223 # same as test_slave_can_add_page_under_slave_home 224 self.assertEqual(page.get_moderator_queryset().count(), 1)225 self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)226 227 # must not have public object yet228 self.assertFalse(page.publisher_public)229 230 self.assertTrue(has_generic_permission(page.pk, self.user_master, "publish", page.site.pk))231 # should be True user_master should have publish permissions for childred aswell232 # don't test for published since publishing must be approved233 publish_page(page, self.user_master)234 235 # user_master is moderator for top level page / but can't approve descendants?236 # approve / publish as user_master237 # user master should be able to approve descendants238 page = approve_page(page, self.user_master) 239 240 def test_super_can_add_plugin(self):241 self._add_plugin(self.user_super, page=self.slave_page)242 243 def test_master_can_add_plugin(self):244 self._add_plugin(self.user_master, page=self.slave_page)245 246 def test_slave_can_add_plugin(self):247 self._add_plugin(self.user_slave, page=self.slave_page)248 249 def test_same_order(self):250 # create 4 pages251 slugs = []252 for i in range(0, 4):253 page = create_page("page", "nav_playground.html", "en",254 parent=self.home_page)255 slug = page.title_set.drafts()[0].slug256 slugs.append(slug)257 258 # approve last 2 pages in reverse order259 for slug in reversed(slugs[2:]):260 page = self.assertObjectExist(Page.objects.drafts(), title_set__slug=slug)261 page = publish_page(page, self.user_master, True)262 self.check_published_page_attributes(page)263 264 def test_create_copy_publish(self):265 # create new page to copy266 page = create_page("page", "nav_playground.html", "en",267 parent=self.slave_page)268 269 # copy it under home page...270 # TODO: Use page.copy_page here271 with self.login_user_context(self.user_master):272 copied_page = self.copy_page(page, self.home_page)273 274 page = publish_page(copied_page, self.user_master, True)275 self.check_published_page_attributes(page)276 277 278 def test_create_publish_copy(self):279 # create new page to copy280 page = create_page("page", "nav_playground.html", "en",281 parent=self.home_page)282 283 page = publish_page(page, self.user_master, True)284 285 # copy it under master page...286 # TODO: Use page.copy_page here287 with self.login_user_context(self.user_master):288 copied_page = self.copy_page(page, self.master_page)289 290 self.check_published_page_attributes(page)291 copied_page = publish_page(copied_page, self.user_master, True)292 self.check_published_page_attributes(copied_page)293 294 295 def test_subtree_needs_approvement(self):296 # create page under slave_page297 page = create_page("parent", "nav_playground.html", "en",298 parent=self.home_page)299 self.assertFalse(page.publisher_public)300 301 # create subpage uner page302 subpage = create_page("subpage", "nav_playground.html", "en", parent=page)303 self.assertFalse(subpage.publisher_public)304 305 # publish both of them in reverse order 306 subpage = publish_page(subpage, self.user_master, True) 307 308 # subpage should not be published, because parent is not published 309 # yet, should be marked as `publish when parent`310 self.assertFalse(subpage.publisher_public) 311 312 # pagemoderator state must be set313 self.assertEqual(subpage.moderator_state, Page.MODERATOR_APPROVED_WAITING_FOR_PARENTS)314 315 # publish page (parent of subage), so subpage must be published also316 page = publish_page(page, self.user_master, True)317 self.assertNotEqual(page.publisher_public, None)318 319 # reload subpage, it was probably changed320 subpage = self.reload_page(subpage)321 322 # parent was published, so subpage must be also published..323 self.assertNotEqual(subpage.publisher_public, None) 324 325 #check attributes326 self.check_published_page_attributes(page)327 self.check_published_page_attributes(subpage)328 def test_subtree_with_super(self):329 # create page under root330 page = create_page("page", "nav_playground.html", "en")331 self.assertFalse(page.publisher_public)332 333 # create subpage under page334 subpage = create_page("subpage", "nav_playground.html", "en",335 parent=page)336 self.assertFalse(subpage.publisher_public)337 338 # tree id must be the same339 self.assertEqual(page.tree_id, subpage.tree_id)340 341 # publish both of them 342 page = self.reload(page)343 page = publish_page(page, self.user_super, True)344 # reload subpage, there were an tree_id change345 subpage = self.reload_page(subpage)346 self.assertEqual(page.tree_id, subpage.tree_id)347 348 subpage = publish_page(subpage, self.user_super, True)349 # tree id must stay the same350 self.assertEqual(page.tree_id, subpage.tree_id)351 352 # published pages must also have the same tree_id353 self.assertEqual(page.publisher_public.tree_id, subpage.publisher_public.tree_id)354 355 #check attributes356 self.check_published_page_attributes(page) 357 self.check_published_page_attributes(subpage)358 359 360 def test_super_add_page_to_root(self):361 """Create page which is not under moderation in root, and check if 362 some properties are correct.363 """364 # create page under root365 page = create_page("page", "nav_playground.html", "en")366 367 # public must not exist368 self.assertFalse(page.publisher_public)369 370 # moderator_state must be changed371 self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)372 373 374 def test_moderator_flags(self):375 """Add page under slave_home and check its flag376 """377 page = create_page("page", "nav_playground.html", "en",378 parent=self.slave_page)379 380 # moderator_state must be changed381 self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)382 383 # check publish box384 page = publish_page(page, self.user_slave)385 386 # page should request approvement now387 self.assertEqual(page.moderator_state, Page.MODERATOR_NEED_APPROVEMENT)388 389 # approve it by master390 # approve this page - but it doesn't get published yet, because 391 # slave home is not published392 page = approve_page(page, self.user_master)393 394 # public page must not exist because of parent395 self.assertFalse(page.publisher_public)396 397 # waiting for parents398 self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED_WAITING_FOR_PARENTS)399 400 # publish slave page401 slave_page = publish_page(self.slave_page, self.user_master)402 403 self.assertFalse(page.publisher_public)404 self.assertFalse(slave_page.publisher_public)405 406 # they must be approved first407 slave_page = approve_page(slave_page, self.user_master)408 409 # master is approved410 self.assertEqual(slave_page.moderator_state, Page.MODERATOR_APPROVED)411 412 # reload page413 page = self.reload_page(page)414 415 # page must be approved also now416 self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED)417 418 def test_plugins_get_published(self):419 # create page under root420 page = create_page("page", "nav_playground.html", "en")421 placeholder = page.placeholders.all()[0]422 add_plugin(placeholder, "TextPlugin", "en", body="test")423 # public must not exist424 self.assertEqual(CMSPlugin.objects.all().count(), 1)425 publish_page(page, self.user_super, True)426 self.assertEqual(CMSPlugin.objects.all().count(), 2)427 def test_remove_plugin_page_under_moderation(self):428 # login as slave and create page429 page = create_page("page", "nav_playground.html", "en", parent=self.slave_page)430 self.assertEqual(page.get_moderator_queryset().count(), 1)431 432 # add plugin433 placeholder = page.placeholders.all()[0]434 plugin = add_plugin(placeholder, "TextPlugin", "en", body="test")435 436 self.assertEqual(page.moderator_state, Page.MODERATOR_CHANGED)437 # publish page438 page = self.reload(page)439 page = publish_page(page, self.user_slave)440 441 # only the draft plugin should exist442 self.assertEqual(CMSPlugin.objects.all().count(), 1)443 444 # page should require approval445 self.assertEqual(page.moderator_state, Page.MODERATOR_NEED_APPROVEMENT)446 447 # master approves and publishes the page448 # first approve slave-home449 slave_page = self.reload(self.slave_page)450 publish_page(slave_page, self.user_master, approve=True)451 page = self.reload(page)452 page = publish_page(page, self.user_master, approve=True)453 454 # draft and public plugins should now exist455 self.assertEqual(CMSPlugin.objects.all().count(), 2)456 457 # login as slave and delete the plugin - should require moderation458 with self.login_user_context(self.user_slave):459 plugin_data = {460 'plugin_id': plugin.pk461 }462 remove_url = URL_CMS_PLUGIN_REMOVE463 response = self.client.post(remove_url, plugin_data)464 self.assertEquals(response.status_code, 200)465 466 # there should only be a public plugin - since the draft has been deleted467 self.assertEquals(CMSPlugin.objects.all().count(), 1)468 469 # reload the page as it's moderator value should have been set in pageadmin.remove_plugin470 self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED)471 page = self.reload_page(page)472 473 self.assertEqual(page.moderator_state, Page.MODERATOR_NEED_APPROVEMENT)474 475 # login as super user and approve/publish the page476 page = publish_page(page, self.user_super, approve=True)477 self.assertEqual(page.moderator_state, Page.MODERATOR_APPROVED)478 479 # there should now be 0 plugins480 self.assertEquals(CMSPlugin.objects.all().count(), 0)481 def test_superuser_can_view(self):482 with self.login_user_context(self.user_super):483 response = self.client.get("/en/pageb/")484 self.assertEqual(response.status_code, 200)485 def test_staff_can_view(self):486 with self.login_user_context(self.user_staff):487 response = self.client.get("/en/pageb/")488 self.assertEqual(response.status_code, 200)489 def test_user_normal_can_view(self):490 url = self.page_b.get_absolute_url(language='en')491 with self.login_user_context(self.user_normal):492 response = self.client.get(url)493 self.assertEqual(response.status_code, 200)494 with self.login_user_context(self.user_non_global):495 response = self.client.get(url)496 self.assertEqual(response.status_code, 404)497 # non logged in user498 response = self.client.get(url)499 self.assertEqual(response.status_code, 404)500 def test_user_globalpermission(self):501 # Global user502 with self.login_user_context(self.user_super):503 user_global = User(username="global", is_active=True)504 user_global.set_password("global")505 user_global.save()506 user_global = create_page_user(user_global, user_global)507 user_global.is_staff = False508 user_global.save() # Prevent is_staff permission509 global_page = create_page("global", "nav_playground.html", "en",510 published=True)511 global_page = publish_page(global_page, user_global, approve=True)512 # it's allowed for the normal user to view the page513 assign_user_to_page(global_page, user_global,514 global_permission=True, can_view=True)515 516 url = global_page.get_absolute_url('en')517 with self.login_user_context(user_global):518 response = self.client.get(url)519 self.assertEqual(response.status_code, 200)520 with self.login_user_context(self.user_non_global):521 response = self.client.get(url)522 self.assertEqual(response.status_code, 404)523 def test_anonymous_user_public_for_all(self):524 url = self.page_b.get_absolute_url('en')525 with SettingsOverride(CMS_PUBLIC_FOR='all'):526 response = self.client.get(url)527 self.assertEqual(response.status_code, 404)528 def test_anonymous_user_public_for_none(self):529 # default of when to show pages to anonymous user doesn't take530 # global permissions into account531 url = self.page_b.get_absolute_url('en')532 with SettingsOverride(CMS_PUBLIC_FOR=None):533 response = self.client.get(url)534 self.assertEqual(response.status_code, 404)535 536class PatricksMoveTest(SettingsOverrideTestCase):537 """538 Fixtures contains 3 users and 1 published page and some other stuff539 540 Users:541 1. `super`: superuser542 2. `master`: user with permissions to all applications543 3. `slave`: user assigned to page `slave-home`544 545 Pages:546 1. `home`:547 - published page548 - master can do anything on its subpages, but not on home!549 550 2. `master`:551 - published page552 - crated by super553 - `master` can do anything on it and its descendants554 - subpages:555 556 3. `slave-home`:557 - not published558 - assigned slave user which can add/change/delete/559 move/publish/moderate this page and its descendants560 - `master` user want to moderate this page and all descendants561 562 4. `pageA`:563 - created by super564 - master can add/change/delete on it and descendants 565 """566 settings_overrides = {567 'CMS_PERMISSION': True,568 'CMS_MODERATOR': True,569 }570 571 def setUp(self):572 # create super user573 self.user_super = User(username="super", is_staff=True, is_active=True, 574 is_superuser=True)575 self.user_super.set_password("super")576 self.user_super.save()577 with self.login_user_context(self.user_super):578 579 self._home_page = create_page("home", "nav_playground.html", "en",580 created_by=self.user_super)581 582 # master page & master user583 584 self._master_page = create_page("master", "nav_playground.html", "en")585 586 # create master user587 master = User.objects.create(username="master", email="master@django-cms.org", password="master")588 self.user_master = create_page_user(self.user_super, master, grant_all=True)589 590 # assign master user under home page591 assign_user_to_page(self.home_page, self.user_master,592 grant_on=ACCESS_DESCENDANTS, grant_all=True)593 594 # and to master page595 assign_user_to_page(self.master_page, self.user_master, grant_all=True)596 597 # slave page & slave user598 599 self._slave_page = create_page("slave-home", "nav_playground.html", "en",600 parent=self.master_page, created_by=self.user_super)601 slave = User(username='slave', email='slave@django-cms.org', is_staff=True, is_active=True)602 slave.set_password('slave')603 slave.save()604 self.user_slave = create_page_user(self.user_super, slave, can_add_page=True,605 can_change_page=True, can_delete_page=True)606 607 assign_user_to_page(self.slave_page, self.user_slave, grant_all=True)608 609 # create page_a - sample page from master610 611 page_a = create_page("pageA", "nav_playground.html", "en",612 created_by=self.user_super)613 assign_user_to_page(page_a, self.user_master, 614 can_add=True, can_change=True, can_delete=True, can_publish=True, 615 can_move_page=True, can_moderate=True)616 617 # publish after creating all drafts618 publish_page(self.home_page, self.user_super)619 publish_page(self.master_page, self.user_super)620 # logg in as master, and request moderation for slave page and descendants621 self.request_moderation(self.slave_page, 7)622 623 with self.login_user_context(self.user_slave):624 625 # all of them are under moderation... 626 self._pa = create_page("pa", "nav_playground.html", "en", parent=self.slave_page)627 self._pb = create_page("pb", "nav_playground.html", "en", parent=self.pa, position="right")628 self._pc = create_page("pc", "nav_playground.html", "en", parent=self.pb, position="right")629 630 self._pd = create_page("pd", "nav_playground.html", "en", parent=self.pb)631 self._pe = create_page("pe", "nav_playground.html", "en", parent=self.pd, position="right")632 633 self._pf = create_page("pf", "nav_playground.html", "en", parent=self.pe)634 self._pg = create_page("pg", "nav_playground.html", "en", parent=self.pf, position="right")635 self._ph = create_page("ph", "nav_playground.html", "en", parent=self.pf, position="right")636 637 self.assertFalse(self.pg.publisher_public)638 639 # login as master for approval640 publish_page(self.slave_page, self.user_master, approve=True)641 642 # publish and approve them all643 publish_page(self.pa, self.user_master, approve=True)644 publish_page(self.pb, self.user_master, approve=True)645 publish_page(self.pc, self.user_master, approve=True)646 publish_page(self.pd, self.user_master, approve=True)647 publish_page(self.pe, self.user_master, approve=True)648 publish_page(self.pf, self.user_master, approve=True)649 publish_page(self.pg, self.user_master, approve=True)650 publish_page(self.ph, self.user_master, approve=True)651 652 @property653 def master_page(self):654 return self.reload(self._master_page)655 656 @property657 def slave_page(self):658 return self.reload(self._slave_page)659 660 @property661 def home_page(self):662 return self.reload(self._home_page)663 664 @property665 def pa(self):666 return self.reload(self._pa)667 668 @property669 def pb(self):670 return self.reload(self._pb)671 672 @property673 def pc(self):674 return self.reload(self._pc)675 676 @property677 def pd(self):678 return self.reload(self._pd)679 680 @property681 def pe(self):682 return self.reload(self._pe)683 684 @property685 def pf(self):686 return self.reload(self._pf)687 688 @property689 def pg(self):690 return self.reload(self._pg)691 692 @property693 def ph(self):694 return self.reload(self._ph)695 696 def test_patricks_move(self):697 """698 699 Tests permmod when moving trees of pages.700 1. build following tree (master node is approved and published)701 702 slave-home703 / | \704 A B C705 / \ 706 D E 707 / | \ 708 F G H 709 2. perform move oparations:710 1. move G under C711 2. move E under G712 713 slave-home714 / | \715 A B C716 / \717 D G718 \ 719 E720 / \721 F H 722 723 3. approve nodes in following order:724 1. approve H725 2. approve G726 3. approve E727 4. approve F728 """729 # TODO: this takes 5 seconds to run on my MBP. That's TOO LONG!730 731 # perform movings under slave...732 user_master = User.objects.get(username='master')733 self.move_page(self.pg, self.pc)734 # We have to reload pe when using mptt >= 0.4.2, 735 # so that mptt realized that pg is no longer a child of pe736 self.move_page(self.pe, self.pg)737 738 # check urls - they should stay them same, there wasn't approved yet739 self.assertEqual(740 self.pg.publisher_public.get_absolute_url(), 741 u'%smaster/slave-home/pb/pe/pg/' % self.get_pages_root()742 )743 self.assertEqual(744 self.ph.publisher_public.get_absolute_url(),745 u'%smaster/slave-home/pb/pe/ph/' % self.get_pages_root()746 )747 748 # pg & pe should require approval749 self.assertEqual(self.pg.requires_approvement(), True)750 self.assertEqual(self.pe.requires_approvement(), True)751 self.assertEqual(self.ph.requires_approvement(), False)752 753 # login as master, and approve moves754 approve_page(self.pg, user_master)755 approve_page(self.pe, user_master)756 approve_page(self.ph, user_master)757 approve_page(self.pf, user_master)758 759 # public parent check after move760 self.assertEqual(self.pg.publisher_public.parent.pk, self.pc.publisher_public_id)761 self.assertEqual(self.pe.publisher_public.parent.pk, self.pg.publisher_public_id)762 self.assertEqual(self.ph.publisher_public.parent.pk, self.pe.publisher_public_id)763 764 # check if urls are correct after move765 self.assertEqual(766 self.pg.publisher_public.get_absolute_url(),767 u'%smaster/slave-home/pc/pg/' % self.get_pages_root()768 )769 self.assertEqual(770 self.ph.publisher_public.get_absolute_url(),771 u'%smaster/slave-home/pc/pg/pe/ph/' % self.get_pages_root()772 )773class ModeratorSwitchCommandTest(CMSTestCase):774 def test_switch_moderator_on(self):775 with SettingsOverride(CMS_MODERATOR=False):776 page1 = create_page('page', 'nav_playground.html', 'en', published=True)777 with SettingsOverride(CMS_MODERATOR=True):778 call_command('cms', 'moderator', 'on')779 page2 = get_page_from_path(page1.get_absolute_url().strip('/'))780 self.assertEqual(page1.get_absolute_url(), page2.get_absolute_url())781 782 def test_switch_moderator_off(self):783 with SettingsOverride(CMS_MODERATOR=True):784 page1 = create_page('page', 'nav_playground.html', 'en', published=True)785 with SettingsOverride(CMS_MODERATOR=False):786 page2 = get_page_from_path(page1.get_absolute_url().strip('/'))787 self.assertEqual(page1.get_absolute_url(), page2.get_absolute_url())788class ViewPermissionTests(SettingsOverrideTestCase):789 settings_overrides = {790 'CMS_MODERATOR': False,791 'CMS_PERMISSION': True,792 'CMS_PUBLIC_FOR': 'all',793 }794 795 def get_request(self, user=None):796 attrs = {797 'user': user or AnonymousUser(),798 'REQUEST': {},799 'session': {},800 }801 return type('Request', (object,), attrs)802 803 def test_public_for_all_staff(self):804 request = self.get_request()805 request.user.is_staff = True806 page = Page()807 page.pk = 1808 self.assertTrue(page.has_view_permission(request))809 def test_public_for_all_staff_assert_num_queries(self):810 request = self.get_request()811 request.user.is_staff = True812 page = Page()813 page.pk = 1814 with self.assertNumQueries(0):815 page.has_view_permission(request)816 def test_public_for_all(self):817 user = User.objects.create_user('user', 'user@domain.com', 'user')818 request = self.get_request(user)819 page = Page()820 page.pk = 1821 page.level = 0822 page.tree_id = 1823 self.assertTrue(page.has_view_permission(request))824 def test_public_for_all_num_queries(self):825 user = User.objects.create_user('user', 'user@domain.com', 'user')826 request = self.get_request(user)827 site = Site()828 site.pk = 1829 page = Page()830 page.pk = 1831 page.level = 0832 page.tree_id = 1833 with self.assertNumQueries(3):834 """835 The queries are:836 The current Site837 PagePermission query for affected pages838 GlobalpagePermission query for user839 """840 page.has_view_permission(request)841 842 def test_unauthed(self):843 request = self.get_request()844 page = Page()845 page.pk = 1846 page.level = 0847 page.tree_id = 1848 self.assertTrue(page.has_view_permission(request))849 850 def test_unauthed_num_queries(self):851 request = self.get_request()852 site = Site()853 site.pk = 1854 page = Page()855 page.pk = 1856 page.level = 0857 page.tree_id = 1858 with self.assertNumQueries(1):859 """860 The query is:861 PagePermission query for affected pages862 """863 page.has_view_permission(request)864 865 def test_authed_basic_perm(self):866 with SettingsOverride(CMS_PUBLIC_FOR='staff'):867 user = User.objects.create_user('user', 'user@domain.com', 'user')868 user.user_permissions.add(Permission.objects.get(codename='view_page'))869 request = self.get_request(user)870 page = Page()871 page.pk = 1872 page.level = 0873 page.tree_id = 1874 self.assertTrue(page.has_view_permission(request))875 876 def test_authed_basic_perm_num_queries(self):877 site = Site()878 site.pk = 1879 with SettingsOverride(CMS_PUBLIC_FOR='staff'):880 user = User.objects.create_user('user', 'user@domain.com', 'user')881 user.user_permissions.add(Permission.objects.get(codename='view_page'))882 request = self.get_request(user)883 page = Page()884 page.pk = 1885 page.level = 0886 page.tree_id = 1887 with self.assertNumQueries(5):888 """889 The queries are:890 The site891 PagePermission query for affected pages892 GlobalpagePermission query for user893 Generic django permission lookup894 content type lookup by permission lookup895 """896 page.has_view_permission(request)897 898 def test_authed_no_access(self):899 with SettingsOverride(CMS_PUBLIC_FOR='staff'):900 user = User.objects.create_user('user', 'user@domain.com', 'user')901 request = self.get_request(user)902 page = Page()903 page.pk = 1904 page.level = 0905 page.tree_id = 1906 self.assertFalse(page.has_view_permission(request))907 908 def test_unauthed_no_access(self):909 with SettingsOverride(CMS_PUBLIC_FOR='staff'):910 request = self.get_request()911 page = Page()912 page.pk = 1913 page.level = 0914 page.tree_id = 1915 self.assertFalse(page.has_view_permission(request))916 917 def test_unauthed_no_access_num_queries(self):918 site = Site()919 site.pk = 1920 request = self.get_request()921 page = Page()922 page.pk = 1923 page.level = 0924 page.tree_id = 1925 with self.assertNumQueries(1):926 page.has_view_permission(request)927 928 def test_page_permissions(self):929 with SettingsOverride(CMS_PUBLIC_FOR='staff'):930 user = User.objects.create_user('user', 'user@domain.com', 'user')931 request = self.get_request(user)932 page = create_page('A', 'nav_playground.html', 'en')933 PagePermission.objects.create(can_view=True, user=user, page=page)934 self.assertTrue(page.has_view_permission(request))935 936 def test_page_permissions_view_groups(self):937 with SettingsOverride(CMS_PUBLIC_FOR='staff'):938 user = User.objects.create_user('user', 'user@domain.com', 'user')939 group = Group.objects.create(name='testgroup')940 group.user_set.add(user)941 request = self.get_request(user)942 page = create_page('A', 'nav_playground.html', 'en')943 PagePermission.objects.create(can_view=True, group=group, page=page)944 self.assertTrue(page.has_view_permission(request))945 946 def test_global_permission(self):947 with SettingsOverride(CMS_PUBLIC_FOR='staff'):948 user = User.objects.create_user('user', 'user@domain.com', 'user')949 GlobalPagePermission.objects.create(can_view=True, user=user)950 request = self.get_request(user)951 page = Page()952 page.pk = 1953 page.level = 0954 page.tree_id = 1...
page.py
Source:page.py
...20import datetime21import os.path22class PagesTestCase(CMSTestCase):23 24 def test_add_page(self):25 """26 Test that the add admin page could be displayed via the admin27 """28 superuser = self.get_superuser()29 with self.login_user_context(superuser):30 response = self.client.get(URL_CMS_PAGE_ADD)31 self.assertEqual(response.status_code, 200)32 def test_create_page(self):33 """34 Test that a page can be created via the admin35 """36 page_data = self.get_new_page_data()37 superuser = self.get_superuser()38 with self.login_user_context(superuser):39 response = self.client.post(URL_CMS_PAGE_ADD, page_data)40 self.assertRedirects(response, URL_CMS_PAGE)41 title = Title.objects.get(slug=page_data['slug'])42 self.assertNotEqual(title, None)43 page = title.page44 page.published = True45 page.save()46 self.assertEqual(page.get_title(), page_data['title'])47 self.assertEqual(page.get_slug(), page_data['slug'])48 self.assertEqual(page.placeholders.all().count(), 2)49 50 # were public instanes created?51 title = Title.objects.drafts().get(slug=page_data['slug'])52 53 def test_slug_collision(self):54 """55 Test a slug collision56 """57 page_data = self.get_new_page_data()58 # create first page59 superuser = self.get_superuser()60 with self.login_user_context(superuser):61 response = self.client.post(URL_CMS_PAGE_ADD, page_data)62 self.assertRedirects(response, URL_CMS_PAGE)63 64 #page1 = Title.objects.get(slug=page_data['slug']).page65 # create page with the same page_data66 67 response = self.client.post(URL_CMS_PAGE_ADD, page_data)68 69 if settings.i18n_installed:70 self.assertEqual(response.status_code, 302)71 # did we got right redirect?72 self.assertEqual(response['Location'].endswith(URL_CMS_PAGE), True)73 else:74 self.assertEqual(response.status_code, 200)75 self.assertEqual(response['Location'].endswith(URL_CMS_PAGE_ADD), True)76 # TODO: check for slug collisions after move77 # TODO: check for slug collisions with different settings 78 79 def test_details_view(self):80 """81 Test the details view82 """83 superuser = self.get_superuser()84 with self.login_user_context(superuser):85 response = self.client.get(self.get_pages_root())86 self.assertEqual(response.status_code, 404)87 page = create_page('test page 1', "nav_playground.html", "en")88 response = self.client.get(self.get_pages_root())89 self.assertEqual(response.status_code, 404)90 self.assertTrue(page.publish())91 create_page("test page 2", "nav_playground.html", "en", 92 parent=page, published=True)93 homepage = Page.objects.get_home()94 self.assertTrue(homepage.get_slug(), 'test-page-1')95 response = self.client.get(self.get_pages_root())96 self.assertEqual(response.status_code, 200)97 def test_edit_page(self):98 """99 Test that a page can edited via the admin100 """101 superuser = self.get_superuser()102 with self.login_user_context(superuser):103 page_data = self.get_new_page_data()104 response = self.client.post(URL_CMS_PAGE_ADD, page_data)105 page = Page.objects.get(title_set__slug=page_data['slug'])106 response = self.client.get('/admin/cms/page/%s/' %page.id)107 self.assertEqual(response.status_code, 200)108 page_data['title'] = 'changed title'109 response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)110 self.assertRedirects(response, URL_CMS_PAGE)111 self.assertEqual(page.get_title(), 'changed title')112 113 def test_meta_description_and_keywords_fields_from_admin(self):114 """115 Test that description and keywords tags can be set via the admin116 """117 superuser = self.get_superuser()118 with self.login_user_context(superuser):119 page_data = self.get_new_page_data()120 page_data["meta_description"] = "I am a page"121 page_data["meta_keywords"] = "page,cms,stuff"122 response = self.client.post(URL_CMS_PAGE_ADD, page_data)123 page = Page.objects.get(title_set__slug=page_data['slug'])124 response = self.client.get('/admin/cms/page/%s/' %page.id)125 self.assertEqual(response.status_code, 200)126 page_data['meta_description'] = 'I am a duck'127 response = self.client.post('/admin/cms/page/%s/' %page.id, page_data)128 self.assertRedirects(response, URL_CMS_PAGE)129 page = Page.objects.get(title_set__slug=page_data["slug"])130 self.assertEqual(page.get_meta_description(), 'I am a duck')131 self.assertEqual(page.get_meta_keywords(), 'page,cms,stuff')132 def test_meta_description_and_keywords_from_template_tags(self):133 from django import template134 superuser = self.get_superuser()135 with self.login_user_context(superuser):136 page_data = self.get_new_page_data()137 page_data["title"] = "Hello"138 page_data["meta_description"] = "I am a page"139 page_data["meta_keywords"] = "page,cms,stuff"140 self.client.post(URL_CMS_PAGE_ADD, page_data)141 page = Page.objects.get(title_set__slug=page_data['slug'])142 self.client.post('/admin/cms/page/%s/' %page.id, page_data)143 t = template.Template("{% load cms_tags %}{% page_attribute title %} {% page_attribute meta_description %} {% page_attribute meta_keywords %}")144 req = HttpRequest()145 page.published = True146 page.save()147 req.current_page = page 148 req.REQUEST = {}149 self.assertEqual(t.render(template.Context({"request": req})), "Hello I am a page page,cms,stuff")150 151 152 def test_copy_page(self):153 """154 Test that a page can be copied via the admin155 """156 page_a = create_page("page_a", "nav_playground.html", "en")157 page_a_a = create_page("page_a_a", "nav_playground.html", "en",158 parent=page_a)159 create_page("page_a_a_a", "nav_playground.html", "en", parent=page_a_a)160 161 page_b = create_page("page_b", "nav_playground.html", "en")162 page_b_a = create_page("page_b", "nav_playground.html", "en", 163 parent=page_b)164 165 count = Page.objects.drafts().count()166 167 superuser = self.get_superuser()168 with self.login_user_context(superuser):169 self.copy_page(page_a, page_b_a)170 171 self.assertEqual(Page.objects.drafts().count() - count, 3)172 173 174 def test_language_change(self):175 superuser = self.get_superuser()176 with self.login_user_context(superuser):177 page_data = self.get_new_page_data()178 self.client.post(URL_CMS_PAGE_ADD, page_data)179 pk = Page.objects.all()[0].pk180 response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"en" })181 self.assertEqual(response.status_code, 200)182 response = self.client.get("/admin/cms/page/%s/" % pk, {"language":"de" })183 self.assertEqual(response.status_code, 200)184 185 def test_move_page(self):186 superuser = self.get_superuser()187 with self.login_user_context(superuser):188 page_data1 = self.get_new_page_data()189 self.client.post(URL_CMS_PAGE_ADD, page_data1)190 page_data2 = self.get_new_page_data()191 self.client.post(URL_CMS_PAGE_ADD, page_data2)192 page_data3 = self.get_new_page_data()193 self.client.post(URL_CMS_PAGE_ADD, page_data3)194 page1 = Page.objects.all()[0]195 page2 = Page.objects.all()[1]196 page3 = Page.objects.all()[2]197 # move pages198 response = self.client.post("/admin/cms/page/%s/move-page/" % page3.pk, {"target": page2.pk, "position": "last-child"})199 self.assertEqual(response.status_code, 200)200 response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "last-child"})201 self.assertEqual(response.status_code, 200)202 # check page2 path and url203 page2 = Page.objects.get(pk=page2.pk)204 self.assertEqual(page2.get_path(), page_data1['slug']+"/"+page_data2['slug'])205 self.assertEqual(page2.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/")206 # check page3 path and url207 page3 = Page.objects.get(pk=page3.pk)208 self.assertEqual(page3.get_path(), page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug'])209 self.assertEqual(page3.get_absolute_url(), self.get_pages_root()+page_data1['slug']+"/"+page_data2['slug']+"/"+page_data3['slug']+"/")210 # publish page 1 (becomes home)211 page1 = Page.objects.get(pk=page1.pk)212 page1.publish()213 public_page1 = page1.publisher_public214 self.assertEqual(public_page1.get_path(), '')215 # check that page2 and page3 url have changed216 page2 = Page.objects.get(pk=page2.pk)217 page2.publish()218 public_page2 = page2.publisher_public219 self.assertEqual(public_page2.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/")220 page3 = Page.objects.get(pk=page3.pk)221 page3.publish()222 public_page3 = page3.publisher_public223 self.assertEqual(public_page3.get_absolute_url(), self.get_pages_root()+page_data2['slug']+"/"+page_data3['slug']+"/")224 # move page2 back to root and check path of 2 and 3225 response = self.client.post("/admin/cms/page/%s/move-page/" % page2.pk, {"target": page1.pk, "position": "right"})226 self.assertEqual(response.status_code, 200)227 page1 = Page.objects.get(pk=page1.pk)228 self.assertEqual(page1.get_path(), page_data1['slug'])229 page2 = Page.objects.get(pk=page2.pk)230 self.assertEqual(page2.get_path(), page_data2['slug'])231 page3 = Page.objects.get(pk=page3.pk)232 self.assertEqual(page3.get_path(), page_data2['slug']+"/"+page_data3['slug'])233 234 def test_move_page_inherit(self):235 parent = create_page("Parent", 'col_three.html', "en")236 child = create_page("Child", settings.CMS_TEMPLATE_INHERITANCE_MAGIC,237 "en", parent=parent)238 self.assertEqual(child.get_template(), parent.get_template())239 child.move_page(parent, 'left')240 self.assertEqual(child.get_template(), parent.get_template())241 242 243 def test_add_placeholder(self):244 # create page245 page = create_page("Add Placeholder", "nav_playground.html", "en",246 position="last-child", published=True, in_navigation=True)247 page.template = 'add_placeholder.html'248 page.save()249 url = page.get_absolute_url()250 response = self.client.get(url)251 self.assertEqual(200, response.status_code)252 path = os.path.join(settings.PROJECT_DIR, 'templates', 'add_placeholder.html')253 f = open(path, 'r')254 old = f.read()255 f.close()256 new = old.replace(257 '<!-- SECOND_PLACEHOLDER -->',258 '{% placeholder second_placeholder %}'259 )260 f = open(path, 'w')261 f.write(new)262 f.close()263 response = self.client.get(url)264 self.assertEqual(200, response.status_code)265 f = open(path, 'w')266 f.write(old)267 f.close()268 def test_sitemap_login_required_pages(self):269 """270 Test that CMSSitemap object contains only published,public (login_required=False) pages271 """272 create_page("page", "nav_playground.html", "en", login_required=True,273 published=True, in_navigation=True)274 self.assertEqual(CMSSitemap().items().count(),0)275 def test_edit_page_other_site_and_language(self):276 """277 Test that a page can edited via the admin when your current site is278 different from the site you are editing and the language isn't available279 for the current site.280 """281 site = Site.objects.create(domain='otherlang', name='otherlang')282 # Change site for this session283 page_data = self.get_new_page_data()284 page_data['site'] = site.pk285 page_data['title'] = 'changed title'286 TESTLANG = settings.CMS_SITE_LANGUAGES[site.pk][0]287 page_data['language'] = TESTLANG288 superuser = self.get_superuser()289 with self.login_user_context(superuser):290 response = self.client.post(URL_CMS_PAGE_ADD, page_data)291 self.assertRedirects(response, URL_CMS_PAGE)292 page = Page.objects.get(title_set__slug=page_data['slug'])293 with LanguageOverride(TESTLANG):294 self.assertEqual(page.get_title(), 'changed title')295 296 def test_flat_urls(self):297 with SettingsOverride(CMS_FLAT_URLS=True):298 home_slug = "home"299 child_slug = "child"300 grandchild_slug = "grandchild"301 home = create_page(home_slug, "nav_playground.html", "en",302 published=True, in_navigation=True)303 home.publish()304 child = create_page(child_slug, "nav_playground.html", "en",305 parent=home, published=True, in_navigation=True)306 child.publish()307 grandchild = create_page(grandchild_slug, "nav_playground.html", "en",308 parent=child, published=True, in_navigation=True)309 grandchild.publish()310 response = self.client.get(home.get_absolute_url())311 self.assertEqual(response.status_code, 200)312 response = self.client.get(child.get_absolute_url())313 self.assertEqual(response.status_code, 200)314 response = self.client.get(grandchild.get_absolute_url())315 self.assertEqual(response.status_code, 200)316 self.assertFalse(child.get_absolute_url() in grandchild.get_absolute_url())317 def test_templates(self):318 """319 Test the inheritance magic for templates320 """321 parent = create_page("parent", "nav_playground.html", "en")322 child = create_page("child", "nav_playground.html", "en", parent=parent)323 child.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC324 child.save()325 self.assertEqual(child.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)326 self.assertEqual(parent.get_template_name(), child.get_template_name())327 parent.template = settings.CMS_TEMPLATE_INHERITANCE_MAGIC328 parent.save()329 self.assertEqual(parent.template, settings.CMS_TEMPLATE_INHERITANCE_MAGIC)330 self.assertEqual(parent.get_template(), settings.CMS_TEMPLATES[0][0])331 self.assertEqual(parent.get_template_name(), settings.CMS_TEMPLATES[0][1])332 333 def test_delete_with_plugins(self):334 """335 Check that plugins and placeholders get correctly deleted when we delete336 a page!337 """338 page = create_page("page", "nav_playground.html", "en")339 page.rescan_placeholders() # create placeholders340 placeholder = page.placeholders.all()[0]341 plugin_base = CMSPlugin(342 plugin_type='TextPlugin',343 placeholder=placeholder, 344 position=1, 345 language=settings.LANGUAGES[0][0]346 )347 plugin_base.insert_at(None, position='last-child', save=False)348 349 plugin = Text(body='')350 plugin_base.set_base_attr(plugin)351 plugin.save()352 self.assertEqual(CMSPlugin.objects.count(), 1)353 self.assertEqual(Text.objects.count(), 1)354 self.assertTrue(Placeholder.objects.count() > 0)355 page.delete()356 self.assertEqual(CMSPlugin.objects.count(), 0)357 self.assertEqual(Text.objects.count(), 0)358 self.assertEqual(Placeholder.objects.count(), 0)359 360 def test_get_page_from_request_on_non_cms_admin(self):361 request = self.get_request(362 reverse('admin:sampleapp_category_change', args=(1,))363 )364 page = get_page_from_request(request)365 self.assertEqual(page, None)366 367 def test_get_page_from_request_on_cms_admin(self):368 page = create_page("page", "nav_playground.html", "en")369 request = self.get_request(370 reverse('admin:cms_page_change', args=(page.pk,))371 )372 found_page = get_page_from_request(request)373 self.assertTrue(found_page)374 self.assertEqual(found_page.pk, page.pk)375 376 def test_get_page_from_request_on_cms_admin_nopage(self):377 request = self.get_request(378 reverse('admin:cms_page_change', args=(1,))379 )380 page = get_page_from_request(request)381 self.assertEqual(page, None)382 383 def test_get_page_from_request_cached(self):384 mock_page = 'hello world'385 request = self.get_request(386 reverse('admin:sampleapp_category_change', args=(1,))387 )388 request._current_page_cache = mock_page389 page = get_page_from_request(request)390 self.assertEqual(page, mock_page)391 392 def test_get_page_from_request_nopage(self):393 request = self.get_request('/')394 page = get_page_from_request(request)395 self.assertEqual(page, None)396 397 def test_get_page_from_request_with_page_404(self):398 page = create_page("page", "nav_playground.html", "en", published=True)399 page.publish()400 request = self.get_request('/does-not-exist/')401 found_page = get_page_from_request(request)402 self.assertEqual(found_page, None)403 404 def test_get_page_from_request_with_page_preview(self):405 page = create_page("page", "nav_playground.html", "en")406 request = self.get_request('%s?preview' % page.get_absolute_url())407 request.user.is_staff = False408 found_page = get_page_from_request(request)409 self.assertEqual(found_page, None)410 superuser = self.get_superuser()411 with self.login_user_context(superuser):412 request = self.get_request('%s?preview&draft' % page.get_absolute_url())413 found_page = get_page_from_request(request)414 self.assertTrue(found_page)415 self.assertEqual(found_page.pk, page.pk)416 417 def test_get_page_from_request_on_cms_admin_with_editplugin(self):418 page = create_page("page", "nav_playground.html", "en")419 request = self.get_request(420 reverse('admin:cms_page_change', args=(page.pk,)) + 'edit-plugin/42/'421 )422 found_page = get_page_from_request(request)423 self.assertTrue(found_page)424 self.assertEqual(found_page.pk, page.pk)425 426 def test_get_page_from_request_on_cms_admin_with_editplugin_nopage(self):427 request = self.get_request(428 reverse('admin:cms_page_change', args=(1,)) + 'edit-plugin/42/'429 )430 page = get_page_from_request(request)431 self.assertEqual(page, None)432 433 def test_page_already_expired(self):434 """435 Test that a page which has a end date in the past gives a 404, not a436 500.437 """438 yesterday = datetime.date.today() - datetime.timedelta(days=1)439 with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):440 page = create_page('page', 'nav_playground.html', 'en',441 publication_end_date=yesterday, published=True)442 resp = self.client.get(page.get_absolute_url('en'))443 self.assertEqual(resp.status_code, 404)444 445 def test_existing_overwrite_url(self):446 with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):447 create_page('home', 'nav_playground.html', 'en', published=True)448 create_page('boo', 'nav_playground.html', 'en', published=True)449 data = {450 'title': 'foo',451 'overwrite_url': '/boo/',452 'slug': 'foo',453 'language': 'en',454 'template': 'nav_playground.html',455 'site': 1,456 }457 form = PageForm(data)458 self.assertFalse(form.is_valid())459 self.assertTrue('overwrite_url' in form.errors)460 461 def test_page_urls(self):462 page1 = create_page('test page 1', 'nav_playground.html', 'en',463 published=True)464 page2 = create_page('test page 2', 'nav_playground.html', 'en',465 published=True, parent=page1)466 page3 = create_page('test page 3', 'nav_playground.html', 'en',467 published=True, parent=page2)468 page4 = create_page('test page 4', 'nav_playground.html', 'en',469 published=True)470 page5 = create_page('test page 5', 'nav_playground.html', 'en',471 published=True, parent=page4)472 self.assertEqual(page1.get_absolute_url(),473 self.get_pages_root()+'')474 self.assertEqual(page2.get_absolute_url(),475 self.get_pages_root()+'test-page-2/')476 self.assertEqual(page3.get_absolute_url(),477 self.get_pages_root()+'test-page-2/test-page-3/')478 self.assertEqual(page4.get_absolute_url(),479 self.get_pages_root()+'test-page-4/')480 self.assertEqual(page5.get_absolute_url(),481 self.get_pages_root()+'test-page-4/test-page-5/')482 page3 = self.move_page(page3, page1)483 self.assertEqual(page3.get_absolute_url(),484 self.get_pages_root()+'test-page-3/')485 page5 = self.move_page(page5, page2)486 self.assertEqual(page5.get_absolute_url(),487 self.get_pages_root()+'test-page-2/test-page-5/')488 page3 = self.move_page(page3, page4)489 self.assertEqual(page3.get_absolute_url(),490 self.get_pages_root()+'test-page-4/test-page-3/')491 492 def test_home_slug_not_accessible(self):493 with SettingsOverride(CMS_MODERATOR=False, CMS_PERMISSION=False):494 page = create_page('page', 'nav_playground.html', 'en', published=True)495 self.assertEqual(page.get_absolute_url('en'), '/')496 resp = self.client.get('/en/')497 self.assertEqual(resp.status_code, HttpResponse.status_code)498 resp = self.client.get('/en/page/')499 self.assertEqual(resp.status_code, HttpResponseNotFound.status_code)500 def test_public_home_page_replaced(self):501 """Test that publishing changes to the home page doesn't move the public version"""502 home = create_page('home', 'nav_playground.html', 'en', published = True, slug = 'home')503 self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')504 home.publish()505 self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')506 other = create_page('other', 'nav_playground.html', 'en', published = True, slug = 'other')507 other.publish()508 self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')509 self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')510 home = Page.objects.get(pk = home.id)511 home.in_navigation = True512 home.save()513 home.publish()514 self.assertEqual(Page.objects.drafts().get_home().get_slug(), 'home')515 self.assertEqual(Page.objects.public().get_home().get_slug(), 'home')516class NoAdminPageTests(CMSTestCase):517 urls = 'project.noadmin_urls'518 519 def setUp(self):520 admin = 'django.contrib.admin'521 noadmin_apps = [app for app in settings.INSTALLED_APPS if not app == admin]522 self._ctx = SettingsOverride(INSTALLED_APPS=noadmin_apps)523 self._ctx.__enter__()524 525 def tearDown(self):526 self._ctx.__exit__(None, None, None)527 528 def test_get_page_from_request_fakeadmin_nopage(self):529 request = self.get_request('/admin/')530 page = get_page_from_request(request)531 self.assertEqual(page, None)532class PreviousFilteredSiblingsTests(CMSTestCase):533 def test_with_publisher(self):534 home = create_page('home', 'nav_playground.html', 'en', published=True)535 home.publish()536 other = create_page('other', 'nav_playground.html', 'en', published=True)537 other.publish()538 other = Page.objects.get(pk=other.pk)539 home = Page.objects.get(pk=home.pk)540 self.assertEqual(other.get_previous_filtered_sibling(), home)541 self.assertEqual(home.get_previous_filtered_sibling(), None)542 543 def test_multisite(self):544 firstsite = Site.objects.create(name='first', domain='first.com')545 secondsite = Site.objects.create(name='second', domain='second.com')546 home = create_page('home', 'nav_playground.html', 'en', published=True, site=firstsite)547 home.publish()548 other = create_page('other', 'nav_playground.html', 'en', published=True, site=secondsite)549 other.publish()550 other = Page.objects.get(pk=other.pk)551 home = Page.objects.get(pk=home.pk)552 self.assertEqual(other.get_previous_filtered_sibling(), None)553 self.assertEqual(home.get_previous_filtered_sibling(), None)...
cms_tags.py
Source:cms_tags.py
...275 if choice['query_string'] != query_string:276 unique_choices.append(choice)277 query_string = choice['query_string']278 return {'title': spec.title(), 'choices' : unique_choices}279def _show_placeholder_for_page(context, placeholder_name, page_lookup, lang=None,280 site=None, cache_result=True):281 """282 Shows the content of a page with a placeholder name and given lookup283 arguments in the given language.284 This is useful if you want to have some more or less static content that is285 shared among many pages, such as a footer.286 See _get_page_by_untyped_arg() for detailed information on the allowed types287 and their interpretation for the page_lookup argument.288 """289 validate_placeholder_name(placeholder_name)290 291 request = context.get('request', False)292 site_id = get_site_id(site)293 if not request:294 return {'content': ''}295 if lang is None:296 lang = get_language_from_request(request)297 content = None298 if cache_result:299 cache_key = _get_cache_key('_show_placeholder_for_page', page_lookup, lang, site_id)+'_placeholder:'+placeholder_name300 content = cache.get(cache_key)301 if not content:302 page = _get_page_by_untyped_arg(page_lookup, request, site_id)303 if not page:304 return {'content': ''}305 try:306 placeholder = page.placeholders.get(slot=placeholder_name)307 except Placeholder.DoesNotExist:308 if settings.DEBUG:309 raise310 return {'content': ''}311 baseqs = get_cmsplugin_queryset(request)312 plugins = baseqs.filter(313 placeholder=placeholder,314 language=lang,315 placeholder__slot__iexact=placeholder_name,316 parent__isnull=True317 ).order_by('position').select_related()318 c = render_plugins(plugins, context, placeholder)319 content = "".join(c)320 if cache_result:321 cache.set(cache_key, content, settings.CMS_CACHE_DURATIONS['content'])322 if content:323 return {'content': mark_safe(content)}324 return {'content': ''}325class ShowPlaceholderById(InclusionTag):326 template = 'cms/content.html'327 name = 'show_placeholder_by_id'328 329 options = Options(330 Argument('placeholder_name'),331 Argument('reverse_id'),332 Argument('lang', required=False, default=None),333 Argument('site', required=False, default=None),334 )335 336 def get_context(self, *args, **kwargs):337 return _show_placeholder_for_page(**self.get_kwargs(*args, **kwargs))338 339 def get_kwargs(self, context, placeholder_name, reverse_id, lang, site):340 return {341 'context': context,342 'placeholder_name': placeholder_name,343 'page_lookup': reverse_id,344 'lang': lang,345 'site': site346 }347register.tag(ShowPlaceholderById)348register.tag('show_placeholder', ShowPlaceholderById)349class ShowUncachedPlaceholderById(ShowPlaceholderById):350 name = 'show_uncached_placeholder_by_id'351 def get_kwargs(self, *args, **kwargs):...
moderator.py
Source:moderator.py
...133 moderator = qs.select_related()[0]134 except IndexError:135 return PageModerator.MAX_MODERATION_LEVEL, False136 return moderator.page.level, True137def approve_page(request, page):138 """Main approving function. Two things can happen here, depending on user139 level:140 141 1.) User is somewhere in the approvement path, but not on the top. In this142 case just mark this page as approved by this user.143 144 2.) User is on top of approvement path. Draft page with all dependencies 145 will be `copied` to public model, page states log will be cleaned. 146 147 """148 moderation_level, moderation_required = get_test_moderation_level(page, request.user, False)149 if not moderator_should_approve(request, page):150 # escape soon if there isn't any approval required by this user151 if not page.publisher_public or page.get_absolute_url() != page.publisher_public.get_absolute_url():...
test_page_retrieval.py
Source:test_page_retrieval.py
...12 'widgets.widget/widget.html': '',13 'testwidgets.testwidget/widget-a/widget.html' : '',14 'testwidgets.testwidget/widget.html' : '',15 }16 create_filled_default_page(self)17 self.user = User.objects.create()18 self.anonymous_user = AnonymousUser()19 self.default_page = Page.objects.get_for_id(settings.DEFAULT_PAGE_ID)20 def get_session(self, key=u'123', session_dict=None):21 session = SessionWrapper(session_dict or {})22 session.session_key = key23 return session24 def test_default_page_retrieved_for_anonymous_user(self):25 page = get_page(user=self.anonymous_user, session=self.get_session())26 self.assert_equals(self.default_page, page)27 def test_default_page_retrieved_for_authenticated_user(self):28 page = get_page(user=self.user, session=self.get_session())29 self.assert_equals(self.default_page, page)30 def test_new_page_for_anonymous_created_when_forced(self):31 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)32 self.assert_not_equals(self.default_page, page)33 def test_new_page_for_authenticated_created_when_forced(self):34 page = get_page(user=self.user, session=self.get_session(), for_update=True)35 self.assert_not_equals(self.default_page, page)36 def test_anonymous_session_page_cloned_with_default_layout(self):37 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)38 self.assert_equals(self.default_page.layout, page.layout)39 def test_user_page_cloned_with_default_layout(self):40 page = get_page(user=self.user, session=self.get_session(), for_update=True)41 self.assert_equals(self.default_page.layout, page.layout)42 def test_page_with_same_config_for_anonymous_retrieved_on_next_visit(self):43 page = get_page(user=self.user, session=self.get_session(), for_update=True)44 page.add_widget(self.widget_u)45 page.save()46 page_again = get_page(user=self.user, session=self.get_session(), for_update=True)47 self.assert_equals(page.layout, page_again.layout)48 def test_anonymous_modifications_preserved_when_logging_in_with_same_session(self):49 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)50 page.add_widget(self.widget_u)51 page.save()52 page_again = get_page(user=self.user, session=self.get_session())53 self.assert_equals(page.layout, page_again.layout)54 self.assert_not_equals(self.default_page.layout, page_again.layout)55 def test_anonymous_page_destroyed_after_converting_to_user_page(self):56 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)57 page.add_widget(self.widget_u)58 page.save()59 # converting to user page60 get_page(user=self.user, session=self.get_session())61 # default page now retrieved62 page = get_page(user=self.anonymous_user, session=self.get_session())63 self.assert_equals(self.default_page, page)64 def test_user_page_takes_preference_over_modified_anonymous_page(self):65 # convert session page to user66 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)67 get_page(user=self.user, session=self.get_session())68 # create modified anonymous page69 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)70 page.add_widget(self.widget_u)71 page.save()72 # unmodified user page should be shown after next login73 page = get_page(user=self.user, session=self.get_session())74 self.assert_equals(self.default_page.layout, page.layout)75 def test_anonymous_page_deleted_even_after_second_conversion(self):76 # this behaviour could change. See #348377 # convert session page to user78 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)79 get_page(user=self.user, session=self.get_session())80 # create modified anonymous page81 session_page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)82 session_page.add_widget(self.widget_u)83 session_page.save()84 # log in again85 get_page(user=self.user, session=self.get_session())86 self.assert_equals(self.default_page.layout, page.layout)87 # our second modification of anonymous page preserved88 page = get_page(user=self.anonymous_user, session=self.get_session(), for_update=True)89 self.assert_equals(session_page.layout, page.layout)90 def tearDown(self):91 super(TestGetPage, self).tearDown()...
__init__.py
Source:__init__.py
...4from mypage.pages.layout import Layout5from mypage.widgets.models import get_object6from django.db.models import ObjectDoesNotExist7from mypage.pages.migrations.utils.layout_refactor_migration import migrate_page 8def get_page(user, session, for_update=False, defaults=None, from_page=None):9 """10 Get page for the current user. Check if they have a UserPage11 and if so, return it, return the default page otherwise.12 If for_update is specified, only return the defaul page for users13 that can edit Page (has_perm('change_page')) so that regular users won't override14 """15 from_page = from_page or settings.DEFAULT_PAGE_ID16 page = None17 session_page = None18 if for_update:19 session.modified = True20 defaults = defaults or session.get('defaults', {})21 try:22 session_page = SessionPage.objects.get(session_key=session.session_key)23 except SessionPage.DoesNotExist, e:24 pass25 if user.is_authenticated():26 # Authenticated users27 try:28 page = UserPage.objects.get(user=user)29 except UserPage.DoesNotExist, e:30 if session_page:31 # user has a session_page, clone it and save it32 page = UserPage.objects.clone_from_page(33 page=session_page,34 defaults=defaults,35 user=user,36 )37 # delete the now obsolete session_page38 session_page.delete()39 session_page = None40 elif for_update:41 # create user page from default42 page = UserPage.objects.clone_from_page(43 page=Page.objects.get_for_id(from_page),44 defaults=defaults,45 user=user46 )47 else:48 # anonymous user49 if session_page:50 # user already as a session page51 page = session_page52 elif for_update:53 # Unknown user without UserPage or SessionPage wanting to edit page must clone SessionPage54 page = SessionPage.objects.clone_from_page(55 page=Page.objects.get_for_id(from_page),56 defaults=defaults,57 session_key=session.session_key58 )59 if not page:60 # read only page61 page = Page.objects.get_for_id(from_page)62 if defaults:63 for k, v in defaults.items():64 setattr(page, k, v)65 if not page.layout_migrated:66 page = migrate_page(page)67 return page68def get_widget_or_404(page, content_type_id, object_id):69 """70 Return a widget using the ct_id and obj_id pair71 """72 try:73 widget = get_object(content_type_id, object_id)74 except ObjectDoesNotExist, e:75 raise http.Http40476 try:77 wil = page.layout.get_widget(int(content_type_id), int(object_id))78 except Layout.WidgetInLayoutDoesNotExist, e:79 raise http.Http40480 return widget, wil81def is_custom_page(page):82 """83 Custom pages could be updated/deleted by users84 """...
views.py
Source:views.py
1#from pages.models import Page2from apps.carosel.models import Carosel3from django.shortcuts import render_to_response4from django.template import RequestContext5#from news.models import Article6#from blog.models import Post7#from mediaviewer.models import *8def Home(request, slug):9# page_items = Page.objects.get(slug='home')10# page_contents = page_items.pagecontent_set.all().order_by('position')11 carosel_list = Carosel.objects.all()[:3]12 13# farticle_list = Article.objects.filter(featured=True).order_by('-created')14# farticle = farticle_list[0]15 16# fimage_list = Image.objects.filter(featured=True).order_by('-created')17 # fimage = fimage_list[0]18# posts = Post.objects.all().order_by('-created')[:8]19# return render_to_response('layouts/home.html', {'page':page_items, 'page_contents':page_contents, 'carosel_list': carosel_list, 'farticle':farticle, 'posts':posts, 'fimage':fimage},context_instance = RequestContext(request))20 return render_to_response('index.html', {'carosel_list': carosel_list})21'''22def About(request):23 page_items = Page.objects.get(slug='about')24 page_contents = page_items.pagecontent_set.all().order_by('position')25 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})26def Work(request):27 page_items = Page.objects.get(slug='work')28 page_contents = page_items.pagecontent_set.all().order_by('position')29 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})30def Media(request):31 page_items = Page.objects.get(slug='media')32 page_contents = page_items.pagecontent_set.all().order_by('position')33 return render_to_response('about.html',{'page':page_items, 'page_contents':page_contents})34def Archives(request):35 page_items = Page.objects.get(slug='archives')36 page_contents = page_items.pagecontent_set.all().order_by('position')37 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})38def Contact(request):39 page_items = Page.objects.get(slug='contact')40 page_contents = page_items.pagecontent_set.all().order_by('position')41 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})42def GetInvolved(request):43 page_items = Page.objects.get(slug='get-involved')44 page_contents = page_items.pagecontent_set.all().order_by('position')45 return render_to_response('about.html', {'page':page_items, 'page_contents':page_contents})...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18const browser = chromium.launch();19module.exports = browser;20const browser = require('./browser');21(async () => {22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.screenshot({ path: 'google.png' });25 await browser.close();26})();27const browser = require('./browser');28(async () => {29 const context = await browser.newContext();30 const page = await context.newPage();31 await page.screenshot({ path: 'google.png' });32 await browser.close();33})();34const browser = require('./browser');35(async () => {36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: '
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of ['chromium', 'firefox', 'webkit']) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const title = await page.evaluate(() => document.title);8 console.log(title);9 await browser.close();10 }11})();12const playwright = require('playwright');13(async () => {14 for (const browserType of ['chromium', 'firefox', 'webkit']) {15 const browser = await playwright[browserType].launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 const title = await page.evaluate(() => document.title);19 console.log(title);20 await browser.close();21 }22})();23const playwright = require('playwright');24(async () => {25 for (const browserType of ['chromium', 'firefox', 'webkit']) {26 const browser = await playwright[browserType].launch();27 const context = await browser.newContext();28 const page = await context.newPage();29 const title = await page.evaluate(() => document.title);30 console.log(title);31 await browser.close();32 }33})();34const playwright = require('playwright');35(async () => {36 for (const browserType of ['chromium', 'firefox', 'webkit']) {37 const browser = await playwright[browserType].launch();38 const context = await browser.newContext();39 const page = await context.newPage();40 const title = await page.evaluate(() => document.title);41 console.log(title);42 await browser.close();43 }44})();45const playwright = require('playwright');46(async () => {47 for (const browserType of ['chromium', 'firefox', 'webkit']) {48 const browser = await playwright[browserType].launch();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('text=Get started');7 await page.waitForTimeout(1000);8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();
Using AI Code Generation
1 const { page } = context;2 await page.waitForSelector('input[name="q"]');3 await page.fill('input[name="q"]', 'playwright');4 await page.keyboard.press('Enter');5 await page.waitForSelector('text="Playwright"');6 await page.click('text="Playwright"');7 await page.waitForSelector('text="Getting started"');8 await page.click('text="Getting started"');9 await page.waitForSelector('text="Installation"');10 await page.click('text="Installation"');11 await page.waitForSelector('text="Node.js"');12 await page.click('text="Node.js"');13 await page.waitForSelector('text="npm"');14 await page.click('text="npm"');15 await page.waitForSelector('text="Installing Playwright"');16 await page.click('text="Installing Playwright"');17 await page.waitForSelector('text="Install the dependencies"');18 await page.click('text="Install the dependencies"');19 await page.waitForSelector('text="npm install"');20 await page.click('text="npm install"');21 await page.waitForSelector('text="Run the tests"');22 await page.click('text="Run the tests"');23 await page.waitForSelector('text="npx playwright test"');24 await page.click('text="npx playwright test"');25 await page.waitForSelector('text="Run the tests in all browsers"');26 await page.click('text="Run the tests in all browsers"');27 await page.waitForSelector('text="npx playwright test --all"');28 await page.click('text="npx playwright test --all"');29 await page.waitForSelector('text="Run the tests in a specific browser"');30 await page.click('text="Run the tests in a specific browser"');31 await page.waitForSelector('text="npx playwright test --browser=chromium"');32 await page.click('text="npx playwright test --browser=chromium"');33 await page.waitForSelector('text="Run the tests in headful mode"');34 await page.click('text="Run the tests in headful mode"');35 await page.waitForSelector('text="npx playwright test --headed"');36 await page.click('text="npx playwright test --headed"');37 await page.waitForSelector('text="Run the tests in a
Using AI Code Generation
1const page = await context.newPage();2await page.screenshot({ path: `example.png` });3await page.close();4const page = await context.newPage();5await page.screenshot({ path: `example.png` });6await page.close();
Using AI Code Generation
1const page = require('@playwright/test').page;2const request = require('@playwright/test').request;3const response = require('@playwright/test').response;4const browser = require('@playwright/test').browser;5const context = require('@playwright/test').context;6const expect = require('@playwright/test').expect;7test('test', async ({ page }) => {8 const browser = page.context().browser();9 const context = page.context();10 const page = page;11 const expect = expect;12});
Using AI Code Generation
1const page = await browser.newPage();2const result = await page.evaluate(() => {3 return document.title;4});5console.log(result);6await browser.close();7const page = await browser.newPage();8const result = await page.evaluate(() => {9 return document.title;10});11console.log(result);12await browser.close();13 at ExecutionContext._evaluateInternal (/home/runner/work/playwright-test/playwright-test/node_modules/playwright/lib/cjs/pw-runner/executionContext.js:218:19)14 at processTicksAndRejections (internal/process/task_queues.js:93:5)15 at async ExecutionContext.evaluate (/home/runner/work/playwright-test/playwright-test/node_modules/playwright/lib/cjs/pw-runner/executionContext.js:107:16)
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!