Exemplo n.º 1
0
    def setUp(self):
        """Create a real client with some mocking."""
        self.client = Client()
        self.client.transport = MagicMock()
        peer = MagicMock()
        peer.host = "127.0.0.1"
        peer.port = 4000
        self.client.transport.getPeer = MagicMock(return_value=peer)
        self.client.factory = MagicMock()

        # Create the sharp engine
        sharp = SharpScript(self.client.factory.engine, self.client,
                MagicMock())
        sharp.bind_client(self.client)
        self.client.factory.sharp_engine = sharp

        def get_setting(address):
            """Private function to return a set of default settings."""
            default = {
                    "options.input.command_stacking": "",
                    "options.general.encoding": "latin-1",
            }
            return default[address]

        self.client.factory.engine.settings.__getitem__ = MagicMock(
                side_effect=get_setting)
Exemplo n.º 2
0
    def sharp_engine(self):
        if self._sharp_engine:
            return self._sharp_engine

        log.debug(
            f"Creating a SharpEngine for session {self.sid} (world: {'yes' if self.world else 'no'}, client: {'yes' if self.client else 'no'}, character: {'yes' if self.character else 'no'}, engine: {'yes' if self.engine else 'no'})"
        )
        self._sharp_engine = SharpScript(self.engine, self.client, self.world)
        return self._sharp_engine
Exemplo n.º 3
0
    def prepare_world(self, world, merge=None):
        """Prepare the world, creating appropriate values."""
        if not world.sharp_engine:
            sharp_engine = SharpScript(self, None, world)
            world.sharp_engine = sharp_engine

        if merge is not None:
            if merge == "ignore":
                world.merging = MergingMethod.ignore
            elif merge == "replace":
                world.merging = MergingMethod.replace
            else:
                raise ValueError("unkwno merging method: {}".format(
                        merge))
Exemplo n.º 4
0
 def setUp(self):
     """Create the SharpScript instance."""
     self.engine = SharpScript(None, None, None)
Exemplo n.º 5
0
class TestFormat(unittest.TestCase):

    """Unittest for the SharpScript format."""

    def setUp(self):
        """Create the SharpScript instance."""
        self.engine = SharpScript(None, None, None)

    def test_single(self):
        """Test a single statement."""
        # Test a statement on one line with one argument
        content = self.engine.format("#play file.wav")
        self.assertEqual(content, "#play file.wav")

        # Test a statement with an new line and no argument
        content = self.engine.format("#stop\n")
        self.assertEqual(content, "#stop")

        # Same test, but with some useless spaces
        content = self.engine.format("  #stop  \n  ")
        self.assertEqual(content, "#stop")

        # Test a statement with arguments surrounded by braces
        content = self.engine.format("#macro {Alt + Enter} north")
        self.assertEqual(content, "#macro {Alt + Enter} north")

        # Same test but with some useless spaces
        content = self.engine.format("  #macro  {Alt + Enter}  north\n  ")
        self.assertEqual(content, "#macro {Alt + Enter} north")

        # Test what happens without function names
        content = self.engine.format("say Hello all!\n  ")
        self.assertEqual(content, "#send {say Hello all!}")

    def test_multiple(self):
        """Test multiple statements at once."""
        # Test two statements on two lines without useless spaces
        content = self.engine.format("#play file.wav\n#stop")
        self.assertEqual(content, "#play file.wav\n#stop")

        # Same test, but with some useless spaces
        content = self.engine.format("  #play   file.wav  \n#stop  \n  ")
        self.assertEqual(content, "#play file.wav\n#stop")

    def test_python(self):
        """Test Python format embeeded in SharpScript."""
        content = self.engine.format(dedent("""
        #trigger {Should it work?} {+
            var = 2 + 3
            print var
        }""".strip("\n")))
        self.assertEqual(content, dedent("""
        #trigger {Should it work?} {+
            var = 2 + 3
            print var
        }""".strip("\n")))

    def test_flag(self):
        """Test the SharpScript format with flags in funciton calls."""
        content = self.engine.format("#say {A message} -braille +speech")
        self.assertEqual(content, "#say {A message} -braille +speech")

    def test_semicolons(self):
        """Test the semi-colons."""
        # A test with simple text
        content = self.engine.format("#macro F1 north;south;;east")
        self.assertEqual(content, "#macro F1 north;south;;east")

        # A test with SharpScript
        content = self.engine.format("#trigger ok {#play new.wav;#stop}")
        self.assertEqual(content, "#trigger ok {#play new.wav;#stop}")

    def test_escape_sharp(self):
        """Test the escaped sharp symbol."""
        # A sharp escaping with plain text
        content = self.engine.format("##out")
        self.assertEqual(content, "#send #out")
