Beispiel #1
0
 def test_add_heading_ids(self):
     dialect = create_dialect(creole10_base, add_heading_ids=True)
     parse = Parser(dialect)
     self.assertEquals(
         parse("== Level 2"),
         '<h2 id="!level-2">Level 2</h2>\n')
     self.assertEquals(
         parse("= Level 1\n= Level 1"),
         '<h1 id="!level-1">Level 1</h1>\n<h1 id="!level-1_1">Level 1</h1>\n')
     self.assertEquals(
         parse("= [[http://www.google.com|Google]]\n"),
         """<h1 id="!google"><a href="http://www.google.com">Google</a></h1>\n""")
     self.assertEquals(
         parse("== http://www.google.com\n"),
         """<h2 id="!http-www-google-com"><a href="http://www.google.com">http://www.google.com</a></h2>\n""")
     self.assertEquals(
         parse("== ~http://www.google.com\n"),
         '<h2 id="!http-www-google-com">http://www.google.com</h2>\n')
     self.assertEquals(
         parse("[[foo bar#!a-heading_1]]"),
         wrap_result("""<a href="foo_bar#!a-heading_1">foo bar#!a-heading_1</a>"""))
     self.assertEquals(
         parse("[[#!a-heading]]"),
         wrap_result("""<a href="#!a-heading">#!a-heading</a>"""))
     self.assertEquals(
         parse("[[foo bar#1]]"),
         wrap_result("""<a href="foo_bar%231">foo bar#1</a>"""))
     self.assertEquals(
         parse("[[#1]]"),
         wrap_result("""<a href="%231">#1</a>"""))
     dialect = create_dialect(creole10_base, add_heading_ids='')
     parse = Parser(dialect)
     self.assertEquals(
         parse("== Level 2"),
         '<h2 id="level-2">Level 2</h2>\n')
Beispiel #2
0
def run_tests():
    vm = VirtualMachine()

    test_files = sorted(os.listdir(test_dir))

    for i, file_name in enumerate(test_files):
        full_path = osp.join(test_dir, file_name)

        print('>>> Run test #{} ({})'.format(i, file_name))
        with open(full_path) as f:
            text = f.read()

            compiler = Compiler()
            parser = Parser(Lexer(text))

            ast = parser.parse()

            # print(ast)  # выведем дерево

            program = compiler.compile(ast)

            vars = vm.run(program)

            print('Execution finished.')
            for j in range(26):
                if vars[j] != '$':
                    print('{} = {}'.format(chr(j + ord('a')), vars[j]))

        print('\n' + '#' * 40 + '\n')
Beispiel #3
0
    def test_log_splitter_wrong_log(self):
        """
        log_splitter should not call any other function
        if the received log is not on the correct format or
        if the log does not match any of the predicted logs
        """
        with mock.patch('core.Parser.init_game') as mockFunc1:
            with mock.patch('core.Parser.shutdown_game') as mockFunc2:
                with mock.patch('core.Parser.score_kill') as mockFunc3:
                    with mock.patch(
                            'core.Parser.userinfo_changed') as mockFunc4:
                        with mock.patch(
                                'core.Parser.client_begin') as mockFunc5:
                            with mock.patch('core.Parser.client_disconnect'
                                            ) as mockFunc6:
                                parser = Parser()
                                parser.log_splitter('blablabla anything')
                                parser.log_splitter('21:32 Item: whatever')

                                mockFunc1.assert_not_called()
                                mockFunc2.assert_not_called()
                                mockFunc3.assert_not_called()
                                mockFunc4.assert_not_called()
                                mockFunc5.assert_not_called()
                                mockFunc6.assert_not_called()
