#! /usr/bin/env python

import types
import unittest
from pyprolog import swipl

class test_PQuery(unittest.TestCase):
    
    def setUp(self):
        return
    
    def test_call_predicate(self): 
        msg = 'call_predicate is wrong.'

        # load and compile calc.pl into prolog.
        g = swipl.chars_to_term("consult(%s)." % 'calc')
        assert repr(g) == 'consult(calc)', msg
        g.call()
        
        # retrieve the predicate from the loaded module.
        pred = swipl.new_predicate("calc", 2, "user")
        assert repr(pred) == 'user:calc/2', msg
        
        # make arguments for call: calc('1+2', Result).
        h0 = swipl.new_term()
        h0.put_atom(swipl.new_atom('1+2'))
        assert repr(h0) == '1+2', msg
        
        Result = swipl.chars_to_term('Result')
        assert repr(Result)[:2] == '_G', msg
        
        args = swipl.make_args([h0, Result])
        assert repr(args) == 'PTermArray[2]', msg
        
        # call it.
        r = pred.call_predicate(swipl.PL_Q_NORMAL, args)
        assert r, msg
        assert repr(Result) == '3', msg
    
    def test_call_member(self): 
        msg = 'call_member is wrong.'
        
        # fetch already defined predicate.
        member = swipl.new_predicate("member", 2, "")
        name, arity, module = member.predicate_info()
        assert repr(name) == 'new_atom("member")'
        assert arity == 2
        
        # make arg vector
        X = swipl.chars_to_term('X')
        assert X.is_variable()
        
        items = swipl.chars_to_term("[alpha, beta, gamma]")
        assert items.is_list()
        
        args = swipl.make_args([X, items])
        assert repr(args) == 'PTermArray[2]'
        
        # start query
        query = swipl.open_query(member, args, swipl.PL_Q_NORMAL, module)
        assert repr(query)[:6] == 'query:'
        
        # first solution
        assert query.next_solution()
        assert repr(X) == 'alpha'
        
        # backtrack
        assert query.next_solution()
        assert repr(X) == 'beta'
        
        assert query.next_solution()
        assert repr(X) == 'gamma'
        
        # no more solutions
        assert not query.next_solution()
        
        query.close_query()

def make_suite():
    suite = unittest.TestSuite()
    suite.addTest(test_PQuery('test_call_predicate'))
    suite.addTest(test_PQuery('test_call_member'))
    return suite

def main():
    runner = unittest.TextTestRunner()
    suite = make_suite()
    runner.run(suite)

if __name__ == '__main__':
    main()
   
# Local Variables:          
# mode:python               
# indent-tabs-mode: nil     
# py-indent-offset: 4  
# py-smart-indentation: nil 
# End:                      
