⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testbasics.java

📁 Jena推理机
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/******************************************************************
 * File:        TestBasics.java
 * Created by:  Dave Reynolds
 * Created on:  30-Mar-03
 * 
 * (c) Copyright 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
 * [See end of file]
 * $Id: TestBasics.java,v 1.38 2007/01/02 11:50:30 andy_seaborne Exp $
 *****************************************************************/
package com.hp.hpl.jena.reasoner.rulesys.test;

import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.reasoner.*;
import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.reasoner.rulesys.impl.*;
import com.hp.hpl.jena.reasoner.test.TestUtil;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.util.PrintUtil;
import com.hp.hpl.jena.vocabulary.*;

import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.util.*;
import java.io.*;

/**
 * Unit tests for simple infrastructure pieces of the rule systems.
 * 
 * @author <a href="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
 * @version $Revision: 1.38 $ on $Date: 2007/01/02 11:50:30 $
 */
public class TestBasics extends TestCase  {
    
    // Maximum size of binding environment needed in the tests
    private static final int MAX_VARS = 10;
    
    // Useful constants
    Node p = Node.createURI("p");
    Node q = Node.createURI("q");
    Node r = Node.createURI("r");
    Node s = Node.createURI("s");
    Node n1 = Node.createURI("n1");
    Node n2 = Node.createURI("n2");
    Node n3 = Node.createURI("n3");
    Node n4 = Node.createURI("n4");
    Node n5 = Node.createURI("n5");
    Node res = Node.createURI("res");
        
     
    /**
     * Boilerplate for junit
     */ 
    public TestBasics( String name ) {
        super( name ); 
    }
    
    /**
     * Boilerplate for junit.
     * This is its own test suite
     */
    public static TestSuite suite() {
        return new TestSuite( TestBasics.class ); 
    }  

    /**
     * Test the internal rule parser
     */
    public void testRuleParser() {
       String[] testRules = new String[] {
            "(?a rdf:type ?_) -> (?a rdf:type ?b).",
            "(?a rdf:type ?_), (?a rdf:type ?_) -> (?a rdf:type ?b).",
            "(?a rdf:type max(?a,1)) -> (?a rdf:type 'foo').",
            "(?a rdf:type ?_) -> addOne(?a).",
            "(?a rdf:type ?_) -> [(?a rdf:type ?_) -> addOne(?a)].",
           "(?a rdf:type ?_) -> (?a rdf:type '42').",
           "(?a rdf:type ?_) -> (?a rdf:type 4.2).",
           "(?a rdf:type ?_) -> (?a rdf:type ' fool that,I(am)').",
            "[rule1: (?a rdf:type ?_) -> (?a rdf:type a)]",
            "-> print(' ').",
            "-> print(' literal with embedded \\' characters ').",
            "-> print(\" literal characters \").",
            "-> print(42). ",
            "-> print('42'^^xsd:byte). ",
            "-> print('42'^^http://www.w3.org/2001/XMLSchema#int). ",
            "-> print('42'^^foobar:byte). "
        };
        String[] testResults = new String[] {
            "[ (?a rdf:type ?_) -> (?a rdf:type ?b) ]",
            "[ (?a rdf:type ?_) (?a rdf:type ?_) -> (?a rdf:type ?b) ]",
            "[ (?a rdf:type 'max(?a '1'^^http://www.w3.org/2001/XMLSchema#int)'^^urn:x-hp-jena:Functor) -> (?a rdf:type 'foo') ]",
            "[ (?a rdf:type ?_) -> addOne(?a) ]",
            "[ (?a rdf:type ?_) -> [ (?a rdf:type ?_) -> addOne(?a) ] ]",
            "[ (?a rdf:type ?_) -> (?a rdf:type '42') ]",
            "[ (?a rdf:type ?_) -> (?a rdf:type '4.2'^^http://www.w3.org/2001/XMLSchema#float) ]",
            "[ (?a rdf:type ?_) -> (?a rdf:type ' fool that,I(am)') ]",
            "[ rule1: (?a rdf:type ?_) -> (?a rdf:type a) ]",
            "[ -> print(' ') ]",
            "[ -> print(' literal with embedded ' characters ') ]",
            "[ -> print(' literal characters ') ]",
            "[ -> print('42'^^http://www.w3.org/2001/XMLSchema#int) ]",
            "[ -> print('42'^^http://www.w3.org/2001/XMLSchema#byte) ]",
            "[ -> print('42'^^http://www.w3.org/2001/XMLSchema#int) ]",
            "[ -> print('42'^^http://foobar#byte) ]",
        };
        
        PrintUtil.registerPrefix("foobar", "http://foobar#");
        for (int i = 0; i < testRules.length; i++) {
            Rule r = Rule.parseRule(testRules[i]);
            assertEquals(testResults[i], r.toString());
        }
        
        // Test for an illegal rule format
        String[] testBadRules = new String[] {
                "(foo(?A) eg:p ?B) <- (?a, eg:p, ?B)." ,
                "(foo(?A) eg:p ?B) -> (?a, eg:p, ?B)." 
        };
        for (int i = 0; i < testBadRules.length; i++) {
            boolean foundError = false;
            try {
                Rule r = Rule.parseRule(testBadRules[i]);
            } catch (Rule.ParserException e) {
                foundError = true;
            }
            assertTrue("Failed to find illegal rule", foundError);
        }
    }

