def test_grammar():

    validator_fail = False

    class DummyType(object):
        pass

    class TestGrammarClass(object):
        def __init__(self):
            self.grammar = GrammarDict()

        @grammar
        def test_grammar(value):
            if validator_fail:
                raise ValueError('validator failed')

        @grammar(grammar_type=DummyType)
        def test_grammar_with_type(value):
            if validator_fail:
                raise ValueError('validator failed')

        @grammar(grammar_name='a name')
        def test_grammar_with_name(value):
            if validator_fail:
                raise ValueError('validator failed')

    test = TestGrammarClass()
    nt.assert_is_none(test.test_grammar)
    nt.assert_dict_equal(test.grammar, {})

    test.test_grammar = 'testing'
    nt.assert_equal(test.test_grammar, 'testing')
    nt.assert_dict_equal(test.grammar, {'test_grammar': 'testing'})

    del test.test_grammar
    nt.assert_is_none(test.test_grammar)
    nt.assert_dict_equal(test.grammar, {})

    validator_fail = True
    nt.assert_raises_regexp(ValueError, 'validator failed', setattr, test,
                            'test_grammar', 'testing')

    # grammar with type checking
    test = TestGrammarClass()
    validator_fail = False
    dummy = DummyType()
    test.test_grammar_with_type = dummy
    nt.assert_equal(test.test_grammar_with_type, dummy)
    nt.assert_dict_equal(test.grammar, {'test_grammar_with_type': dummy})
    nt.assert_raises_regexp(ValueError, 'must be DummyType', setattr, test,
                            'test_grammar_with_type', 'testing')
    validator_fail = True
    nt.assert_raises_regexp(ValueError, 'validator failed', setattr, test,
                            'test_grammar_with_type', dummy)

    # grammar with field name
    test = TestGrammarClass()
    validator_fail = False
    test.test_grammar_with_name = 'testing'
    nt.assert_equal(test.test_grammar_with_name, 'testing')
    nt.assert_dict_equal(test.grammar, {'a name': 'testing'})
    validator_fail = True
    nt.assert_raises_regexp(ValueError, 'validator failed', setattr, test,
                            'test_grammar_with_name', 'testing')
Grammar decorator behaves correctly.
dataset/ETHPy150Open wrobstory/vincent/tests/test_vega.py/test_grammar