示例#1
0
    def test_equivalence(self):
        """Two conjunctions are equivalent if they have the same operands."""
        op1 = And(BoolVar(), TrafficLightVar())
        op2 = And(TrafficLightVar(), BoolVar())
        op3 = And(DriversAwaitingGreenLightVar(), BoolVar())
        op4 = And(DriversAwaitingGreenLightVar(), BoolVar())
        op5 = Or(DriversAwaitingGreenLightVar(), BoolVar())

        assert_node_equivalence(
            (op1, op2),
            (op3, op4),
            (op5, ),
        )
示例#2
0
    def test_equivalence(self):
        """
        Two exclusive disjunctions are equivalent if they have the same
        operands.
        
        """
        op1 = Xor(BoolVar(), PedestriansCrossingRoad())
        op2 = Xor(PedestriansCrossingRoad(), BoolVar())
        op3 = Xor(DriversAwaitingGreenLightVar(), BoolVar())
        op4 = Xor(DriversAwaitingGreenLightVar(), BoolVar())
        op5 = Or(DriversAwaitingGreenLightVar(), BoolVar())

        assert_node_equivalence(
            (op1, op2),
            (op3, op4),
            (op5, ),
        )
示例#3
0
 def test_operation(self):
     """Operations are valid evaluable parse trees."""
     operation = And(PedestriansCrossingRoad(),
                     DriversAwaitingGreenLightVar())
     tree = EvaluableParseTree(operation)
     # True
     context = {'pedestrians_crossroad': ("gustavo", "carla"),
                'drivers_trafficlight': ("andreina", "juan")}
     ok_(tree(context))
     # False
     context = {'pedestrians_crossroad': (),
                'drivers_traffic_light': ()}
     assert_false(tree(context))
示例#4
0
class TestEvaluableParser(object):
    """Tests for the evaluable parser."""

    global_objects = {
        'bool': BoolVar(),
        'message': String("Hello world"),
        'foo': PermissiveFunction,
    }

    traffic_objects = {
        'traffic_light': TrafficLightVar(),
        'pedestrians_crossing_road': PedestriansCrossingRoad(),
        'drivers_awaiting_green_light': DriversAwaitingGreenLightVar(),
        'traffic_violation': TrafficViolationFunc,
    }

    root_namespace = Namespace(global_objects, {
        'traffic': Namespace(traffic_objects),
    })

    parser = EvaluableParser(Grammar(), root_namespace)

    #{ Tests for the parse action that makes the variables

    def test_existing_variable_without_namespace(self):
        parse_tree = self.parser("~ bool")
        eq_(parse_tree.root_node, Not(self.global_objects['bool']))

    def test_existing_variable_with_namespace(self):
        parse_tree = self.parser('traffic:traffic_light == "green"')
        expected_node = Equal(self.traffic_objects['traffic_light'],
                              String("green"))
        eq_(parse_tree.root_node, expected_node)

    def test_non_existing_variable_without_namespace(self):
        assert_raises(ScopeError, self.parser, "~ non_existing_var")

    def test_non_existing_variable_with_namespace(self):
        assert_raises(ScopeError, self.parser, "~ traffic:non_existing_var")

    def test_variable_in_non_existing_namespace(self):
        assert_raises(ScopeError, self.parser, "~ bar:foo")

    def test_function_instead_of_variable(self):
        # "foo" is a function, so it cannot be used as a variable (without
        # parenthesis):
        try:
            self.parser('~ foo')
        except BadExpressionError, exc:
            eq_('"foo" represents a function, not a variable', unicode(exc))
        else:
示例#5
0
    def test_variable_evaluation(self):
        subset = DriversAwaitingGreenLightVar()
        set_ = PedestriansCrossingRoad()
        operation = IsSubset(subset, set_)

        # {"carla"} ⊂ {"carla", "andreina"}
        context1 = {
            'drivers_trafficlight': ("carla", ),
            'pedestrians_crossroad': ("andreina", "carla")
        }
        ok_(operation(context1))

        # {"liliana", "carlos"} ⊂ {"manuel", "yolmary", "carla"}
        context2 = {
            'drivers_trafficlight': ("liliana", "carlos"),
            'pedestrians_crossroad': ("manuel", "yolmary", "carla")
        }
        assert_false(operation(context2))
示例#6
0
    def test_variables_evaluation(self):
        operation = NotEqual(PedestriansCrossingRoad(),
                             DriversAwaitingGreenLightVar())

        # The pedestrians are different from the drivers... That's my universe!
        context = {
            'pedestrians_crossroad': ("gustavo", "carla"),
            'drivers_trafficlight': ("liliana", "carlos")
        }
        ok_(operation(context))

        # The pedestrians awaiting the green light to cross the street are
        # the same drivers... Must be a parallel universe!
        context = {
            'pedestrians_crossroad': ("gustavo", "carla"),
            'drivers_trafficlight': ("carla", "gustavo")
        }
        assert_false(operation(context))
示例#7
0
class TestEvaluableParseManager(object):
    """
    Tests for the :class:`EvaluableParseManager` with caching disabled.
    
    """

    # A symbol table to be used across the tests:
    symbol_table = SymbolTable(
        "root",
        (
            Bind("boolean", BoolVar(), es="booleano"),
            Bind("message", String("Hello world"), es="mensaje"),
            Bind("foo", PermissiveFunction, es="fulano"),
        ),
        SymbolTable("traffic", (
            Bind("traffic_light", TrafficLightVar(), es=u"semáforo"),
            Bind("pedestrians_crossing_road",
                 PedestriansCrossingRoad(),
                 es="peatones_cruzando_calle"),
            Bind("drivers_awaiting_green",
                 DriversAwaitingGreenLightVar(),
                 es="conductores_esperando_verde"),
            Bind("traffic_violation", TrafficViolationFunc, es=u"infracción"),
        ),
                    es=u"tráfico"),
    )

    def test_parsing_with_no_localized_grammars(self):
        mgr = EvaluableParseManager(self.symbol_table, Grammar())
        parse_tree1 = mgr.parse('message == "2009-07-13"')
        parse_tree2 = mgr.parse('message == "2009-07-13"', None)
        expected_tree = EvaluableParseTree(
            Equal(String("Hello world"), String("2009-07-13")))
        eq_(parse_tree1, parse_tree2)
        eq_(parse_tree1, expected_tree)

    def test_parsing_with_localized_grammars(self):
        castilian_grammar = Grammar(decimal_separator=",",
                                    thousands_separator=".")
        mgr = EvaluableParseManager(self.symbol_table,
                                    Grammar(),
                                    es=castilian_grammar)
        parse_tree = mgr.parse(u"tráfico:peatones_cruzando_calle <= 3,00",
                               "es")
        expected_tree = EvaluableParseTree(
            LessEqual(PedestriansCrossingRoad(), Number(3.0)))
        eq_(parse_tree, expected_tree)

    def test_parsing_with_undefined_grammar_but_available_translations(self):
        """
        When an expression is written in an unsupported grammar, a parser
        based on the generic grammar must be created and used.
        
        The respective translated bindings must be used if available.
        
        """
        log_handler = LoggingHandlerFixture()
        mgr = EvaluableParseManager(self.symbol_table, Grammar())
        # Castilian grammar is not supported:
        parse_tree = mgr.parse(u"tráfico:peatones_cruzando_calle <= 3.0", "es")
        expected_tree = EvaluableParseTree(
            LessEqual(PedestriansCrossingRoad(), Number(3)))
        eq_(parse_tree, expected_tree)
        # Checking the log:
        info = "Generated parser for unknown grammar 'es'"
        ok_(info in log_handler.handler.messages['info'])
        log_handler.undo()

    def test_parsing_with_undefined_grammar_and_no_translated_bindings(self):
        """
        When an expression is written in an unsupported grammar, a parser
        based on the generic grammar must be created and used.
        
        If there are no translated bindings, the default names must be used.
        
        """
        log_handler = LoggingHandlerFixture()
        mgr = EvaluableParseManager(self.symbol_table, Grammar())
        # French grammar is not supported:
        parse_tree = mgr.parse("traffic:pedestrians_crossing_road <= 3.0",
                               "fr")
        expected_tree = EvaluableParseTree(
            LessEqual(PedestriansCrossingRoad(), Number(3)))
        eq_(parse_tree, expected_tree)
        # Checking the log:
        info = "Generated parser for unknown grammar 'fr'"
        ok_(info in log_handler.handler.messages['info'])
        log_handler.undo()

    def test_parsing_with_defined_grammar_but_no_available_translations(self):
        """
        When an expression is written in an supported grammar but there are no
        translated bindings, the default names must be used along with the
        custom grammar.
        
        """
        french_grammar = Grammar(decimal_separator=",",
                                 thousands_separator=".")
        mgr = EvaluableParseManager(self.symbol_table,
                                    Grammar(),
                                    fr=french_grammar)
        # French grammar is not supported:
        parse_tree = mgr.parse("traffic:pedestrians_crossing_road <= 3,0",
                               "fr")
        expected_tree = EvaluableParseTree(
            LessEqual(PedestriansCrossingRoad(), Number(3)))
        eq_(parse_tree, expected_tree)

    def test_adding_grammar(self):
        """It should be possible to add grammars after instantiation."""
        castilian_grammar = Grammar(decimal_separator=",",
                                    thousands_separator=".")
        mgr = EvaluableParseManager(self.symbol_table, Grammar())
        mgr.add_parser("es", castilian_grammar)
        parse_tree = mgr.parse(u'tráfico:peatones_cruzando_calle <= 3,00',
                               "es")
        expected_tree = EvaluableParseTree(
            LessEqual(PedestriansCrossingRoad(), Number(3.0)))
        eq_(parse_tree, expected_tree)

    def test_adding_existing_grammar(self):
        """There can't be duplicate/overlapped parsers."""
        mgr = EvaluableParseManager(self.symbol_table, Grammar(), es=Grammar())
        assert_raises(GrammarError, mgr.add_parser, "es", Grammar())

    def test_evaluating_expressions(self):
        """Managers should be able to evaluate the expressions too."""
        mgr = EvaluableParseManager(self.symbol_table, Grammar())
        context = {'pedestrians_crossroad': (u"gustavo", u"carla")}
        evaluation1 = mgr.evaluate("traffic:pedestrians_crossing_road <= 3",
                                   None, context)
        evaluation2 = mgr.evaluate(
            u'"carla" ∈ traffic:pedestrians_crossing_road', None, context)
        evaluation3 = mgr.evaluate("traffic:pedestrians_crossing_road > 2",
                                   None, context)
        ok_(evaluation1)
        ok_(evaluation2)
        assert_false(evaluation3)