def start_drawing(self, args): #loads one moduleName = args["module"] funcName = args["constructor"] showBoundary = int(args.get("showBoundary", "0")) hAlign = args.get("hAlign", "CENTER") # the path for the imports should include: # 1. document directory # 2. python path if baseDir not given, or # 3. baseDir if given try: dirName = sdict["baseDir"] except: dirName = None importPath = [os.getcwd()] if dirName is None: importPath.extend(sys.path) else: importPath.insert(0, dirName) modul = recursiveImport(moduleName, baseDir=importPath) func = getattr(modul, funcName) drawing = func() drawing.hAlign = hAlign if showBoundary: drawing._showBoundary = 1 self._curDrawing = pythonpoint.PPDrawing() self._curDrawing.drawing = drawing
def testRecursiveImportErrors(self): "check we get useful error messages" try: m1 = recursiveImport("reportlab.pdfgen.brush") self.fail("Imported a nonexistent module") except ImportError, e: self.assertEquals(e.message, "Could not import 'reportlab.pdfgen.brush'")
def test2(self): "try under a well known directory NOT on the path" from reportlab.lib.testutils import testsFolder D = os.path.join(testsFolder,'..','tools','pythonpoint') fn = os.path.join(D,'stdparser.py') if rl_isfile(fn) or rl_isfile(fn+'c') or rl_isfile(fn+'o'): m1 = recursiveImport('stdparser', baseDir=D)
def test2(self): "try under a well known directory NOT on the path" from reportlab.lib.testutils import testsFolder D = os.path.join(testsFolder, "..", "tools", "pythonpoint") fn = os.path.join(D, "stdparser.py") if rl_isfile(fn) or rl_isfile(fn + "c") or rl_isfile(fn + "o"): m1 = recursiveImport("stdparser", baseDir=D)
def test3(self): "ensure CWD is on the path" try: cwd = os.getcwd() os.chdir(self._tempdir) m1 = recursiveImport(self._testmodulename) finally: os.chdir(cwd)
def __init__(self, modulename, classname, caption, baseDir=None, background=None): module = recursiveImport(modulename, baseDir) klass = getattr(module, classname) self.drawing = klass() FlexFigure.__init__(self, self.drawing.width, self.drawing.height, caption, background) self.growToFit = 1
def testRecursiveImportErrors(self): "check we get useful error messages" try: m1 = recursiveImport('reportlab.pdfgen.brush') self.fail("Imported a nonexistent module") except ImportError as e: self.assertIn('reportlab.pdfgen.brush',str(e)) try: m1 = recursiveImport('totally.non.existent') self.fail("Imported a nonexistent module") except ImportError as e: self.assertIn('totally',str(e)) try: #import a module in the 'tests' directory with a bug m1 = recursiveImport('unimportable') self.fail("Imported a buggy module") except Exception as e: self.assertIn(reportlab.isPy3 and 'division by zero' or 'integer division or modulo by zero',str(e))
def testRecursiveImportErrors(self): "check we get useful error messages" try: m1 = recursiveImport('reportlab.pdfgen.brush') self.fail("Imported a nonexistent module") except ImportError as e: self.assertIn('reportlab.pdfgen.brush',str(e)) try: m1 = recursiveImport('totally.non.existent') self.fail("Imported a nonexistent module") except ImportError as e: self.assertIn('totally',str(e)) try: #import a module in the 'tests' directory with a bug m1 = recursiveImport('unimportable') self.fail("Imported a buggy module") except Exception as e: self.assertIn(("integer division by zeroException raised while importing 'unimportable': integer division by zero" if isPyPy else 'division by zero') ,str(e))
def preProcess(tree, nameSpace, caller=None): """Expands the parsed tree in the namespace and return new one. Returns a single tag-tuple in most cases, but a list of them if processing a loop node. """ from reportPackages.rlextra.radxml import xmlutils #expand this into a class with methods for each tag it handles. #then I can put logic tags in one and data access in another. tagName, attrs, children, extraStuff = tree #any attribute as $name becomes th value of name #tags might be nested in a loop, and if so then #each dictionary must be a fresh copy rather than # a pointer to the same dict newAttrs = attrs.copy() if attrs is not None else {} for key, value in list(newAttrs.items()): if isinstance(value,str) and value[0:1] == '$': newValue = eval(value[1:], nameSpace) newAttrs[key] = newValue attrs = newAttrs if tagName in TAG_LOOP: innerTxt = attrs[TAG_LOOP_INNER] outer = eval(attrs[TAG_LOOP_OUTER], nameSpace) dataSet = [] for row in outer: nameSpace['__loop_inner__'] = row rl_exec((innerTxt + " = __loop_inner__\n"), nameSpace) #at this point we're making lots of child nodes. # the attribute dictionary of each shold be a copy, not # a reference newChildren = processChildren(children, nameSpace) if newChildren is not None: dataSet.extend(newChildren) return dataSet elif tagName in TAG_ASSIGN: name = attrs[TAG_ASSIGN_NAME] valueStr = attrs[TAG_ASSIGN_VALUE] try: value = eval(valueStr, nameSpace) except SyntaxError: #must be a string value = valueStr nameSpace[name] = value return None elif tagName in TAG_SCRIPT: code = children[0] if not code.endswith('\n'): code += '\n' try: rl_exec(code, nameSpace) except SyntaxError: raise SyntaxError("Error with following script in xpreppy:\n\n%s" % code) return None elif tagName in TAG_EXPR: exprText = children[0] assert isinstance(exprText,strTypes), "expr can only contain strings" #attributes may affect escaping escape = attrs.get(u'escape', None) encoding = attrs.get(u'encoding',u'utf8') exprValue = eval(exprText, nameSpace) if isBytes(exprValue): exprValue = exprValue.decode(encoding) elif isUnicode(exprValue): pass else: exprValue = asUnicodeEx(exprValue) if escape in (u'CDATA',u'CDATAESCAPE'): exprValue = u'<![CDATA[%s]]>' % exprValue if escape==u'CDATA': return [exprValue] elif escape == u'off': return [asUnicodeEx(exprValue)] elif escape == u'unescape': return [xmlutils.unescape(exprValue, ENTITY_SUBSTITUTIONS_DRAWSTRING_DICT)] return [xmlEscape(exprValue)] elif tagName in TAG_IF: condText = attrs[u'cond'] yesOrNo = eval(condText, nameSpace) if yesOrNo: return processChildren(children, nameSpace) elif tagName in TAG_SWITCH: #two modes, with and without top level variable exprText = attrs.get(u'expr',u'') if exprText: expr = eval(exprText, nameSpace) selected = None for child in children: if isinstance(child,tuple): (childTagName, childAttrs, grandChildren, stuff) = child if childTagName in TAG_CASE: condition = childAttrs[u'condition'] if exprText: #check if it equals the value try: value = eval(condition, nameSpace) except NameError: value = condition # assume a string if (expr == value): selected = processChildren(grandChildren, nameSpace) break else: #they gave us a full condition, evaluate it yes = eval(condition, nameSpace) if yes: selected = processChildren(grandChildren, nameSpace) break elif childTagName in TAG_DEFAULT: selected = processChildren(grandChildren, nameSpace) break else: raise ValueError('%s tag may only contain these tags: ' % (TAG_SWITCH, ', '.join(TAG_CASE+TAG_DEFAULT))) return selected elif tagName in TAG_ACQUIRE: #all children will be data fetchers xacquire.acquireData(children, nameSpace) return None elif tagName in TAG_DOCLET: #pull out args needed to initialize dirName = attrs.get(u"baseDir", None) moduleName = attrs[u"module"] className = attrs[u"class"] dataStr = attrs.get(u"data", None) #load module, import and create it if caller == 'rml': from reportPackages.rlextra.rml2pdf.rml2pdf import _rml2pdf_locations locations = _rml2pdf_locations(dirName) else: locations = dirName m = recursiveImport(moduleName, locations) klass = getattr(m, className) docletObj = klass() #give it the data model if dataStr: dataObj = eval(dataStr, nameSpace) else: dataObj = nameSpace docletObj.setData(dataObj) #hide it in the tree so RML can see the object attrs[u'__doclet__'] = docletObj #return the tag otherwise unmodified return (tagName, attrs, children, extraStuff) else: newChildren = processChildren(children, nameSpace) return (tagName, attrs, newChildren, extraStuff)
def test2(self): "try under a well known directory NOT on the path" D = os.path.join(os.path.dirname(reportlab.__file__), 'tools','pythonpoint') fn = os.path.join(D,'stdparser.py') if rl_isfile(fn) or rl_isfile(fn+'c') or rl_isfile(fn+'o'): m1 = recursiveImport('stdparser', baseDir=D)
def test2(self): "try under a well known directory NOT on the path" D = os.path.join(os.path.dirname(reportlab.__file__), "tools", "pythonpoint") fn = os.path.join(D, "stdparser.py") if rl_isfile(fn) or rl_isfile(fn + "c") or rl_isfile(fn + "o"): m1 = recursiveImport("stdparser", baseDir=D)
def test1(self): "try stuff known to be in the path" m1 = recursiveImport('reportlab.pdfgen.canvas') import reportlab.pdfgen.canvas assert m1 == reportlab.pdfgen.canvas
"check we get useful error messages" try: m1 = recursiveImport('reportlab.pdfgen.brush') self.fail("Imported a nonexistent module") except ImportError, e: self.assertEquals(e.message, "Could not import 'reportlab.pdfgen.brush'") try: m1 = recursiveImport('totally.non.existent') self.fail("Imported a nonexistent module") except ImportError, e: self.assertEquals(e.message, "Could not import 'totally.non.existent'") try: #import a module in the 'tests' directory with a bug m1 = recursiveImport('unimportable') self.fail("Imported a buggy module") except ImportError, e: self.assert_('integer division or modulo by zero' in e.message) def makeSuite(): return makeSuiteForClasses(ImporterTestCase) if __name__ == "__main__": #noruntests unittest.TextTestRunner().run(makeSuite()) printLocation()
def testRecursiveImportErrors(self): "check we get useful error messages" try: m1 = recursiveImport("reportlab.pdfgen.brush") self.fail("Imported a nonexistent module") except ImportError, e: self.assertEquals(e.message, "Could not import 'reportlab.pdfgen.brush'") try: m1 = recursiveImport("totally.non.existent") self.fail("Imported a nonexistent module") except ImportError, e: self.assertEquals(e.message, "Could not import 'totally.non.existent'") try: # import a module in the 'tests' directory with a bug m1 = recursiveImport("unimportable") self.fail("Imported a buggy module") except ImportError, e: self.assert_("integer division or modulo by zero" in e.message) def makeSuite(): return makeSuiteForClasses(ImporterTestCase) if __name__ == "__main__": # noruntests unittest.TextTestRunner().run(makeSuite()) printLocation()
def preProcess(tree, nameSpace, caller=None): """Expands the parsed tree in the namespace and return new one. Returns a single tag-tuple in most cases, but a list of them if processing a loop node. """ from rlextra.radxml import xmlutils #expand this into a class with methods for each tag it handles. #then I can put logic tags in one and data access in another. tagName, attrs, children, extraStuff = tree #any attribute as $name becomes th value of name #tags might be nested in a loop, and if so then #each dictionary must be a fresh copy rather than # a pointer to the same dict newAttrs = attrs.copy() if attrs is not None else {} for key, value in list(newAttrs.items()): if isinstance(value,str) and value[0:1] == '$': newValue = eval(value[1:], nameSpace) newAttrs[key] = newValue attrs = newAttrs if tagName in TAG_LOOP: innerTxt = attrs[TAG_LOOP_INNER] outer = eval(attrs[TAG_LOOP_OUTER], nameSpace) dataSet = [] for row in outer: nameSpace['__loop_inner__'] = row rl_exec((innerTxt + " = __loop_inner__\n"), nameSpace) #at this point we're making lots of child nodes. # the attribute dictionary of each shold be a copy, not # a reference newChildren = processChildren(children, nameSpace) if newChildren is not None: dataSet.extend(newChildren) return dataSet elif tagName in TAG_ASSIGN: name = attrs[TAG_ASSIGN_NAME] valueStr = attrs[TAG_ASSIGN_VALUE] try: value = eval(valueStr) except SyntaxError: #must be a string value = valueStr nameSpace[name] = value return None elif tagName in TAG_SCRIPT: code = children[0] if not code.endswith('\n'): code += '\n' try: rl_exec(code, nameSpace) except SyntaxError: raise SyntaxError("Error with following script in xpreppy:\n\n%s" % code) return None elif tagName in TAG_EXPR: exprText = children[0] assert isinstance(exprText,strTypes), "expr can only contain strings" #attributes may affect escaping escape = attrs.get(u'escape', None) encoding = attrs.get(u'encoding',u'utf8') exprValue = eval(exprText, nameSpace) if isBytes(exprValue): exprValue = exprValue.decode(encoding) elif isUnicode(exprValue): pass else: exprValue = asUnicodeEx(exprValue) if escape in (u'CDATA',u'CDATAESCAPE'): exprValue = u'<![CDATA[%s]]>' % exprValue if escape==u'CDATA': return [exprValue] elif escape == u'off': return [asUnicodeEx(exprValue)] elif escape == u'unescape': return [xmlutils.unescape(exprValue, ENTITY_SUBSTITUTIONS_DRAWSTRING_DICT)] return [xmlEscape(exprValue)] elif tagName in TAG_IF: condText = attrs[u'cond'] yesOrNo = eval(condText, nameSpace) if yesOrNo: return processChildren(children, nameSpace) elif tagName in TAG_SWITCH: #two modes, with and without top level variable exprText = attrs.get(u'expr',u'') if exprText: expr = eval(exprText, nameSpace) selected = None for child in children: if isinstance(child,tuple): (childTagName, childAttrs, grandChildren, stuff) = child if childTagName in TAG_CASE: condition = childAttrs[u'condition'] if exprText: #check if it equals the value try: value = eval(condition, nameSpace) except NameError: value = condition # assume a string if (expr == value): selected = processChildren(grandChildren, nameSpace) break else: #they gave us a full condition, evaluate it yes = eval(condition, nameSpace) if yes: selected = processChildren(grandChildren, nameSpace) break elif childTagName in TAG_DEFAULT: selected = processChildren(grandChildren, nameSpace) break else: raise ValueError('%s tag may only contain these tags: ' % (TAG_SWITCH, ', '.join(TAG_CASE+TAG_DEFAULT))) return selected elif tagName in TAG_ACQUIRE: #all children will be data fetchers xacquire.acquireData(children, nameSpace) return None elif tagName in TAG_DOCLET: #pull out args needed to initialize dirName = attrs.get(u"baseDir", None) moduleName = attrs[u"module"] className = attrs[u"class"] dataStr = attrs.get(u"data", None) #load module, import and create it if caller == 'rml': from rlextra.rml2pdf.rml2pdf import _rml2pdf_locations locations = _rml2pdf_locations(dirName) else: locations = dirName m = recursiveImport(moduleName, locations) klass = getattr(m, className) docletObj = klass() #give it the data model if dataStr: dataObj = eval(dataStr, nameSpace) else: dataObj = nameSpace docletObj.setData(dataObj) #hide it in the tree so RML can see the object attrs[u'__doclet__'] = docletObj #return the tag otherwise unmodified return (tagName, attrs, children, extraStuff) else: newChildren = processChildren(children, nameSpace) return (tagName, attrs, newChildren, extraStuff)