Beispiel #4
0
    def test_shutdown_game(self):
        """
        shutdown_game should put the list active_players on game_info['kills']
        should also clear the list active_players
        should add one to the count of current_game
        should call print_game()
        """
        intersection = [{'Fulano': 56}, {'Deltrano': 1}, {'Jack': 0}]
        active_players_mock = {
            '2': ['Fulano', 56],
            '6': ['Deltrano', 1],
            '12': ['Jack', 0]
        }
        kills_mock = [{'Player1': 3}, {'Player2': 987}]

        parser = Parser()

        with mock.patch('core.Parser.print_game') as mockFunc:
            parser.active_players = active_players_mock
            parser.game_info['kills'] = kills_mock
            parser.current_game = 11
            parser.shutdown_game()

            assert parser.current_game == 12
            mockFunc.assert_called_once_with()
            self.assertDictEqual(parser.game_info['kills'][2], intersection[0])
            self.assertDictEqual(parser.game_info['kills'][3], intersection[1])
            self.assertDictEqual(parser.game_info['kills'][4], intersection[2])
Beispiel #5
0
    def setUp(self):
        def inter_wiki_link_maker(name):
            return name[::-1]

        def simple_class_maker(name):
            return name.lower()

        functions = {
            'moo':inter_wiki_link_maker,
            'goo':inter_wiki_link_maker,
            }
        base_urls = {
            'goo': 'http://example.org',
            'poo': 'http://example.org',
            'Ohana': inter_wiki_url,
            }
        space_characters = {
            'goo': '+',
            'poo': '+',
            }

        class_functions = {
            'moo':simple_class_maker,
            'goo':simple_class_maker,
            }

        dialect = create_dialect(creole10_base,
            interwiki_links_path_funcs=functions,
            interwiki_links_class_funcs=class_functions,
            interwiki_links_base_urls=base_urls,
            interwiki_links_space_chars=space_characters
            )

        self.parse = Parser(dialect)
Beispiel #6
0
def nextPage(next_page, number_page, headers, cookie, config, filename, regex):
    p = Parser.Parser()
    print("{YELLOW}\n+[PAGE %s/%s]-----------------------------------------+".
          format(**colors) %
          (next_page.split("&")[1].split("=")[1], number_page))
    content_html = requestPage(next_page, headers, cookie)
    p.getSearch(content_html.content, number_page, headers, cookie, config,
                filename, regex)
Beispiel #7
0
 def test_simple_tokens_option(self):
     Base = creole10_base()
     class MyDialect(Base):
         simple_element = SimpleElement(token_dict={'*':'strong','#':'code'})
     parse = Parser(MyDialect)
     self.assertEquals(
         parse("This block of #text *should* be monospace# now"),
         wrap_result("This block of <code>text <strong>should</strong> be monospace</code> now"))
Beispiel #8
0
 def test_blog_style_endings_option(self):
     dialect = create_dialect(creole10_base, blog_style_endings=True)
     parse = Parser(dialect)
     self.assertEquals(
         parse("The first line\nthis text **should** be on the second line\n now third"),
         wrap_result("The first line<br />this text <strong>should</strong> be on the second line<br /> now third"))
     self.assertEquals(
         parse("The first line\\\\\nthis text **should** be on the second line\\\\\n now third"),
         wrap_result("The first line<br />this text <strong>should</strong> be on the second line<br /> now third"))
Beispiel #9
0
 def setUp(self):
     self.parse = Parser(
     dialect=create_dialect(creole11_base,
     wiki_links_base_url='',
     interwiki_links_base_urls={'Ohana': inter_wiki_url},
     #use_additions=True,
     no_wiki_monospace=False
        )
     )
Beispiel #10
0
 def setUp(self):
     creole2html = Parser(
         dialect=create_dialect(creole10_base,
             wiki_links_base_url=base_url,
             interwiki_links_base_urls={'Ohana': inter_wiki_url},
             #use_additions=False,
             no_wiki_monospace=True,
             )
         )
     self.parse = creole2html