    /**
     * Test rule equality operations.
     */
    public void testRuleEquality() {
        Rule r1 = Rule.parseRule("(?a p ?b) -> (?a q ?b).");
        Rule r2 = Rule.parseRule("(?a p ?b) -> (?b q ?a).");
        Rule r1b = Rule.parseRule("(?x p ?y) -> (?x q ?y).");
        Rule r3 = Rule.parseRule("(?a p ?b), addOne(?a) -> (?a q ?b).");
        Rule r3b = Rule.parseRule("(?c p ?d), addOne(?c) -> (?c q ?d).");
        Rule r4 = Rule.parseRule("(?a p ?b), makeTemp(?a) -> (?a q ?b).");
        Rule r5 = Rule.parseRule("(?a p ?b), addOne(?b) -> (?a q ?b).");
        Rule r6 = Rule.parseRule("(?a p ?b), addOne(p) -> (?a q ?b).");
        assertTrue(! r1.equals(r2));
        assertTrue(  r1.equals(r1b));
        assertTrue(! r1.equals(r3));
        assertTrue(  r3.equals(r3b));
        assertTrue(! r3.equals(r4));
        assertTrue(! r3.equals(r5));
        assertTrue(! r3.equals(r6));
    }
    
    /**
     * Test the BindingEnvironment machinery
     */
    public void testBindingEnvironment() {
        BindingStack env = new BindingStack();
        env.reset(MAX_VARS);
        
        env.bind(3, n1);
        assertEquals(n1, env.getEnvironment()[3]);
        env.push();
        env.bind(2, n2);
        assertEquals(n2, env.getEnvironment()[2]);
        env.unwind();
        assertEquals(null, env.getEnvironment()[2]);
        assertEquals(n1, env.getEnvironment()[3]);
        env.push();
        env.bind(1, n3);
        assertEquals(null, env.getEnvironment()[2]);
        assertEquals(n1, env.getEnvironment()[3]);
        assertEquals(n3, env.getEnvironment()[1]);
        env.unwind();
        assertEquals(null, env.getEnvironment()[2]);
        assertEquals(n1, env.getEnvironment()[3]);
        assertEquals(null, env.getEnvironment()[1]);
        env.push();
        env.bind(1, n3);
        assertEquals(null, env.getEnvironment()[2]);
        assertEquals(n1, env.getEnvironment()[3]);
        assertEquals(n3, env.getEnvironment()[1]);
        env.commit();
        assertEquals(null, env.getEnvironment()[2]);
        assertEquals(n1, env.getEnvironment()[3]);
        assertEquals(n3, env.getEnvironment()[1]);
        try {
            env.unwind();
            assertTrue("Failed to catch end of stack", false);
        } catch (IndexOutOfBoundsException e) {
        }
    }  
    
