[antlr-interest] antlr python unit testing

Laurie Harper laurie at holoweb.net
Thu May 3 20:20:24 PDT 2007


Thanks, that's a lot easier than the solution I came up with, mocking a 
Python object with a read(int) method and injecting it into the lexer so 
it would wrap it in a CharReader or whatever.

L.

Kaleb Pederson wrote:
> Hi Laurie,
> 
> In python, stdin is just a file descriptor that you can change.  So, if you 
> wanted to manipulate it to read from a file, or some other object that had 
> the same interface as a file descriptor, you could do so.
> 
> For example:
> 
> import sys
> sys.stdin = open('myfile','r');
> 
> Then, if you needed to get the regular stdin back, sys.stdin = sys.__stdin__
> 
> So, take advantage of the StringIO class:
> 
> import StringIO
> import sys
> 
> sys.stdin = StringIO.StringIO("My text to be parsed")
> 
> Now you can run your unit tests using whatever text you want.
> 
> Hope that helps.
> 
> --Kaleb
> 
> On Thursday 03 May 2007, Laurie Harper wrote:
>> I'm using ANTLR for Python and have my lexer and parser partially
>> working. I would like to start writing unit tests to identify exactly
>> what is and isn't right in what I have so far. (Call it test-first
>> debugging ;-)
>>
>> This is a total newbie question but, how do I pass input into my lexer
>> or parser from a Python script, rather than having it come from stdin?
>> Ideally, I'd like to create a lexer instance and a parser instance and
>> then write unit tests that exercise specific rules with varying input,
>> al la:
>>
>>      import unittest
>>      class LexerTests(unittest.TestCase):
>>          def setUp(self):
>>              self.L = lexer()
>>              self.P = parser(self.L)
>>
>>          def test_lexer(self):
>>              input = "specimen input"
>>
>>              # *****
>>              self.L.INJECT_INPUT_CHARACTERS(input)
>>              # *****
>>
>>              self.failUnlessEqual(some_result, self.L.nextToken())
>>
>>          def test_parser(self):
>>              input = "specimen input"
>>
>>              # *****
>>              self.L.INJECT_INPUT_CHARACTERS(input)
>>              # *****
>>
>>              self.failUnlessEqual(some_result, self.P.someRule()
>>
>> How do I achieve the INJECT_INPUT_CHARACTERS(input) part?
>>
>> L.
> 
> 
> 



More information about the antlr-interest mailing list