Beispiel #11
0
 def setUp(self):
     dialect = create_dialect(creole11_base,
         wiki_links_base_url='',
         wiki_links_space_char='_',
         interwiki_links_base_urls={'Ohana': inter_wiki_url},
         no_wiki_monospace=False,
         macro_func=self.macroFactory,
         bodied_macros=dict(span=self.span, div=self.div),
         non_bodied_macros=dict(luca=self.luca),                                 
                              )
     self.parse = Parser(dialect)
Beispiel #12
0
 def setUp(self):
     noSpaces = Parser(
         dialect=create_dialect(creole11_base,
             wiki_links_base_url=base_url,
             wiki_links_space_char='',
             interwiki_links_base_urls={'Ohana': inter_wiki_url},
             no_wiki_monospace=False,
             wiki_links_class_func=class_name_function,
             wiki_links_path_func=path_name_function
             )
         )
     self.parse = noSpaces
Beispiel #13
0
 def test_disable_images(self):
     Base = creole10_base()
     class MyDialect(Base):
         @property
         def inline_elements(self):
             l = super(MyDialect,self).inline_elements
             l.remove(self.img)
             return l
     parse = Parser(MyDialect)
     self.assertEquals(
         parse("{{somefile.jpg}}"),
         wrap_result("{{somefile.jpg}}"))
Beispiel #14
0
 def test_disable_external_content(self):
     dialect = create_dialect(creole10_base, disable_external_content=True)
     parse = Parser(dialect)
     self.assertEquals(
         parse("{{campfire.jpg}}"),
         wrap_result("""<img src="campfire.jpg" alt="campfire.jpg" title="campfire.jpg" />"""))
     self.assertEquals(
         parse("{{/campfire.jpg}}"),
         wrap_result("""<span class="external_image">External images are disabled</span>"""))
     self.assertEquals(
         parse("{{http://www.somesite.com/campfire.jpg}}"),
         wrap_result("""<span class="external_image">External images are disabled</span>"""))
Beispiel #15
0
 def test_external_links_class_option(self):
     dialect = create_dialect(creole10_base, external_links_class='external')
     parse = Parser(dialect)
     self.assertEquals(
         parse("[[campfire.jpg]]"),
         wrap_result("""<a href="campfire.jpg">campfire.jpg</a>"""))
     self.assertEquals(
         parse("[[/campfire.jpg]]"),
         wrap_result("""<a class="external" href="/campfire.jpg">/campfire.jpg</a>"""))
     self.assertEquals(
         parse("[[http://www.somesite.com/campfire.jpg]]"),
         wrap_result("""<a class="external" href="http://www.somesite.com/campfire.jpg">http://www.somesite.com/campfire.jpg</a>"""))
Beispiel #16
0
 def test_interwiki_image_link_options(self):
     dialect = create_dialect(creole10_base,
                              interwiki_links_base_urls={'a': ['/pages/','/files/']},
                              interwiki_links_space_chars={'a': ['_',' ']},
                              interwiki_links_path_funcs={'a': [lambda s:s.upper(),
                                                                 lambda s:s.capitalize()]})
     parse = Parser(dialect)
     self.assertEquals(
         parse("[[a:foo bar|Foo]]"),
         wrap_result("""<a href="/pages/FOO_BAR">Foo</a>"""))
     self.assertEquals(
         parse("{{a:foo bar|Foo}}"),
         wrap_result("""<img src="/files/Foo bar" alt="Foo" title="Foo" />"""))
Beispiel #17
0
 def test_custom_markup_option(self):
     def wikiword(mo, e):
         return builder.tag.a(mo.group(1),href=mo.group(1))
     dialect = create_dialect(creole10_base,
                              custom_markup=[('(c)','&copy;'),
                                             (re.compile(esc_neg_look + r'\b([A-Z]\w+[A-Z]+\w+)'),wikiword)])
     parse = Parser(dialect)
     self.assertEquals(
         parse("The copyright symbol (c), escaped ~(c)"),
         wrap_result("The copyright symbol &copy;, escaped (c)"))
     self.assertEquals(
         parse("A WikiPage name that is a ~WikiWord"),
         wrap_result('A <a href="WikiPage">WikiPage</a> name that is a WikiWord'))