    /**
     * Test simple single clause binding
     */
    public void testClauseMaching() {
        BindingStack env = new BindingStack();
        env.reset(MAX_VARS);
        List rules = new ArrayList();
        BasicForwardRuleInfGraph inf = new BasicForwardRuleInfGraph(
                                            new BasicForwardRuleReasoner(rules), rules, null);
        TriplePattern p1 = new TriplePattern(
                                    new Node_RuleVariable("?a", 0),
                                    n1,
                                    new Node_RuleVariable("?b", 1));
        TriplePattern p2 = new TriplePattern(
                                    new Node_RuleVariable("?b", 1),
                                    new Node_RuleVariable("?c", 2),
                                    n2);

        // Should fail with no bindings
        boolean match = FRuleEngine.match(p1, new Triple(n1, n2, n3), env);
        assertTrue(!match);
        assertEquals(null, env.getEnvironment()[0]);
        assertEquals(null, env.getEnvironment()[1]);
        assertEquals(null, env.getEnvironment()[2]);
        
        // Should succeed with two bindings
        match = FRuleEngine.match(p1, new Triple(n2, n1, n3), env);
        assertTrue(match);
        assertEquals(n2, env.getEnvironment()[0]);
        assertEquals(n3, env.getEnvironment()[1]);
        assertEquals(null, env.getEnvironment()[2]);
        
        // should fail but leave prior bindings intact
        match = FRuleEngine.match(p2, new Triple(n1, n2, n2), env);
        assertTrue(!match);
        assertEquals(n2, env.getEnvironment()[0]);
        assertEquals(n3, env.getEnvironment()[1]);
        assertEquals(null, env.getEnvironment()[2]);
        
        // should succeed with full binding set
        match = FRuleEngine.match(p2, new Triple(n3, n1, n2), env);
        assertTrue(match);
        assertEquals(n2, env.getEnvironment()[0]);
        assertEquals(n3, env.getEnvironment()[1]);
        assertEquals(n1, env.getEnvironment()[2]);
    }
      
    /**
     * Minimal rule tester to check basic pattern match
     */
    public void testRuleMatcher() {
        String rules = "[r1: (?a p ?b), (?b q ?c) -> (?a, q, ?c)]" +
                       "[r2: (?a p ?b), (?b p ?c) -> (?a, p, ?c)]" +
                       "[r3: (?a p ?a), (n1 p ?c), (n1, p, ?a) -> (?a, p, ?c)]" +
                       "[r4: (n4 ?p ?a) -> (n4, ?a, ?p)]";
        List ruleList = Rule.parseRules(rules);
        
        InfGraph infgraph = new BasicForwardRuleReasoner(ruleList).bind(Factory.createGraphMem());
        infgraph.add(new Triple(n1, p, n2));
        infgraph.add(new Triple(n2, p, n3));
        infgraph.add(new Triple(n2, q, n3));
        infgraph.add(new Triple(n4, p, n4));
        
        TestUtil.assertIteratorValues(this, infgraph.find(null, null, null),
            new Triple[] {
                new Triple(n1, p, n2),
                new Triple(n2, p, n3),
                new Triple(n2, q, n3),
                new Triple(n4, p, n4),
                new Triple(n1, p, n3),
                new Triple(n1, q, n3),
                new Triple(n4, n4, p),
            });
    }
      
    /**
     * Test derivation machinery
     */
    public void testRuleDerivations() {
        String rules = "[testRule1: (n1 p ?a) -> (n2, p, ?a)]" +
                       "[testRule2: (n1 q ?a) -> (n2, q, ?a)]" +
                       "[testRule3: (n2 p ?a), (n2 q ?a) -> (res p ?a)]";
        List ruleList = Rule.parseRules(rules);
        
        InfGraph infgraph = new BasicForwardRuleReasoner(ruleList).bind(Factory.createGraphMem());
        infgraph.setDerivationLogging(true);
        infgraph.add(new Triple(n1, p, n3));
        infgraph.add(new Triple(n1, q, n4));
        infgraph.add(new Triple(n1, q, n3));

        TestUtil.assertIteratorValues(this, infgraph.find(null, null, null),
            new Triple[] {
                new Triple(n1, p, n3),
                new Triple(n2, p, n3),
                new Triple(n1, q, n4),
                new Triple(n2, q, n4),
                new Triple(n1, q, n3),
                new Triple(n2, q, n3),
                new Triple(res, p, n3)
            });
        
        Iterator derivs = infgraph.getDerivation(new Triple(res, p, n3));
        StringWriter outString = new StringWriter(250);
        PrintWriter out = new PrintWriter(outString);
        while (derivs.hasNext()) {
            Derivation d = (Derivation) derivs.next();
            d.printTrace(out, true);
        }
        out.flush();
        
        String testString = TestUtil.normalizeWhiteSpace("Rule testRule3 concluded (res p n3) <-\n" +
                "    Rule testRule1 concluded (n2 p n3) <-\n" +
                "        Fact (n1 p n3)\r\n" +
                "    Rule testRule2 concluded (n2 q n3) <-\n" +
                "        Fact (n1 q n3)\r\n");
        assertEquals(testString, TestUtil.normalizeWhiteSpace(outString.getBuffer().toString()));

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -