def add_old_cfd( page: pywikibot.Page, cfd_page: CfdPage, action: str, result: str, summary: str, ) -> None: """Add {{Old CfD}} to the talk page.""" date = cfd_page.title(with_section=False).rpartition('/')[2] if page.exists(): wikicode = mwparserfromhell.parse(page.text, skip_style_tags=True) for tpl in wikicode.ifilter_templates(): try: template = pywikibot.Page(page.site, str(tpl.name), ns=10) if template not in TPL['old cfd'] or not tpl.has( 'date', ignore_empty=True): continue except pywikibot.InvalidTitle: continue if tpl.get('date').value.strip() == date: # Template already present. return old_cfd = Template('Old CfD') old_cfd.add('action', action) old_cfd.add('date', date) old_cfd.add('section', cfd_page.section()) old_cfd.add('result', result) page.text = str(old_cfd) + '\n' + page.text page.save(summary=summary)
def test_params(self): """test getter for the params attribute""" node1 = Template(wraptext("foobar")) plist = [pgenh("1", "bar"), pgens("abc", "def")] node2 = Template(wraptext("foo"), plist) self.assertEqual([], node1.params) self.assertIs(plist, node2.params)
def test_integration2(self): """an even more audacious test for building a horrible wikicode mess""" # {{a|b|{{c|[[d]]{{{e}}}}}}}[[f|{{{g}}}<!--h-->]]{{i|j= }} test = [tokens.TemplateOpen(), tokens.Text(text="a"), tokens.TemplateParamSeparator(), tokens.Text(text="b"), tokens.TemplateParamSeparator(), tokens.TemplateOpen(), tokens.Text(text="c"), tokens.TemplateParamSeparator(), tokens.WikilinkOpen(), tokens.Text(text="d"), tokens.WikilinkClose(), tokens.ArgumentOpen(), tokens.Text(text="e"), tokens.ArgumentClose(), tokens.TemplateClose(), tokens.TemplateClose(), tokens.WikilinkOpen(), tokens.Text(text="f"), tokens.WikilinkSeparator(), tokens.ArgumentOpen(), tokens.Text(text="g"), tokens.ArgumentClose(), tokens.CommentStart(), tokens.Text(text="h"), tokens.CommentEnd(), tokens.WikilinkClose(), tokens.TemplateOpen(), tokens.Text(text="i"), tokens.TemplateParamSeparator(), tokens.Text(text="j"), tokens.TemplateParamEquals(), tokens.HTMLEntityStart(), tokens.Text(text="nbsp"), tokens.HTMLEntityEnd(), tokens.TemplateClose()] valid = wrap( [Template(wraptext("a"), params=[Parameter(wraptext("1"), wraptext( "b"), showkey=False), Parameter(wraptext("2"), wrap([Template( wraptext("c"), params=[Parameter(wraptext("1"), wrap([Wikilink( wraptext("d")), Argument(wraptext("e"))]), showkey=False)])]), showkey=False)]), Wikilink(wraptext("f"), wrap([Argument(wraptext( "g")), Comment("h")])), Template(wraptext("i"), params=[ Parameter(wraptext("j"), wrap([HTMLEntity("nbsp", named=True)]))])]) self.assertWikicodeEqual(valid, self.builder.build(test))
def time_from_template(template: Template): """ Pulls date-time information encoded by a template and returns a WikiTime object. If date-time information is missing or incomplete, None is returned instead. :param template: A mwparserfromhell Template object with date, time, and timezone parameters :return: a WikiTime object representing the date-time information encoded by this template """ tz_lookup = { 'PST': WikiTime.pst, 'CET': WikiTime.cet, 'KST': WikiTime.kst } if not template.has('date') or not template.has('time'): return None date = template.get("date").value.strip() time = template.get("time").value.strip() if date == '' or time == '': return None # Fix case of a time being written as 100 or 1100 without a : if match(r'\d\d\d\d', time): time = '{}:{}'.format(time[:2], time[3:]) elif match(r'\d\d\d', time): time = '{}:{}'.format(time[:1], time[2:]) tz_local_str = template.get('timezone').value.strip() tz_local = tz_lookup[tz_local_str] date_and_time = date + " " + time return time_from_str(date_and_time, tz=tz_local)
def test_unicode(self): """test Template.__unicode__()""" node = Template(wraptext("foobar")) self.assertEqual("{{foobar}}", str(node)) node2 = Template(wraptext("foo"), [pgenh("1", "bar"), pgens("abc", "def")]) self.assertEqual("{{foo|bar|abc=def}}", str(node2))
def test_strip(self): """test Template.__strip__()""" node1 = Template(wraptext("foobar")) node2 = Template(wraptext("foo"), [pgenh("1", "bar"), pgens("abc", "def")]) for a in (True, False): for b in (True, False): self.assertEqual(None, node1.__strip__(a, b)) self.assertEqual(None, node2.__strip__(a, b))
def try_get(template: Template, key: str, default="", warn=True, throw=False) -> str: if template.has(key): return str(template.get(key)) else: if throw: raise ValueError(f"Template {template} doesn't have value defined at index {key}!") if warn: warnings.warn(f"Template {template} doesn't have a word defined at index {key}! This is strange but apparently possible.") return default
def repl_conditional(self, arg: Template, code: Wikicode, index: Union[str, int]): if arg.has(index): param = arg.get(index) self.apply_wikitext(param.value) code.replace( arg, str(param.value).strip() if param.showkey else param.value) else: code.remove(arg)
def test_name(self): """test getter/setter for the name attribute""" name = wraptext("foobar") node1 = Template(name) node2 = Template(name, [pgenh("1", "bar")]) self.assertIs(name, node1.name) self.assertIs(name, node2.name) node1.name = "asdf" node2.name = "téstïng" self.assertWikicodeEqual(wraptext("asdf"), node1.name) self.assertWikicodeEqual(wraptext("téstïng"), node2.name)
class MenaCreator(object): """ Create the MatchSchedule data for an event. This will add results to anything already played. Things we will NOT do: * Any disambigs * Check any one-team ff (both teams ff'ing WILL be handled though) * Split the data page in case it's too big * Label any tabs for playoffs etc """ heading = '== Day {} ==\n' outro = '{{MatchSchedule/End}}' def __init__(self, site: EsportsClient, title: str, bestof=1): self.site = site self.event = self.site.target(title).strip() self.toornament = self.site.cargo_client.query_one_result( tables='Tournaments', where='OverviewPage="{}"'.format(self.event), fields='ScrapeLink') self.summary = "Edit made by web scraping!" self.parser = Parser(self.toornament) self.intro_template = Template(name="MatchSchedule/Start") self.intro_template.add('bestof', str(bestof)) self.sandbox_page = self.site.client.pages[ 'User:RheingoldRiver/Toornament_Sandbox'] def run(self): matches = self.parser.run() output_list = [] current_day_index = 1 previousDate = time_from_str('1900-01-01 00:00:00+00:00') for match in matches: if match.timestamp.cet_date != previousDate.cet_date: if current_day_index > 1: output_list.append(self.outro) output_list.append(self.get_intro(current_day_index)) previousDate.cet_date = match.timestamp.cet_date current_day_index += 1 output_list.append(match.print()) output_list.append(self.outro) self.site.save_title(self.sandbox_page, '\n'.join(output_list)) return 'https://lol.gamepedia.com/' + self.sandbox_page.name.replace( ' ', '_') def get_intro(self, current_day_index: int): self.intro_template.add('tab', 'Day {}'.format(current_day_index), before="bestof") return self.heading.format(str(current_day_index)) + str( self.intro_template)
def flag_template(self: TemplateParser, code: Wikicode, template: Template, flag, index=None): if index and template.has(index): param = template.get(index) self.apply_wikitext(param.value) code.replace(template, param) else: code.remove(template) self.state.flags.add(flag)
def redirect_cat(cat: pywikibot.Category, target: pywikibot.Category, summary: str) -> None: """ Redirect a category to another category. @param cat: Category to redirect @param target: Category redirect target @param summary: Edit summary """ tpl = Template('Category redirect') tpl.add('1', target.title(with_ns=False)) cat.text = str(tpl) cat.save(summary=summary)
def test_nodes(self): """test getter/setter for the nodes attribute""" code = parse("Have a {{template}}") self.assertEqual(["Have a ", "{{template}}"], code.nodes) L1 = SmartList([Text("foobar"), Template(wraptext("abc"))]) L2 = [Text("barfoo"), Template(wraptext("cba"))] L3 = "abc{{def}}" code.nodes = L1 self.assertIs(L1, code.nodes) code.nodes = L2 self.assertIs(L2, code.nodes) code.nodes = L3 self.assertEqual(["abc", "{{def}}"], code.nodes) self.assertRaises(ValueError, setattr, code, "nodes", object)
def __init__(self, site: EsportsClient, title: str, bestof=1): self.site = site self.event = self.site.target(title).strip() self.toornament = self.site.cargo_client.query_one_result( tables='Tournaments', where='OverviewPage="{}"'.format(self.event), fields='ScrapeLink') self.summary = "Edit made by web scraping!" self.parser = Parser(self.toornament) self.intro_template = Template(name="MatchSchedule/Start") self.intro_template.add('bestof', str(bestof)) self.sandbox_page = self.site.client.pages[ 'User:RheingoldRiver/Toornament_Sandbox']
def test_add(self): """test Tag.add()""" node = Tag(wraptext("ref"), wraptext("cite")) node.add("name", "value") node.add("name", "value", quotes=None) node.add("name", "value", quotes="'") node.add("name") node.add(1, False) node.add("style", "{{foobar}}") node.add("name", "value", '"', "\n", " ", " ") attr1 = ' name="value"' attr2 = " name=value" attr3 = " name='value'" attr4 = " name" attr5 = ' 1="False"' attr6 = ' style="{{foobar}}"' attr7 = '\nname = "value"' self.assertEqual(attr1, node.attributes[0]) self.assertEqual(attr2, node.attributes[1]) self.assertEqual(attr3, node.attributes[2]) self.assertEqual(attr4, node.attributes[3]) self.assertEqual(attr5, node.attributes[4]) self.assertEqual(attr6, node.attributes[5]) self.assertEqual(attr7, node.attributes[6]) self.assertEqual(attr7, node.get("name")) self.assertWikicodeEqual(wrap([Template(wraptext("foobar"))]), node.attributes[5].value) self.assertEqual( "".join(("<ref", attr1, attr2, attr3, attr4, attr5, attr6, attr7, ">cite</ref>")), node) self.assertRaises(ValueError, node.add, "name", "foo", quotes="bar") self.assertRaises(ValueError, node.add, "name", "a bc d", quotes=None)
def test_add(self): """test Tag.add()""" node = Tag(wraptext("ref"), wraptext("cite")) node.add("name", "value") node.add("name", "value", quoted=False) node.add("name") node.add(1, False) node.add("style", "{{foobar}}") node.add("name", "value", True, "\n", " ", " ") attr1 = ' name="value"' attr2 = " name=value" attr3 = " name" attr4 = ' 1="False"' attr5 = ' style="{{foobar}}"' attr6 = '\nname = "value"' self.assertEqual(attr1, node.attributes[0]) self.assertEqual(attr2, node.attributes[1]) self.assertEqual(attr3, node.attributes[2]) self.assertEqual(attr4, node.attributes[3]) self.assertEqual(attr5, node.attributes[4]) self.assertEqual(attr6, node.attributes[5]) self.assertEqual(attr6, node.get("name")) self.assertWikicodeEqual(wrap([Template(wraptext("foobar"))]), node.attributes[4].value) self.assertEqual( "".join(("<ref", attr1, attr2, attr3, attr4, attr5, attr6, ">cite</ref>")), node)
def create_wikitext(self, vals): wikitext = '' empty_pages = [] first_page = '' for ind, val in vals.items(): t_name, = val[1] if t_name != self.template_name: raise ValueError( f"Unexpected template name {t_name} instead of {self.template_name}" ) t_params = val[1][t_name] t_params2 = { k: t_params[k] for k in t_params if k not in self.ignore_params } if t_params: if not first_page: first_page = val[0] wikitext += f"* _INDEX_={ind}\n" wikitext += str( Template(t_name, params=[ Parameter(k, v) for k, v in t_params2.items() ])) wikitext += '\n' else: empty_pages.append( PageContent(title=val[0], timestamp=datetime.utcnow(), data={})) if wikitext: wikitext += f"* _INDEX_=END\n" return empty_pages, wikitext, first_page
def test_parse_anything_valid(self): """tests for valid input to utils.parse_anything()""" tests = [ (wraptext("foobar"), wraptext("foobar")), (Template(wraptext("spam")), wrap([Template(wraptext("spam"))])), ("fóóbar", wraptext("fóóbar")), (b"foob\xc3\xa1r", wraptext("foobár")), (123, wraptext("123")), (True, wraptext("True")), (None, wrap([])), ([Text("foo"), Text("bar"), Text("baz")], wraptext("foo", "bar", "baz")), ([wraptext("foo"), Text("bar"), "baz", 123, 456], wraptext("foo", "bar", "baz", "123", "456")), ([[[([[((("foo", ), ), )], "bar"], )]]], wraptext("foo", "bar")) ] for test, valid in tests: self.assertWikicodeEqual(valid, parse_anything(test))
def test_name(self): """test getter/setter for the name attribute""" name = wraptext("id") node = Attribute(name, wraptext("bar")) self.assertIs(name, node.name) node.name = "{{id}}" self.assertWikicodeEqual(wrap([Template(wraptext("id"))]), node.name)
def test_children(self): """test Template.__children__()""" node2p1 = Parameter(wraptext("1"), wraptext("bar"), showkey=False) node2p2 = Parameter(wraptext("abc"), wrap([Text("def"), Text("ghi")]), showkey=True) node1 = Template(wraptext("foobar")) node2 = Template(wraptext("foo"), [node2p1, node2p2]) gen1 = node1.__children__() gen2 = node2.__children__() self.assertEqual(node1.name, next(gen1)) self.assertEqual(node2.name, next(gen2)) self.assertEqual(node2.params[0].value, next(gen2)) self.assertEqual(node2.params[1].name, next(gen2)) self.assertEqual(node2.params[1].value, next(gen2)) self.assertRaises(StopIteration, next, gen1) self.assertRaises(StopIteration, next, gen2)
def test_integration(self): """a test for building a combination of templates together""" # {{{{{{{{foo}}bar|baz=biz}}buzz}}usr|{{bin}}}} test = [ tokens.TemplateOpen(), tokens.TemplateOpen(), tokens.TemplateOpen(), tokens.TemplateOpen(), tokens.Text(text="foo"), tokens.TemplateClose(), tokens.Text(text="bar"), tokens.TemplateParamSeparator(), tokens.Text(text="baz"), tokens.TemplateParamEquals(), tokens.Text(text="biz"), tokens.TemplateClose(), tokens.Text(text="buzz"), tokens.TemplateClose(), tokens.Text(text="usr"), tokens.TemplateParamSeparator(), tokens.TemplateOpen(), tokens.Text(text="bin"), tokens.TemplateClose(), tokens.TemplateClose() ] valid = wrap([ Template(wrap([ Template( wrap([ Template(wrap([Template(wraptext("foo")), Text("bar")]), params=[ Parameter(wraptext("baz"), wraptext("biz")) ]), Text("buzz") ])), Text("usr") ]), params=[ Parameter(wraptext("1"), wrap([Template(wraptext("bin"))]), showkey=False) ]) ]) self.assertWikicodeEqual(valid, self.builder.build(test))
def test_closing_tag(self): """test getter/setter for the closing_tag attribute""" tag = wraptext("ref") node = Tag(tag, wraptext("foobar")) self.assertIs(tag, node.closing_tag) node.closing_tag = "ref {{ignore me}}" parsed = wrap([Text("ref "), Template(wraptext("ignore me"))]) self.assertWikicodeEqual(parsed, node.closing_tag) self.assertEqual("<ref>foobar</ref {{ignore me}}>", node)
def test_contents(self): """test getter/setter for the contents attribute""" contents = wraptext("text") node = Tag(wraptext("ref"), contents) self.assertIs(contents, node.contents) node.contents = "text and a {{template}}" parsed = wrap([Text("text and a "), Template(wraptext("template"))]) self.assertWikicodeEqual(parsed, node.contents) self.assertEqual("<ref>text and a {{template}}</ref>", node)
def test_value(self): """test getter/setter for the value attribute""" value = wraptext("foo") node = Attribute(wraptext("id"), value) self.assertIs(value, node.value) node.value = "{{bar}}" self.assertWikicodeEqual(wrap([Template(wraptext("bar"))]), node.value) node.value = None self.assertIs(None, node.value)
def print(self): template = Template(name="MatchSchedule") self.add_field(template, 'date', self.timestamp.cet_date) self.add_field(template, 'time', self.timestamp.cet_time) self.add_field(template, 'timezone', 'CET') self.add_field(template, 'dst', self.timestamp.dst) self.add_field(template, 'stream', ' ') self.add_field(template, 'team1', self.team1) self.add_field(template, 'team2', self.team2) self.add_field(template, 'team1score', self.team1score) self.add_field(template, 'team2score', self.team2score) if self.is_forfeit: template.add('ff', self.forfeit) self.add_field(template, 'winner', self.winner) self.add_field(template, 'direct_link', self.url) self.add_field(template, 'page', self.page) self.add_field(template, 'n_in_page', self.index_in_page) return str(template)
def test_parsing(self): """integration test for parsing overall""" text = "this is text; {{this|is=a|template={{with|[[links]]|in}}it}}" expected = wrap([ Text("this is text; "), Template(wraptext("this"), [ Parameter(wraptext("is"), wraptext("a")), Parameter(wraptext("template"), wrap([ Template(wraptext("with"), [ Parameter(wraptext("1"), wrap([Wikilink(wraptext("links"))]), showkey=False), Parameter(wraptext("2"), wraptext("in"), showkey=False) ]), Text("it") ])) ]) ]) actual = parser.Parser().parse(text) self.assertWikicodeEqual(expected, actual)
def test_showtree(self): """test Template.__showtree__()""" output = [] getter, marker = object(), object() get = lambda code: output.append((getter, code)) mark = lambda: output.append(marker) node1 = Template(wraptext("foobar")) node2 = Template(wraptext("foo"), [pgenh("1", "bar"), pgens("abc", "def")]) node1.__showtree__(output.append, get, mark) node2.__showtree__(output.append, get, mark) valid = [ "{{", (getter, node1.name), "}}", "{{", (getter, node2.name), " | ", marker, (getter, node2.params[0].name), " = ", marker, (getter, node2.params[0].value), " | ", marker, (getter, node2.params[1].name), " = ", marker, (getter, node2.params[1].value), "}}", ] self.assertEqual(valid, output)
def update_template(self, template: Template): # i just added more and more checks to avoid crashing on LPL games over time if any( [_ in self.current_page.name for _ in ['LPL', 'LDL', 'Demacia']]): return for param in template.params: if '|primary=' in str(param.value): return if not template.has('statslink'): return mh = template.get('statslink').value.strip() if 'lpl.qq' in mh: return if 'wanplus' in mh: return if not mh: return # sigh ok hopefully we actually have a valid mh now print(f'Parsing mh {mh} on page {self.current_page.name}') try: result = get_riot_game(mh, add_names=True) except HTTPError: sleep(10) result = get_riot_game(mh, add_names=True) for param in template.params: param: Parameter if param.name.startswith('blue') or param.name.startswith('red'): # hax, sorry team = 'BLUE' if param.name.startswith('blue') else 'RED' player = int(param.name[-1]) - 1 w = param.value for tl in w.filter_templates(): tl: Template if not tl.name.matches('Scoreboard/Player'): continue primary = result['teams'][team]['players'][player][ 'primaryRuneTreeName'] tl.add('primary', primary, before='secondary')
def test_strip(self): """test Template.__strip__()""" node1 = Template(wraptext("foobar")) node2 = Template(wraptext("foo"), [ pgenh("1", "bar"), pgens("foo", ""), pgens("abc", "def")]) node3 = Template(wraptext("foo"), [ pgenh("1", "foo"), Parameter(wraptext("2"), wrap([Template(wraptext("hello"))]), showkey=False), pgenh("3", "bar")]) self.assertEqual(None, node1.__strip__(keep_template_params=False)) self.assertEqual(None, node2.__strip__(keep_template_params=False)) self.assertEqual("", node1.__strip__(keep_template_params=True)) self.assertEqual("bar def", node2.__strip__(keep_template_params=True)) self.assertEqual("foo bar", node3.__strip__(keep_template_params=True))
def test_iternodes(self): """test Template.__iternodes__()""" node1n1 = Text("foobar") node2n1, node2n2, node2n3 = Text("foo"), Text("bar"), Text("abc") node2n4, node2n5 = Text("def"), Text("ghi") node2p1 = Parameter(wraptext("1"), wrap([node2n2]), showkey=False) node2p2 = Parameter(wrap([node2n3]), wrap([node2n4, node2n5]), showkey=True) node1 = Template(wrap([node1n1])) node2 = Template(wrap([node2n1]), [node2p1, node2p2]) gen1 = node1.__iternodes__(getnodes) gen2 = node2.__iternodes__(getnodes) self.assertEqual((None, node1), next(gen1)) self.assertEqual((None, node2), next(gen2)) self.assertEqual((node1.name, node1n1), next(gen1)) self.assertEqual((node2.name, node2n1), next(gen2)) self.assertEqual((node2.params[0].value, node2n2), next(gen2)) self.assertEqual((node2.params[1].name, node2n3), next(gen2)) self.assertEqual((node2.params[1].value, node2n4), next(gen2)) self.assertEqual((node2.params[1].value, node2n5), next(gen2)) self.assertRaises(StopIteration, next, gen1) self.assertRaises(StopIteration, next, gen2)
def handle_template(tpl, code, namespace=None): if tpl.has('sprache'): if tpl.get('sprache').value.strip().lower() in ('englisch', 'english'): set_param_value(tpl, 'sprache', 'en') if tpl.get('sprache').value.strip().lower() in ('deutsch', 'german'): set_param_value(tpl, 'sprache', 'de') if tpl.has('wann'): if tpl.get('wann').value.strip() in ('Sommersemester', 'ss'): set_param_value(tpl, 'wann', 'SS') elif tpl.get('wann').value.strip() in ('Wintersemester', 'ws'): set_param_value(tpl, 'wann', 'WS') elif tpl.get('wann').value.strip() in ('Winter- und Sommersemester', 'Sommer- und Wintersemester'): set_param_value(tpl, 'wann', 'beide') if tpl.has('tiss'): if tpl.get('tiss').value.strip() == '1234567890': tpl.remove('tiss') archived = False successor = None if tpl.has('veraltet'): archived = True tpl.remove('veraltet') if tpl.has('nachfolger'): archived = True successor = tpl.get('nachfolger').value.strip() tpl.remove('nachfolger') for t in code.ifilter_templates( matches=lambda t: t.name.matches('Veraltet')): archived = True code.remove(t) archivedFlag = code.filter_templates( matches=lambda t: t.name.matches('Archiv')) if archived and not archivedFlag: tpl = Template(Wikicode([Text('Archiv')])) if successor: tpl.add('nachfolger', successor) code.insert(0, tpl) code.insert(1, '\n\n') if tpl.has('zuordnungen'): rels = tpl.get('zuordnungen').value.filter_templates() for rel in rels: if rel.has('2'): rel.get('2').value = str(rel.get('2').value).replace('–', '-') rels.sort(key=lambda x: x.get('1')) tpl.get('zuordnungen').value = '\n' + '\n'.join( [' ' * 4 + str(r) for r in rels]) + '\n' return 'fixe LVA-Daten'
def test_showtree(self): """test Template.__showtree__()""" output = [] getter, marker = object(), object() get = lambda code: output.append((getter, code)) mark = lambda: output.append(marker) node1 = Template(wraptext("foobar")) node2 = Template(wraptext("foo"), [pgenh("1", "bar"), pgens("abc", "def")]) node1.__showtree__(output.append, get, mark) node2.__showtree__(output.append, get, mark) valid = [ "{{", (getter, node1.name), "}}", "{{", (getter, node2.name), " | ", marker, (getter, node2.params[0].name), " = ", marker, (getter, node2.params[0].value), " | ", marker, (getter, node2.params[1].name), " = ", marker, (getter, node2.params[1].value), "}}"] self.assertEqual(valid, output)
def test_template(self): """tests for building Template nodes""" tests = [ ([tokens.TemplateOpen(), tokens.Text(text="foobar"), tokens.TemplateClose()], wrap([Template(wraptext("foobar"))])), ([tokens.TemplateOpen(), tokens.Text(text="spam"), tokens.Text(text="eggs"), tokens.TemplateClose()], wrap([Template(wraptext("spam", "eggs"))])), ([tokens.TemplateOpen(), tokens.Text(text="foo"), tokens.TemplateParamSeparator(), tokens.Text(text="bar"), tokens.TemplateClose()], wrap([Template(wraptext("foo"), params=[ Parameter(wraptext("1"), wraptext("bar"), showkey=False)])])), ([tokens.TemplateOpen(), tokens.Text(text="foo"), tokens.TemplateParamSeparator(), tokens.Text(text="bar"), tokens.TemplateParamEquals(), tokens.Text(text="baz"), tokens.TemplateClose()], wrap([Template(wraptext("foo"), params=[ Parameter(wraptext("bar"), wraptext("baz"))])])), ([tokens.TemplateOpen(), tokens.TemplateParamSeparator(), tokens.TemplateParamSeparator(), tokens.TemplateParamEquals(), tokens.TemplateParamSeparator(), tokens.TemplateClose()], wrap([Template(wrap([]), params=[ Parameter(wraptext("1"), wrap([]), showkey=False), Parameter(wrap([]), wrap([]), showkey=True), Parameter(wraptext("2"), wrap([]), showkey=False)])])), ([tokens.TemplateOpen(), tokens.Text(text="foo"), tokens.TemplateParamSeparator(), tokens.Text(text="bar"), tokens.TemplateParamEquals(), tokens.Text(text="baz"), tokens.TemplateParamSeparator(), tokens.Text(text="biz"), tokens.TemplateParamSeparator(), tokens.Text(text="buzz"), tokens.TemplateParamSeparator(), tokens.Text(text="3"), tokens.TemplateParamEquals(), tokens.Text(text="buff"), tokens.TemplateParamSeparator(), tokens.Text(text="baff"), tokens.TemplateClose()], wrap([Template(wraptext("foo"), params=[ Parameter(wraptext("bar"), wraptext("baz")), Parameter(wraptext("1"), wraptext("biz"), showkey=False), Parameter(wraptext("2"), wraptext("buzz"), showkey=False), Parameter(wraptext("3"), wraptext("buff")), Parameter(wraptext("3"), wraptext("baff"), showkey=False)])])), ] for test, valid in tests: self.assertWikicodeEqual(valid, self.builder.build(test))
def test_get(self): """test Template.get()""" node1 = Template(wraptext("foobar")) node2p1 = pgenh("1", "bar") node2p2 = pgens("abc", "def") node2 = Template(wraptext("foo"), [node2p1, node2p2]) node3p1 = pgens("b", "c") node3p2 = pgens("1", "d") node3 = Template(wraptext("foo"), [pgenh("1", "a"), node3p1, node3p2]) node4p1 = pgens(" b", " ") node4 = Template(wraptext("foo"), [pgenh("1", "a"), node4p1]) self.assertRaises(ValueError, node1.get, "foobar") self.assertIs(node2p1, node2.get(1)) self.assertIs(node2p2, node2.get("abc")) self.assertRaises(ValueError, node2.get, "def") self.assertIs(node3p1, node3.get("b")) self.assertIs(node3p2, node3.get("1")) self.assertIs(node4p1, node4.get("b "))
def test_value(self): """test getter/setter for the value attribute""" value = wraptext("foo") node = Attribute(wraptext("id"), value) self.assertIs(value, node.value) node.value = "{{bar}}" self.assertWikicodeEqual(wrap([Template(wraptext("bar"))]), node.value) node.value = None self.assertIs(None, node.value) node2 = Attribute(wraptext("id"), wraptext("foo"), None) node2.value = "foo bar baz" self.assertWikicodeEqual(wraptext("foo bar baz"), node2.value) self.assertEqual('"', node2.quotes) node2.value = 'foo "bar" baz' self.assertWikicodeEqual(wraptext('foo "bar" baz'), node2.value) self.assertEqual("'", node2.quotes) node2.value = "foo 'bar' baz" self.assertWikicodeEqual(wraptext("foo 'bar' baz"), node2.value) self.assertEqual('"', node2.quotes) node2.value = "fo\"o 'bar' b\"az" self.assertWikicodeEqual(wraptext("fo\"o 'bar' b\"az"), node2.value) self.assertEqual('"', node2.quotes)
def test_remove(self): """test Template.remove()""" node1 = Template(wraptext("foobar")) node2 = Template(wraptext("foo"), [pgenh("1", "bar"), pgens("abc", "def")]) node3 = Template(wraptext("foo"), [pgenh("1", "bar"), pgens("abc", "def")]) node4 = Template(wraptext("foo"), [pgenh("1", "bar"), pgenh("2", "baz")]) node5 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node6 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node7 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgens(" 1", "b"), pgens("2", "c")]) node8 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgens(" 1", "b"), pgens("2", "c")]) node9 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgenh("1", "b"), pgenh("2", "c")]) node10 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgenh("1", "b"), pgenh("2", "c")]) node11 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node12 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node13 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node14 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node15 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node16 = Template(wraptext("foo"), [ pgens(" a", "b"), pgens("b", "c"), pgens("a ", "d")]) node17 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgenh("1", "b"), pgenh("2", "c")]) node18 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgenh("1", "b"), pgenh("2", "c")]) node19 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgenh("1", "b"), pgenh("2", "c")]) node20 = Template(wraptext("foo"), [ pgens("1 ", "a"), pgenh("1", "b"), pgenh("2", "c")]) node21 = Template(wraptext("foo"), [ pgens("a", "b"), pgens("c", "d"), pgens("e", "f"), pgens("a", "b"), pgens("a", "b")]) node22 = Template(wraptext("foo"), [ pgens("a", "b"), pgens("c", "d"), pgens("e", "f"), pgens("a", "b"), pgens("a", "b")]) node23 = Template(wraptext("foo"), [ pgens("a", "b"), pgens("c", "d"), pgens("e", "f"), pgens("a", "b"), pgens("a", "b")]) node24 = Template(wraptext("foo"), [ pgens("a", "b"), pgens("c", "d"), pgens("e", "f"), pgens("a", "b"), pgens("a", "b")]) node25 = Template(wraptext("foo"), [ pgens("a", "b"), pgens("c", "d"), pgens("e", "f"), pgens("a", "b"), pgens("a", "b")]) node26 = Template(wraptext("foo"), [ pgens("a", "b"), pgens("c", "d"), pgens("e", "f"), pgens("a", "b"), pgens("a", "b")]) node27 = Template(wraptext("foo"), [pgenh("1", "bar")]) node28 = Template(wraptext("foo"), [pgenh("1", "bar")]) node2.remove("1") node2.remove("abc") node3.remove(1, keep_field=True) node3.remove("abc", keep_field=True) node4.remove("1", keep_field=False) node5.remove("a", keep_field=False) node6.remove("a", keep_field=True) node7.remove(1, keep_field=True) node8.remove(1, keep_field=False) node9.remove(1, keep_field=True) node10.remove(1, keep_field=False) node11.remove(node11.params[0], keep_field=False) node12.remove(node12.params[0], keep_field=True) node13.remove(node13.params[1], keep_field=False) node14.remove(node14.params[1], keep_field=True) node15.remove(node15.params[2], keep_field=False) node16.remove(node16.params[2], keep_field=True) node17.remove(node17.params[0], keep_field=False) node18.remove(node18.params[0], keep_field=True) node19.remove(node19.params[1], keep_field=False) node20.remove(node20.params[1], keep_field=True) node21.remove("a", keep_field=False) node22.remove("a", keep_field=True) node23.remove(node23.params[0], keep_field=False) node24.remove(node24.params[0], keep_field=True) node25.remove(node25.params[3], keep_field=False) node26.remove(node26.params[3], keep_field=True) self.assertRaises(ValueError, node1.remove, 1) self.assertRaises(ValueError, node1.remove, "a") self.assertRaises(ValueError, node2.remove, "1") self.assertEqual("{{foo}}", node2) self.assertEqual("{{foo||abc=}}", node3) self.assertEqual("{{foo||baz}}", node4) self.assertEqual("{{foo|b=c}}", node5) self.assertEqual("{{foo| a=|b=c}}", node6) self.assertEqual("{{foo|1 =|2=c}}", node7) self.assertEqual("{{foo|2=c}}", node8) self.assertEqual("{{foo||c}}", node9) self.assertEqual("{{foo||c}}", node10) self.assertEqual("{{foo|b=c|a =d}}", node11) self.assertEqual("{{foo| a=|b=c|a =d}}", node12) self.assertEqual("{{foo| a=b|a =d}}", node13) self.assertEqual("{{foo| a=b|b=|a =d}}", node14) self.assertEqual("{{foo| a=b|b=c}}", node15) self.assertEqual("{{foo| a=b|b=c|a =}}", node16) self.assertEqual("{{foo|b|c}}", node17) self.assertEqual("{{foo|1 =|b|c}}", node18) self.assertEqual("{{foo|1 =a||c}}", node19) self.assertEqual("{{foo|1 =a||c}}", node20) self.assertEqual("{{foo|c=d|e=f}}", node21) self.assertEqual("{{foo|a=|c=d|e=f}}", node22) self.assertEqual("{{foo|c=d|e=f|a=b|a=b}}", node23) self.assertEqual("{{foo|a=|c=d|e=f|a=b|a=b}}", node24) self.assertEqual("{{foo|a=b|c=d|e=f|a=b}}", node25) self.assertEqual("{{foo|a=b|c=d|e=f|a=|a=b}}", node26) self.assertRaises(ValueError, node27.remove, node28.get(1))
def test_add(self): """test Template.add()""" node1 = Template(wraptext("a"), [pgens("b", "c"), pgenh("1", "d")]) node2 = Template(wraptext("a"), [pgens("b", "c"), pgenh("1", "d")]) node3 = Template(wraptext("a"), [pgens("b", "c"), pgenh("1", "d")]) node4 = Template(wraptext("a"), [pgens("b", "c"), pgenh("1", "d")]) node5 = Template(wraptext("a"), [pgens("b", "c"), pgens(" d ", "e")]) node6 = Template(wraptext("a"), [pgens("b", "c"), pgens("b", "d"), pgens("b", "e")]) node7 = Template(wraptext("a"), [pgens("b", "c"), pgenh("1", "d")]) node8p = pgenh("1", "d") node8 = Template(wraptext("a"), [pgens("b", "c"), node8p]) node9 = Template(wraptext("a"), [pgens("b", "c"), pgenh("1", "d")]) node10 = Template(wraptext("a"), [pgens("b", "c"), pgenh("1", "e")]) node11 = Template(wraptext("a"), [pgens("b", "c")]) node12 = Template(wraptext("a"), [pgens("b", "c")]) node13 = Template(wraptext("a"), [ pgens("\nb ", " c"), pgens("\nd ", " e"), pgens("\nf ", " g")]) node14 = Template(wraptext("a\n"), [ pgens("b ", "c\n"), pgens("d ", " e"), pgens("f ", "g\n"), pgens("h ", " i\n")]) node15 = Template(wraptext("a"), [ pgens("b ", " c\n"), pgens("\nd ", " e"), pgens("\nf ", "g ")]) node16 = Template(wraptext("a"), [ pgens("\nb ", " c"), pgens("\nd ", " e"), pgens("\nf ", " g")]) node17 = Template(wraptext("a"), [pgenh("1", "b")]) node18 = Template(wraptext("a"), [pgenh("1", "b")]) node19 = Template(wraptext("a"), [pgenh("1", "b")]) node20 = Template(wraptext("a"), [pgenh("1", "b"), pgenh("2", "c"), pgenh("3", "d"), pgenh("4", "e")]) node21 = Template(wraptext("a"), [pgenh("1", "b"), pgenh("2", "c"), pgens("4", "d"), pgens("5", "e")]) node22 = Template(wraptext("a"), [pgenh("1", "b"), pgenh("2", "c"), pgens("4", "d"), pgens("5", "e")]) node23 = Template(wraptext("a"), [pgenh("1", "b")]) node24 = Template(wraptext("a"), [pgenh("1", "b")]) node25 = Template(wraptext("a"), [pgens("b", "c")]) node26 = Template(wraptext("a"), [pgenh("1", "b")]) node27 = Template(wraptext("a"), [pgenh("1", "b")]) node28 = Template(wraptext("a"), [pgens("1", "b")]) node29 = Template(wraptext("a"), [ pgens("\nb ", " c"), pgens("\nd ", " e"), pgens("\nf ", " g")]) node30 = Template(wraptext("a\n"), [ pgens("b ", "c\n"), pgens("d ", " e"), pgens("f ", "g\n"), pgens("h ", " i\n")]) node31 = Template(wraptext("a"), [ pgens("b ", " c\n"), pgens("\nd ", " e"), pgens("\nf ", "g ")]) node32 = Template(wraptext("a"), [ pgens("\nb ", " c "), pgens("\nd ", " e "), pgens("\nf ", " g ")]) node33 = Template(wraptext("a"), [pgens("b", "c"), pgens("d", "e"), pgens("b", "f"), pgens("b", "h"), pgens("i", "j")]) node34 = Template(wraptext("a"), [pgens("1", "b"), pgens("x", "y"), pgens("1", "c"), pgens("2", "d")]) node35 = Template(wraptext("a"), [pgens("1", "b"), pgens("x", "y"), pgenh("1", "c"), pgenh("2", "d")]) node36 = Template(wraptext("a"), [pgens("b", "c"), pgens("d", "e"), pgens("f", "g")]) node37 = Template(wraptext("a"), [pgenh("1", "")]) node38 = Template(wraptext("abc")) node1.add("e", "f", showkey=True) node2.add(2, "g", showkey=False) node3.add("e", "foo|bar", showkey=True) node4.add("e", "f", showkey=True, before="b") node5.add("f", "g", showkey=True, before=" d ") node6.add("f", "g", showkey=True, before="b") self.assertRaises(ValueError, node7.add, "e", "f", showkey=True, before="q") node8.add("e", "f", showkey=True, before=node8p) node9.add("e", "f", showkey=True, before=pgenh("1", "d")) self.assertRaises(ValueError, node10.add, "e", "f", showkey=True, before=pgenh("1", "d")) node11.add("d", "foo=bar", showkey=True) node12.add("1", "foo=bar", showkey=False) node13.add("h", "i", showkey=True) node14.add("j", "k", showkey=True) node15.add("h", "i", showkey=True) node16.add("h", "i", showkey=True, preserve_spacing=False) node17.add("2", "c") node18.add("3", "c") node19.add("c", "d") node20.add("5", "f") node21.add("3", "f") node22.add("6", "f") node23.add("c", "foo=bar") node24.add("2", "foo=bar") node25.add("b", "d") node26.add("1", "foo=bar") node27.add("1", "foo=bar", showkey=True) node28.add("1", "foo=bar", showkey=False) node29.add("d", "foo") node30.add("f", "foo") node31.add("f", "foo") node32.add("d", "foo", preserve_spacing=False) node33.add("b", "k") node34.add("1", "e") node35.add("1", "e") node36.add("d", "h", before="b") node37.add(1, "b") node38.add("1", "foo") self.assertRaises(ValueError, node38.add, "z", "bar", showkey=False) self.assertEqual("{{a|b=c|d|e=f}}", node1) self.assertEqual("{{a|b=c|d|g}}", node2) self.assertEqual("{{a|b=c|d|e=foo|bar}}", node3) self.assertIsInstance(node3.params[2].value.get(1), HTMLEntity) self.assertEqual("{{a|e=f|b=c|d}}", node4) self.assertEqual("{{a|b=c|f=g| d =e}}", node5) self.assertEqual("{{a|b=c|b=d|f=g|b=e}}", node6) self.assertEqual("{{a|b=c|d}}", node7) self.assertEqual("{{a|b=c|e=f|d}}", node8) self.assertEqual("{{a|b=c|e=f|d}}", node9) self.assertEqual("{{a|b=c|e}}", node10) self.assertEqual("{{a|b=c|d=foo=bar}}", node11) self.assertEqual("{{a|b=c|foo=bar}}", node12) self.assertIsInstance(node12.params[1].value.get(1), HTMLEntity) self.assertEqual("{{a|\nb = c|\nd = e|\nf = g|\nh = i}}", node13) self.assertEqual("{{a\n|b =c\n|d = e|f =g\n|h = i\n|j =k\n}}", node14) self.assertEqual("{{a|b = c\n|\nd = e|\nf =g |h =i}}", node15) self.assertEqual("{{a|\nb = c|\nd = e|\nf = g|h=i}}", node16) self.assertEqual("{{a|b|c}}", node17) self.assertEqual("{{a|b|3=c}}", node18) self.assertEqual("{{a|b|c=d}}", node19) self.assertEqual("{{a|b|c|d|e|f}}", node20) self.assertEqual("{{a|b|c|4=d|5=e|f}}", node21) self.assertEqual("{{a|b|c|4=d|5=e|6=f}}", node22) self.assertEqual("{{a|b|c=foo=bar}}", node23) self.assertEqual("{{a|b|foo=bar}}", node24) self.assertIsInstance(node24.params[1].value.get(1), HTMLEntity) self.assertEqual("{{a|b=d}}", node25) self.assertEqual("{{a|foo=bar}}", node26) self.assertIsInstance(node26.params[0].value.get(1), HTMLEntity) self.assertEqual("{{a|1=foo=bar}}", node27) self.assertEqual("{{a|foo=bar}}", node28) self.assertIsInstance(node28.params[0].value.get(1), HTMLEntity) self.assertEqual("{{a|\nb = c|\nd = foo|\nf = g}}", node29) self.assertEqual("{{a\n|b =c\n|d = e|f =foo\n|h = i\n}}", node30) self.assertEqual("{{a|b = c\n|\nd = e|\nf =foo }}", node31) self.assertEqual("{{a|\nb = c |\nd =foo|\nf = g }}", node32) self.assertEqual("{{a|b=k|d=e|i=j}}", node33) self.assertEqual("{{a|1=e|x=y|2=d}}", node34) self.assertEqual("{{a|x=y|e|d}}", node35) self.assertEqual("{{a|b=c|d=h|f=g}}", node36) self.assertEqual("{{a|b}}", node37) self.assertEqual("{{abc|foo}}", node38)
def test_has(self): """test Template.has()""" node1 = Template(wraptext("foobar")) node2 = Template(wraptext("foo"), [pgenh("1", "bar"), pgens("\nabc ", "def")]) node3 = Template(wraptext("foo"), [pgenh("1", "a"), pgens("b", "c"), pgens("1", "d")]) node4 = Template(wraptext("foo"), [pgenh("1", "a"), pgens("b", " ")]) self.assertFalse(node1.has("foobar", False)) self.assertTrue(node2.has(1, False)) self.assertTrue(node2.has("abc", False)) self.assertFalse(node2.has("def", False)) self.assertTrue(node3.has("1", False)) self.assertTrue(node3.has(" b ", False)) self.assertTrue(node4.has("b", False)) self.assertTrue(node3.has("b", True)) self.assertFalse(node4.has("b", True)) self.assertFalse(node1.has_param("foobar", False)) self.assertTrue(node2.has_param(1, False))