Beispiel #18
0
 def test_image_link_options(self):
     dialect = create_dialect(creole10_base, wiki_links_base_url=['/pages/',
                                                                  '/files/'],
                              wiki_links_space_char=['_',' '],
                              wiki_links_path_func=[lambda s:s.upper(),
                                                    lambda s:s.capitalize()])
     parse = Parser(dialect)
     self.assertEquals(
         parse("[[foo bar]]"),
         wrap_result("""<a href="/pages/FOO_BAR">foo bar</a>"""))
     self.assertEquals(
         parse("{{foo bar}}"),
         wrap_result("""<img src="/files/Foo bar" alt="foo bar" title="foo bar" />"""))
Beispiel #19
0
def main():

    taskManager = TaskManager()

    parser = Parser(taskManager=taskManager)

    printWelcomeMessage()

    while (True):
        print("$ ", end="")
        command = input()
        if command == "":
            continue
        parser.processCommand(command)
Beispiel #20
0
def start(arg1, arg2):

    pathToFile = arg1  #sys.argv[1]
    pathToInputSettings = arg2  #sys.argv[2]
    parser = Parser.Parser(pathToFile, pathToInputSettings)

    if parser.parseNetwork():
        network = parser.returnNetwork()
        network.countTotalUnitCostPerPath()

        settings = parser.returnSettings()
        printSettings(settings)

        populationSize = int(settings['population_size'])
        probabOfCrossingover = float(settings['probab_of_crossingover'])
        probabOfMutation = float(settings['probab_of_mutation'])
        stopCriterion = settings['stop_criterion']
        valueOfStopCriterion = int(settings['value_of_stop_criterion'])
        seed = int(settings['seed'])

        if settings['method'] == 'evolution':
            isDAP = True if (settings['problem'] == 'DAP') else False
            evo = Evolution.Evolution(isDAP, populationSize,
                                      probabOfCrossingover, probabOfMutation,
                                      seed, stopCriterion,
                                      valueOfStopCriterion)
            evo.createStartingPopulation(network)
            evo.startEvolutionAlgorithm()

        elif settings['method'] == 'bruteforce':
            isDAP = True if (settings['problem'] == 'DAP') else False
            bruteforce = BruteForce.BruteForce(network, isDAP)
            bruteforce.startBruteforce()

        # elif settings['method'] == 'bruteforce' and settings['problem'] == 'DDAP':
        #     bruteforce = BruteForce.BruteForce(network)
        #     bruteforce.generateAllPossibleSolutions()
        #     print(bruteforce.m_ListOfAllPossibleSolutions)
        #     # ddap = DDAP.DDAP(network, 100)
        #     # ddap.startBruteForceIterations()

        else:
            print("!!!!!!!!!!!!!!!!!!!!")
            print("SOMETHING WENT WRONG")
            print("!!!!!!!!!!!!!!!!!!!!")
            print("BELOW CORECT INPUT FILE")
            print(parser.exampleOfInputFile)
Beispiel #21
0
    def test_init_game(self):
        """
        init_game should rest game_info to be equal base_dict
        """
        game_info_mock = {'item': 'some item', 'action': 'a random action'}
        base_dict_mock = {
            'word': 'the corresponding word',
            'something': [],
            'anotherThing': {}
        }

        parser = Parser()

        parser.game_info = game_info_mock
        parser.base_dict = base_dict_mock
        parser.init_game()
        assert parser.game_info == base_dict_mock
Beispiel #22
0
    def test_client_begin(self):
        """
        client_begin should pass the confirmed active player to the list of players
        """
        active_players_mock = {
            '2': ['New Player', 0],
            '6': ['Deltrano', 1],
            '12': ['Jack', 0]
        }

        game_info_players = ['Fulano', 'Deltrano', 'Jack']

        parser = Parser()

        parser.active_players = active_players_mock
        parser.game_info['players'] = game_info_players

        parser.client_begin('2')
        assert parser.game_info['players'][3] == 'New Player'
Beispiel #23
0
    def test_userinfo_changed(self):
        """
        userinfo_changed should update the list of active players
        """
        active_players_mock = {
            '2': ['Fulano', 5],
            '6': ['Deltrano', 1],
            '12': ['Jack', 0]
        }

        game_info_players = ['Fulano', 'Deltrano', 'Jack']

        parser = Parser()

        parser.active_players = active_players_mock
        parser.game_info['players'] = game_info_players

        parser.userinfo_changed('4 n\\New Player\\whatever')
        assert parser.active_players['4'] == ['New Player', 0]
Beispiel #24
0
 def test_log_splitter(self):
     """
     log_splitter should call the correct functions, with the
     correct arguments depending on what is passed by as argument
     """
     test_cases = [{
         'path_name': 'init_game',
         'log': '0:00 InitGame: the game has begun',
         'argument': None
     }, {
         'path_name': 'shutdown_game',
         'log': '78:32 ShutdownGame: game over',
         'argument': None
     }, {
         'path_name': 'score_kill',
         'log': '89:12 Kill: Somebody died!',
         'argument': 'Somebody died!'
     }, {
         'path_name': 'userinfo_changed',
         'log': '34:45 ClientUserinfoChanged: Some info has changed',
         'argument': 'Some info has changed'
     }, {
         'path_name': 'client_disconnect',
         'log': '58:62 ClientDisconnect: Fulano DC',
         'argument': 'Fulano DC'
     }, {
         'path_name': 'client_begin',
         'log': '58:62 ClientBegin: Fulano begin',
         'argument': 'Fulano begin'
     }]
     parser = Parser()
     for params in test_cases:
         with mock.patch('core.Parser.' + params['path_name']) as mockFunc:
             parser.log_splitter(params['log'])
             if params['argument'] is None:
                 mockFunc.assert_called_with()
             else:
                 mockFunc.assert_called_once_with(params['argument'])
Beispiel #25
0
    def test_client_disconnect(self):
        """
        client_disconnect should pass the info from active_players to game_info['kills'] from the DC player
        """
        kills_mock = [{'Player1': 3}, {'Player2': 987}]
        active_players_mock = {
            '2': ['New Player', 67],
            '6': ['Deltrano', 1],
            '12': ['Jack', 0]
        }

        parser = Parser()

        parser.game_info['kills'] = kills_mock
        parser.active_players = active_players_mock

        parser.client_disconnect('6')

        if '6' in parser.active_players:
            assert False
        else:
            assert True
        assert parser.game_info['kills'][2] == {'Deltrano': 1}
Beispiel #26
0
    def test_score_kill(self):
        """
        score_kill should give points to the player that killed
        should take out one point if the player died from <world>
        should increase the count of total kills
        should increase the kill count of that death cause
        """
        death_causes = [{
            'death_cause': 0
        }, {
            'death_cause': 0
        }, {
            'death_cause': 0
        }]

        active_players_mock = {
            '2': ['Fulano', 5],
            '6': ['Deltrano', 1],
            '12': ['Jack', 0]
        }

        parser = Parser()
        parser.death_causes = death_causes
        parser.active_players = active_players_mock
        parser.game_info['total_kills'] = 6

        # World kill
        parser.score_kill('1022 2 0: something something')
        assert parser.game_info['total_kills'] == 7
        assert parser.active_players['2'][1] == 4
        assert parser.death_causes[0]['death_cause'] == 1

        # Player kill
        parser.score_kill('6 12 2: something something')
        assert parser.game_info['total_kills'] == 8
        assert parser.active_players['6'][1] == 2
        assert parser.death_causes[2]['death_cause'] == 1
