def test_cb_head(self): # no entries yields no entry_title args = {"request": pyblosxom.Request({}, {}, {}), "entry": {}} newargs = entrytitle.cb_head(args) self.assertEquals(newargs["entry"].get("entry_title", ""), "") # one entry yields entry_title args = { "request": pyblosxom.Request({}, {}, {"entry_list": [{ "title": "foobar" }]}), "entry": {} } newargs = entrytitle.cb_head(args) self.assertEquals(newargs["entry"]["entry_title"], ":: foobar") # one entry with no title yields entry_title with "No title" args = { "request": pyblosxom.Request({}, {}, {"entry_list": [{}]}), "entry": {} } newargs = entrytitle.cb_head(args) self.assertEquals(newargs["entry"]["entry_title"], ":: No title") # one entry yields entry_title, using entry_title_template # configuration property args = { "request": pyblosxom.Request({"entry_title_template": "%(title)s ::"}, {}, {"entry_list": [{ "title": "foobar" }]}), "entry": {} } newargs = entrytitle.cb_head(args) self.assertEquals(newargs["entry"]["entry_title"], "foobar ::") # multiple entries yields no title args = { "request": pyblosxom.Request( {}, {}, {"entry_list": [{ "title": "foobar" }, { "title": "foobar2" }]}), "entry": {} } newargs = entrytitle.cb_head(args) self.assertEquals(newargs["entry"].get("entry_title", ""), "")
def test_verify_installation(self): config = dict(self.config_base) req = pyblosxom.Request(config, self.environ, {}) self.assert_(acronyms.verify_installation(req) == 0) config["acronym_file"] = os.path.join(self.datadir, "foo.txt") req = pyblosxom.Request(config, self.environ, {}) filename = acronyms.get_acronym_file(config) fp = open(filename, "w") fp.write("...") fp.close() self.assert_(acronyms.verify_installation(req) == 1)
def build_request(self, cfg=None, http=None, data=None, inputstream=""): """ process_path_info uses: - req.pyhttp["PATH_INFO"] - string - req.config["default_flavour"] - string - req.config["datadir"] - string - req.config["blog_title"] - string - req.config["base_url"] - string - req.data["extensions"] - dict of string -> func if using req.get_form(): - req.pyhttp["wsgi.input"] - StringIO instance - req.pyhttp["REQUEST_METHOD"] - GET or POST - req.pyhttp["CONTENT_LENGTH"] - integer """ _config = {"default_flavour": "html", "datadir": os.path.join(self.get_temp_dir(), "entries"), "blog_title": "Joe's blog", "base_url": "http://www.example.com/"} if cfg: _config.update(cfg) _data = {"extensions": {"txt": 0}} if data: _data.update(data) _http = {"wsgi.input": StringIO.StringIO(inputstream), "REQUEST_METHOD": len(inputstream) and "GET" or "POST", "CONTENT_LENGTH": len(inputstream)} if http: _http.update(http) return pyblosxom.Request(_config, _http, _data)
def category_to_tags(command, argv): """Goes through all entries and converts the category to tags metadata. It adds the tags line as the second line. It maintains the mtime for the file. """ import config datadir = config.py.get("datadir") if not datadir: raise ValueError("config.py has no datadir property.") sep = config.py.get("tags_separator", ",") tagsfile = get_tagsfile(config.py) from Pyblosxom import pyblosxom from Pyblosxom import tools from Pyblosxom.entries import fileentry data = {} # register entryparsers so that we parse all possible file types. data["extensions"] = tools.run_callback( "entryparser", {"txt": pyblosxom.blosxom_entry_parser}, mappingfunc=lambda x, y: y, defaultfunc=lambda x: x) req = pyblosxom.Request(config.py, {}, data) # grab all the entries in the datadir filelist = tools.walk(req, datadir) if not datadir.endswith(os.sep): datadir = datadir + os.sep for mem in filelist: print "working on %s..." % mem category = os.path.dirname(mem)[len(datadir):] tags = category.split(os.sep) print " adding tags %s" % tags tags = "#tags %s\n" % (sep.join(tags)) atime, mtime = os.stat(mem)[7:9] fp = open(mem, "r") data = fp.readlines() fp.close() data.insert(1, tags) fp = open(mem, "w") fp.write("".join(data)) fp.close() os.utime(mem, (atime, mtime)) return 0
def buildtags(command, argv): """Builds the tags index. """ import config datadir = config.py.get("datadir") if not datadir: raise ValueError("config.py has no datadir property.") sep = config.py.get("tags_separator", ",") tagsfile = get_tagsfile(config.py) from Pyblosxom import pyblosxom from Pyblosxom import tools from Pyblosxom.entries import fileentry data = {} # register entryparsers so that we parse all possible file types. data["extensions"] = tools.run_callback( "entryparser", {"txt": pyblosxom.blosxom_entry_parser}, mappingfunc=lambda x, y: y, defaultfunc=lambda x: x) req = pyblosxom.Request(config.py, {}, data) # grab all the entries in the datadir filelist = tools.walk(req, datadir) entrylist = [fileentry.FileEntry(req, e, datadir) for e in filelist] tags_to_files = {} for mem in entrylist: tagsline = mem["tags"] if not tagsline: continue tagsline = [t.strip() for t in tagsline.split(sep)] for t in tagsline: tags_to_files.setdefault(t, []).append(mem["filename"]) savefile(tagsfile, tags_to_files) return 0
def test_cb_story(self): req = pyblosxom.Request( self.config, self.environ, {"acronyms": acronyms.build_acronyms(["FOO = bar"])}) # basic test args = {"request": req, "entry": {"body": "<p>This is FOO!</p>"}} ret = acronyms.cb_story(args) self.assertEquals( args["entry"]["body"], "<p>This is <acronym title=\"bar\">FOO</acronym>!</p>") # test to make sure substitutions don't happen in tags args = {"request": req, "entry": {"body": "<FOO>This is FOO!</FOO>"}} ret = acronyms.cb_story(args) self.assertEquals( args["entry"]["body"], "<FOO>This is <acronym title=\"bar\">FOO</acronym>!</FOO>")
def render_url(cdict, pathinfo, querystring=""): """ Takes a url and a querystring and renders the page that corresponds with that by creating a Request and a PyBlosxom object and passing it through. @param cdict: the config.py dict @type cdict: dict @param pathinfo: the path_info string. ex: "/dev/pyblosxom/firstpost.html" @type pathinfo: string @param querystring: the querystring (if any). ex: "debug=yes" @type querystring: string """ staticdir = cdict.get("static_dir", "") # if there is no staticdir, then they're not set up for static # rendering. if not staticdir: raise Exception("You must set static_dir in your config file.") from Pyblosxom import pyblosxom oldstdout = sys.stdout req = pyblosxom.Request() req.addHttp({ "HTTP_USER_AGENT": "static renderer", "REQUEST_METHOD": "GET", "HTTP_HOST": "localhost", "PATH_INFO": pathinfo, "QUERY_STRING": querystring, "REQUEST_URI": pathinfo + "?" + querystring, "PATH_INFO": pathinfo, "HTTP_REFERER": "", "REMOTE_ADDR": "" }) req.addConfiguration(cdict) req.addData({"STATIC": 1}) buffer = StringIO.StringIO() sys.stdout = buffer p = pyblosxom.PyBlosxom(req) p.run() sys.stdout = oldstdout fn = os.path.normpath(staticdir + os.sep + pathinfo) if not os.path.isdir(os.path.dirname(fn)): os.makedirs(os.path.dirname(fn)) # this is cheesy--we need to remove the HTTP headers # from the file. output = buffer.getvalue().splitlines() while 1: if len(output[0].strip()) == 0: break output.pop(0) output.pop(0) f = open(fn, "w") f.write("\n".join(output)) f.close()
def setUp(self, plugin_module): """Subclasses should call this in their setUp() methods. The plugin_module arg is the plugin module being tested. This is used to set the plugin_dir config variable. """ # freeze time self.timestamp = TIMESTAMP self.frozen_time = self.freeze_pyblosxom_time(self.timestamp) self.timestamp_asc = time.ctime(self.timestamp) gmtime = time.gmtime(self.timestamp) self.timestamp_date = time.strftime('%a %d %b %Y', gmtime) self.timestamp_w3c = time.strftime('%Y-%m-%dT%H:%M:%SZ', gmtime) # set up config, including datadir and plugin_dirs self.datadir = tempfile.mkdtemp(prefix='pyblosxom_test_datadir') plugin_file = os.path.dirname(plugin_module.__file__) self.config_base = { 'datadir': self.datadir, 'plugin_dirs': [plugin_file], 'base_url': 'http://bl.og/', } self.config = self.config_base tools.initialize(self.config) # set up environment vars and http request self.environ = {'PATH_INFO': '/', 'REMOTE_ADDR': ''} self.form_data = '' self.request = pyblosxom.Request(self.config, self.environ, {}) self.http = self.request.get_http() # set up entries and data dict self.entry_name = 'test_entry' entry_properties = {'absolute_path': '.', 'fn': self.entry_name} self.entry = entries.base.generate_entry(self.request, entry_properties, {}, gmtime) self.entry_list = [self.entry] self.data = { 'entry_list': self.entry_list, 'bl_type': 'file', } self.request._data = self.data # set up renderer and templates self.renderer = Renderer(self.request) self.renderer.set_content(self.entry_list) templates = ('content_type', 'head', 'story', 'foot', 'date_head', 'date_foot') self.renderer.flavour = dict([(t, t) for t in templates]) # populate args dict self.args = { 'request': self.request, 'renderer': self.renderer, 'entry': self.entry, 'template': 'template starts:', } # this stores the callbacks that have been injected. it maps # callback names to the injected methods to call. any # callbacks that haven't been injected are passed through to # pyblosxom's callback chain. # # use inject_callback() to inject a callback. self.injected_callbacks = {} orig_run_callback = tools.run_callback def intercept_callback(name, args, **kwargs): if name in self.injected_callbacks: return self.injected_callbacks[name]() else: return orig_run_callback(name, args, **kwargs) tools.run_callback = intercept_callback
def test_function_with_arguments(self): for mem in (('$foo("arg1")', 'foo("arg1")'), ('$foo("arg1", 1)', 'foo("arg1", 1)'), ('$foo("español", 1)', 'foo("español", 1)')): self.eq_(self._get_match(tools._VAR_REGEXP, mem[0]), mem[1]) def test_parens(self): for mem in (("$(foo)", "(foo)"), ("$(foo())", "(foo())"), ("$(foo::bar)", "(foo::bar)"), ("$(foo::bar())", "(foo::bar())"), ("$(foo::bar(1, 2, 3))", "(foo::bar(1, 2, 3))")): self.eq_(self._get_match(tools._VAR_REGEXP, mem[0]), mem[1]) req = pyblosxom.Request({}, {}, {}) class Testparse(UnitTestBase): """tools.parse""" def setUp(self): UnitTestBase.setUp(self) def test_simple(self): env = {"foo": "FOO", "country": "España"} for mem in (("foo foo foo", "foo foo foo"), ("foo $foo foo", "foo FOO foo"), ("foo $foor foo", "foo foo"), ("foo $country foo", "foo España foo")): self.eq_(tools.parse(req, env, mem[0]), mem[1])
def req_(): return pyblosxom.Request({}, {}, {})