Exemplo n.º 6
0
class TestSyntax(unittest.TestCase):

    """Unittest for the SharpScript syntax."""

    def setUp(self):
        """Create the SharpScript instance."""
        self.engine = SharpScript(None, None, None)

    def test_single(self):
        """Test a single statement."""
        # Test a statement on one line with one argument
        statements = self.engine.feed("#play file.wav")
        self.assertEqual(statements, ["play('file.wav')"])

        # Test a statement with an new line and no argument
        statements = self.engine.feed("#stop\n")
        self.assertEqual(statements, ["stop()"])

        # Same test, but with some useless spaces
        statements = self.engine.feed("  #stop  \n  ")
        self.assertEqual(statements, ["stop()"])

        # Test a statement with arguments surrounded by braces
        statements = self.engine.feed("#macro {Alt + Enter} north")
        self.assertEqual(statements, ["macro('Alt + Enter', 'north')"])

        # Same test but with some useless spaces
        statements = self.engine.feed("  #macro  {Alt + Enter}  north\n  ")
        self.assertEqual(statements, ["macro('Alt + Enter', 'north')"])

        # Test what happens without function names
        statements = self.engine.feed("say Hello all!\n  ")
        self.assertEqual(statements, ["send('say Hello all!')"])

    def test_multiple(self):
        """Test multiple statements at once."""
        # Test two statements on two lines without useless spaces
        statements = self.engine.feed("#play file.wav\n#stop")
        self.assertEqual(statements, ["play('file.wav')", "stop()"])

        # Same test, but with some useless spaces
        statements = self.engine.feed("  #play   file.wav  \n#stop  \n  ")
        self.assertEqual(statements, ["play('file.wav')", "stop()"])

    def test_python(self):
        """Test Python syntax embeeded in SharpScript."""
        statements = self.engine.feed("""#trigger {Should it work?} {+
            var = 2 + 3
            print var
        }""")
        self.assertEqual(statements, [
            "trigger('Should it work?', '{+\\n" \
            "            var = 2 + 3\\n" \
            "            print var\\n        }')"""
        ])

    def test_flag(self):
        """Test the SharpScript syntax with flags in funciton calls."""
        statements = self.engine.feed("#say {A message} -braille +speech")
        self.assertEqual(statements, [
            "say('A message', braille=False, speech=True)"
        ])

    def test_python_top(self):
        """Test Python code in SharpScript at the top level."""
        statements = self.engine.feed("""{+
            print 1
            print 3
        }""")
        self.assertEqual(statements, [
            'print 1\nprint 3',
        ])

    def test_semicolons(self):
        """Test the semi-colons."""
        # A test with simple text
        statements = self.engine.feed("#macro F1 north;south;;east")
        self.assertEqual(statements, ["macro('F1', 'north\nsouth;east')"])

        # A test with SharpScript
        statements = self.engine.feed("#trigger ok {#play new.wav;#stop}")
        self.assertEqual(statements, [
                "trigger('ok', '#play new.wav\\n#stop')",
        ])

    def test_simple_variables(self):
        """Test simple variables."""
        self.engine.locals["a"] = 30
        self.engine.locals["b"] = -80
        self.engine.locals["art"] = "magnificient"

        # Try to display the variables
        statements = self.engine.feed("#send {Display a: $a.}",
                variables=True)
        self.assertEqual(statements, ["send('Display a: 30.')"])
        statements = self.engine.feed("#send {Display b: $b.}",
                variables=True)
        self.assertEqual(statements, ["send('Display b: -80.')"])
        statements = self.engine.feed("#send {Display art: $art.}",
                variables=True)
        self.assertEqual(statements, ["send('Display art: magnificient.')"])
        statements = self.engine.feed("#send {a=$a, b=$b, art=$art.}",
                variables=True)
        self.assertEqual(statements, ["send('a=30, b=-80, art=magnificient.')"])

    def test_variables_args(self):
        """Test variables in arguments."""
        args = {"1": 800}
        self.engine.locals["args"] = args
        statements = self.engine.feed("#send $1", variables=True)
        self.assertEqual(statements, ["send('800')"])

    def test_escape_variables(self):
        """Test a more complex syntax for variables."""
        self.engine.locals["sum"] = 500
        self.engine.locals["HP"] = 20
        self.engine.locals["s"] = "calc"

        # Try to display the variables
        statements = self.engine.feed("#send {sum=$sum}",
                variables=True)
        self.assertEqual(statements, ["send('sum=500')"])
        statements = self.engine.feed("#send {You have \\$$sum.}",
                variables=True)
        self.assertEqual(statements, ["send('You have $500.')"])
        statements = self.engine.feed("#send {You have ${HP}HP left.}",
                variables=True)
        self.assertEqual(statements, ["send('You have 20HP left.')"])
        statements = self.engine.feed("#send {You have ${H}HP left.}",
                variables=True)
        self.assertEqual(statements, ["send('You have HP left.')"])

    def test_escape_sharp(self):
        """Test the escaped sharp symbol."""
        # A sharp escaping with plain text
        statements = self.engine.feed("##out")
        self.assertEqual(statements, ["send('#out')"])

        # A sharp escaping with SharpScript
        statements = self.engine.feed("#macro ##ok")
        self.assertEqual(statements, ["macro('#ok')"])

    def test_multiline(self):
        """Test the SharpScript editor with multiple lines."""
        statements = self.engine.feed("#action {ok} {\n    1\n    2\n}")
        self.assertEqual(statements, [
                "action('ok', '\\n    1\\n    2\\n')",
        ])

    def test_python_variables(self):
        """Test with Python variables."""
        code = dedent("""
            {+
            try:
                i
            except NameError:
                i = 0

            i += 1
            }
        """.strip("\n"))

        self.engine.execute(code)
        self.assertEqual(self.engine.locals["i"], 1)
        self.engine.execute(code)
        self.assertEqual(self.engine.locals["i"], 2)

        # Try to get the 'i' variable
        self.engine.execute(code)
        statements = self.engine.feed("#say {i=$i}",
                variables=True)
        self.assertEqual(statements, ["say('i=3')"])
Exemplo n.º 7
0
 def setUp(self):
     """Create the SharpScript instance."""
     self.engine = SharpScript(None, None, None)
Exemplo n.º 8
0
class TestSyntax(unittest.TestCase):
    """Unittest for the SharpScript syntax."""
    def setUp(self):
        """Create the SharpScript instance."""
        self.engine = SharpScript(None, None, None)

    def test_single(self):
        """Test a single statement."""
        # Test a statement on one line with one argument
        statements = self.engine.feed("#play file.wav")
        self.assertEqual(statements, ["play('file.wav')"])

        # Test a statement with an new line and no argument
        statements = self.engine.feed("#stop\n")
        self.assertEqual(statements, ["stop()"])

        # Same test, but with some useless spaces
        statements = self.engine.feed("  #stop  \n  ")
        self.assertEqual(statements, ["stop()"])

        # Test a statement with arguments surrounded by braces
        statements = self.engine.feed("#macro {Alt + Enter} north")
        self.assertEqual(statements, ["macro('Alt + Enter', 'north')"])

        # Same test but with some useless spaces
        statements = self.engine.feed("  #macro  {Alt + Enter}  north\n  ")
        self.assertEqual(statements, ["macro('Alt + Enter', 'north')"])

        # Test what happens without function names
        statements = self.engine.feed("say Hello all!\n  ")
        self.assertEqual(statements, ["send('say Hello all!')"])

    def test_multiple(self):
        """Test multiple statements at once."""
        # Test two statements on two lines without useless spaces
        statements = self.engine.feed("#play file.wav\n#stop")
        self.assertEqual(statements, ["play('file.wav')", "stop()"])

        # Same test, but with some useless spaces
        statements = self.engine.feed("  #play   file.wav  \n#stop  \n  ")
        self.assertEqual(statements, ["play('file.wav')", "stop()"])

    def test_python(self):
        """Test Python syntax embeeded in SharpScript."""
        statements = self.engine.feed("""#trigger {Should it work?} {+
            var = 2 + 3
            print var
        }""")
        self.assertEqual(statements, [
            "trigger('Should it work?', '{+\\n" \
            "            var = 2 + 3\\n" \
            "            print var\\n        }')"""
        ])

    def test_flag(self):
        """Test the SharpScript syntax with flags in funciton calls."""
        statements = self.engine.feed("#say {A message} -braille +speech")
        self.assertEqual(statements,
                         ["say('A message', braille=False, speech=True)"])

    def test_python_top(self):
        """Test Python code in SharpScript at the top level."""
        statements = self.engine.feed("""{+
            print 1
            print 3
        }""")
        self.assertEqual(statements, [
            'print 1\nprint 3',
        ])

    def test_semicolons(self):
        """Test the semi-colons."""
        # A test with simple text
        statements = self.engine.feed("#macro F1 north;south;;east")
        self.assertEqual(statements, ["macro('F1', 'north\nsouth;east')"])

        # A test with SharpScript
        statements = self.engine.feed("#trigger ok {#play new.wav;#stop}")
        self.assertEqual(statements, [
            "trigger('ok', '#play new.wav\\n#stop')",
        ])

    def test_simple_variables(self):
        """Test simple variables."""
        self.engine.locals["a"] = 30
        self.engine.locals["b"] = -80
        self.engine.locals["art"] = "magnificient"

        # Try to display the variables
        statements = self.engine.feed("#send {Display a: $a.}", variables=True)
        self.assertEqual(statements, ["send('Display a: 30.')"])
        statements = self.engine.feed("#send {Display b: $b.}", variables=True)
        self.assertEqual(statements, ["send('Display b: -80.')"])
        statements = self.engine.feed("#send {Display art: $art.}",
                                      variables=True)
        self.assertEqual(statements, ["send('Display art: magnificient.')"])
        statements = self.engine.feed("#send {a=$a, b=$b, art=$art.}",
                                      variables=True)
        self.assertEqual(statements,
                         ["send('a=30, b=-80, art=magnificient.')"])

    def test_variables_args(self):
        """Test variables in arguments."""
        args = {"1": 800}
        self.engine.locals["args"] = args
        statements = self.engine.feed("#send $1", variables=True)
        self.assertEqual(statements, ["send('800')"])

    def test_escape_variables(self):
        """Test a more complex syntax for variables."""
        self.engine.locals["sum"] = 500
        self.engine.locals["HP"] = 20
        self.engine.locals["s"] = "calc"

        # Try to display the variables
        statements = self.engine.feed("#send {sum=$sum}", variables=True)
        self.assertEqual(statements, ["send('sum=500')"])
        statements = self.engine.feed("#send {You have \\$$sum.}",
                                      variables=True)
        self.assertEqual(statements, ["send('You have $500.')"])
        statements = self.engine.feed("#send {You have ${HP}HP left.}",
                                      variables=True)
        self.assertEqual(statements, ["send('You have 20HP left.')"])
        statements = self.engine.feed("#send {You have ${H}HP left.}",
                                      variables=True)
        self.assertEqual(statements, ["send('You have HP left.')"])

    def test_escape_sharp(self):
        """Test the escaped sharp symbol."""
        # A sharp escaping with plain text
        statements = self.engine.feed("##out")
        self.assertEqual(statements, ["send('#out')"])

        # A sharp escaping with SharpScript
        statements = self.engine.feed("#macro ##ok")
        self.assertEqual(statements, ["macro('#ok')"])

    def test_multiline(self):
        """Test the SharpScript editor with multiple lines."""
        statements = self.engine.feed("#action {ok} {\n    1\n    2\n}")
        self.assertEqual(statements, [
            "action('ok', '\\n    1\\n    2\\n')",
        ])

    def test_python_variables(self):
        """Test with Python variables."""
        code = dedent("""
            {+
            try:
                i
            except NameError:
                i = 0

            i += 1
            }
        """.strip("\n"))

        self.engine.execute(code)
        self.assertEqual(self.engine.locals["i"], 1)
        self.engine.execute(code)
        self.assertEqual(self.engine.locals["i"], 2)

        # Try to get the 'i' variable
        self.engine.execute(code)
        statements = self.engine.feed("#say {i=$i}", variables=True)
        self.assertEqual(statements, ["say('i=3')"])