Beispiel #27
0
 def test_bodied_macros_option(self):
     def red(macro,e,*args,**kw):
         return builder.tag.__getattr__(macro.isblock and 'div' or 'span')(
             macro.parsed_body(),style='color:red')
     red.parse_body = True
         #return {'style':'color:red'}
     def blockquote(macro,e,*args,**kw):
         return builder.tag.blockquote(macro.parsed_body())
     blockquote.parse_body = True
         #return {'tag':'blockquote'}
     MyDialect = create_dialect(creole11_base, bodied_macros=dict(red=red, blockquote=blockquote))
     parse = Parser(MyDialect)
     self.assertEquals(
         parse("This block of <<red>>text **should** be monospace<</red>> now"),
         wrap_result('This block of <span style="color:red">text <strong>should</strong> be monospace</span> now'))
     self.assertEquals(
         parse("<<red>>\ntext **should** be monospace\n<</red>>"),
         '<div style="color:red"><p>text <strong>should</strong> be monospace</p>\n</div>')
     self.assertEquals(
         parse("This block of <<blockquote>>text **should** be monospace<</blockquote>> now"),
         wrap_result('This block of </p><blockquote>text <strong>should</strong> be monospace</blockquote><p> now'))
     self.assertEquals(
         parse("<<blockquote>>\ntext **should** be monospace\n<</blockquote>>"),
         '<blockquote><p>text <strong>should</strong> be monospace</p>\n</blockquote>')
Beispiel #28
0
    def test_print_game(self):
        """
        print_game should get the top player of the match
        should get the deaths by cause
        should dump all the game info into game_json
        """
        game_info_mock = {
            'total_kills': 34,
            'players': ['Fulano', 'Player1', 'Player2'],
            'kills': [{
                'Player1': 3
            }, {
                'Player2': 12
            }, {
                'Fulano': 6
            }],
            'kills_by_means': {}
        }

        death_causes_mock = [{
            'death_cause0': 6
        }, {
            'death_cause1': 0
        }, {
            'death_cause2': 28
        }]

        death_causes_base_mock = [{
            'death_cause0': 0
        }, {
            'death_cause1': 0
        }, {
            'death_cause2': 0
        }]

        cheat_sheet = {
            'total_kills': 34,
            'players': ['Fulano', 'Player1', 'Player2'],
            'kills': [{
                'Player1': 3
            }, {
                'Player2': 12
            }, {
                'Fulano': 6
            }],
            'kills_by_means': {
                'death_cause0': 6,
                'death_cause2': 28
            },
            'top_player': 'Player2'
        }

        parser = Parser()

        parser.game_info = game_info_mock
        parser.death_causes = death_causes_mock
        parser.current_game = 15

        parser.print_game()

        assert parser.death_causes == death_causes_base_mock
        assert parser.game_json['game-15'] == cheat_sheet
Beispiel #29
0
 def test_simple_markup_option(self):
     MyDialect = create_dialect(creole10_base, simple_markup=[('*','strong'),('#','code')])
     parse = Parser(MyDialect)
     self.assertEquals(
         parse("This block of #text *should* be monospace# now"),
         wrap_result("This block of <code>text <strong>should</strong> be monospace</code> now"))
Beispiel #30
0
#
# This module is part of Creoleparser and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
#
import string
import keyword

from core import Parser, ArgParser
from dialects import (creole11_base, creole10_base, creepy10_base,
                      create_dialect)

__docformat__ = 'restructuredtext en'

__version__ = '0.7.2'

creole2html = Parser(dialect=create_dialect(creole10_base), method='html')
"""This is a pure Creole 1.0 parser created for convenience"""

text2html = Parser(dialect=create_dialect(creole11_base), method='html')
"""This is a Creole 1.0 parser (+ additions) created for convenience"""

parse_args = ArgParser(
    dialect=creepy10_base(),
    key_func=string.lower,
    illegal_keys=keyword.kwlist +
    ['macro_name', 'arg_string', 'body', 'isblock', 'environ', 'macro'])
"""Function for parsing macro arg_strings using a relaxed xml style"""


def _test():
    import doctest