def test_StringIndexFoundAlwaysTheFirstOne(self): self.assertTrue( self.forInput( types.String("e"), types.String("Nel mezzo del cammin di nostra vita")).expect( types.Integer(2)))
def test_ReturnFalseIfNotFound(self): self.assertTrue( self.forInput( types.String("w"), types.String("Nel mezzo del cammin di nostra vita")).expect( types.Symbol("FALSE")))
def test_StringIndexFound(self): self.assertTrue( self.forInput( types.String("camm"), types.String("Nel mezzo del cammin di nostra vita")).expect( types.Integer(15)))
def test_ErrorOnInvalidInput(self): self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.Integer(2), types.String("blabla")) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.String("blabla"), types.Float(2))
def test_Concatenation(self): theWme = WME(1, OrderedFact([])) self.assertTrue( self.forInput(types.Symbol("ciao"), types.String("mucca"), types.Integer(1), types.Float(1.5), theWme).expect( types.String("ciaomucca11.5" + str(theWme))))
def test_FunctionCallAsArgument(self): if not self.theEnv.modulesManager.currentScope.functions.has("upcase"): self.skipTest("upcase not defined") self.assertTrue( self.forInput( types.FunctionCall("upcase", self.theEnv.modulesManager, [types.String("acqua")]), types.String("acqua")).expect( types.Integer(cmp("acqua".upper(), "acqua"))))
def test_EvalBaseTypes(self): typesMap = { "1": types.Integer(1), "1.5": types.Float(1.5), "symbol": types.Symbol("symbol"), '"string"': types.String("string") } for (theString, theResultCmp) in typesMap.items(): theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, theResultCmp)
def do(self, theEnv, theName=None, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.4.html#Heading248 """ theName = self.resolve(theEnv, theName) if isinstance( theName, (types.FunctionCall, types.Variable)) else theName if theName is None or (isinstance(theName, types.Symbol) and theName.pyEqual("t")): theResource = theEnv.RESOURCES["stdin"] elif not isinstance(theName, types.Symbol): raise InvalidArgTypeError( "Function read expected argument #1 to be of type symbol") else: theResource = theEnv.RESOURCES[theName.evaluate()] try: theString = theResource.readline() # python file.readline() doc: # An empty string is returned only when EOF is encountered immediately # @see http://docs.python.org/release/2.4.4/lib/bltin-file-objects.html if theString == "": return types.Symbol("EOF") return types.String(theString) except EOFError: return types.Symbol("EOF") except IOError: return types.Symbol("*** READ ERROR ***")
def test_InputClassKept(self): theString = "This_Is_a_MiXed_StrIng" theResultString = self.theFunc.do(self.theEnv, types.String(theString)) theResultSymbol = self.theFunc.do(self.theEnv, types.Symbol(theString)) self.assertEqual(theResultString.__class__, types.String) self.assertEqual(theResultSymbol.__class__, types.Symbol)
def test_ErrorOnDefRuleEval(self): theString = """ (defrule r (A B C) => ) """ theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, types.Symbol("FALSE"))
def test_FunctionResultToUpcase(self): theString = types.String("This_Is_a_MiXed_StrIng") theFuncCall = types.FunctionCall(types.Symbol("upcase"), self.theEnv.modulesManager, [theString]) theResult = self.theFunc.do(self.theEnv, theFuncCall) self.assertEqual(theResult.__class__, types.String) self.assertEqual(len(set(string.ascii_lowercase).intersection(set(theResult.evaluate()))), 0) self.assertEqual(theResult, self.theFunc.do(self.theEnv, theString))
def do(self, theEnv, thePath, theName, theMode=None, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.4.html#Heading244 """ thePath = self.resolve(theEnv, thePath) if isinstance( thePath, (types.FunctionCall, types.Variable)) else thePath theName = self.resolve(theEnv, theName) if isinstance( theName, (types.FunctionCall, types.Variable)) else theName theMode = self.resolve(theEnv, theMode) if isinstance(theMode, (types.FunctionCall, types.Variable)) \ else theMode if theMode is not None else types.String("r") if not isinstance(thePath, (types.String, types.Symbol)): raise InvalidArgTypeError( "Function open expected argument #1 to be of type string or symbol" ) # normalize the string to a path. In documentation: # all special chars and \ in the path must be escaped # these means that the path is already a valid path # for python thePath = thePath.evaluate() if isinstance( thePath, types.Symbol) else thePath.evaluate()[1:-1] if not isinstance(theName, types.Symbol): raise InvalidArgTypeError( "Function open expected argument #2 to be of type symbol") # check if a resource with the same logical name is already used assert isinstance(theEnv, FunctionEnv) if theEnv.RESOURCES.has_key(theName.evaluate()): raise InvalidArgValueError( "Illegal logical name used for open function: %s" % theName.evaluate()) if not isinstance(theMode, types.String): raise InvalidArgTypeError( "Function open expected argument #3 to be of type string") # normalize the mode removing quotes if <String> theMode = theMode.evaluate()[1:-1] modeMap = {"r": "rU", "r+": "rU+", "w": "w", "a": "a"} import myclips try: theMode = modeMap[theMode] fileResource = open(thePath, theMode) theEnv.RESOURCES[theName.evaluate()] = fileResource return types.Symbol("TRUE") except KeyError: myclips.logger.error("Invalid mode for Open: %s", theMode) return types.Symbol("FALSE") except IOError, e: myclips.logger.error("IOError in Open: %s", e) return types.Symbol("FALSE")
def do(self, theEnv, theMultifield, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.2.html#Heading224 """ theMultifield = self.semplify(theEnv, theMultifield, list, ("1", "multifield")) return types.String(" ".join([str(x) for x in theMultifield]))
def test_EvalFunctionCall(self): if not self.theEnv.modulesManager.currentScope.functions.has("+"): self.skipTest("+ not defined") theString = """ (+ 1 1) """ theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, types.Integer(2))
def test_BuildRule(self): preRules = len(self.theEnv.network.rules) theString = """ (defrule r (A B C) => ) """ theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, types.Symbol("TRUE")) self.assertEqual(len(self.theEnv.network.rules), preRules + 1)
def test_BuildModule(self): self.assertFalse(self.theEnv.modulesManager.isDefined("A")) theString = """ (defmodule A) """ theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, types.Symbol("TRUE")) self.assertTrue(self.theEnv.modulesManager.isDefined("A"))
def test_ScopeRevertedAfterScopeChangeOnRuleBuilt(self): theOldScope = self.theEnv.modulesManager.currentScope.moduleName theString = """ (defmodule A) """ theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, types.Symbol("TRUE")) self.assertTrue(self.theEnv.modulesManager.isDefined("A")) theString = """ (defrule A::blabla (A B C) => ) """ theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, types.Symbol("TRUE")) self.assertEqual(theOldScope, self.theEnv.modulesManager.currentScope.moduleName)
def do(self, theEnv, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.3.html#Heading231 """ concat = "" for arg in args: concat += str(self.resolve(theEnv, self.semplify(theEnv, arg, (types.BaseParsedType, WME), ("ALL", "lexeme, number or fact-address")))) return types.String(concat)
def test_EvalGlobalVar(self): from myclips.GlobalsManager import GlobalVarDefinition (self.theEnv.modulesManager.currentScope.globalsvars.addDefinition( GlobalVarDefinition( self.theEnv.modulesManager.currentScope.moduleName, "?*a*", types.GlobalAssignment( types.GlobalVariable(types.Symbol("a"), self.theEnv.modulesManager, True), types.Integer(1))))) self.assertTrue( self.forInput(types.String("?*a*")).expect(types.Integer(1)))
def do(self, funcEnv, resourceId, theFormat, *args, **kargs): """ Function handler implementation """ resourceId = self.semplify(funcEnv, resourceId, (types.Symbol), ("1", "symbol")) theFormat = self.resolve( funcEnv, self.semplify(funcEnv, theFormat, (types.String), ("2", "string"))) try: if not resourceId.pyEqual('nil'): resource = funcEnv.RESOURCES[resourceId.evaluate()] else: resource = None except KeyError: raise InvalidArgValueError( "Resource with logical name %s cannot be found" % str(resourceId)) else: returnValueRaw = [] for fragment in args: # revolve variables and function calls returnValueRaw.append( self.resolve(funcEnv, self.semplify(funcEnv, fragment))) # execute replacement of special chars: # theFormat = theFormat.replace("%n", "\n")\ .replace("%r", "\r")\ #.replace("%%", "%") # theFormat is a string returnValueRaw = theFormat % tuple(returnValueRaw) if resource is not None: resource.write(returnValueRaw) return types.String(returnValueRaw)
def do(self, theEnv, theStart, theEnd, theString, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.3.html#Heading233 """ theStart = self.resolve( theEnv, self.semplify(theEnv, theStart, types.Integer, ("1", "integer"))) theEnd = self.resolve( theEnv, self.semplify(theEnv, theEnd, types.Integer, ("2", "integer"))) theString = self.resolve( theEnv, self.semplify(theEnv, theString, types.Lexeme, ("3", "string or symbol"))) return types.String(theString[theStart - 1:theEnd])
def test_ErrorOnNotStringOrSymbolInput(self): self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.Integer(10), types.String("a")) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.Float(1.5), types.String("a")) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, [types.Symbol("bla")], types.String("a")) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.String("a"), types.Integer(10)) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.String("a"), types.Float(1.5)) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.String("a"), [types.Symbol("bla")])
def do(self, theEnv, theString, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.2.html#Heading222 """ theString = self.resolve( theEnv, self.semplify(theEnv, theString, types.String, ("1", "string"))) if theString.strip() == "": return [] # return an empty list # \" -> " theString.replace("\\\"", "\"") import pyparsing as pp constantParser = theEnv.network.getParser().getSParser( "ConstantParser") variableParser = ((pp.Literal("$?") + theEnv.network.getParser().getSParser("VariableSymbolParser"))\ .setParseAction(lambda s,l,t: types.String("".join([str(x) for x in t.asList()])) ) | pp.Literal("$?")\ .setParseAction(lambda s,l,t: types.String("$?") ) | theEnv.network.getParser().getSParser("GlobalVariableParser").copy()\ .setParseAction(lambda s,l,t: types.String("".join([str(x) for x in t.asList()])) ) | (pp.Literal("?") + theEnv.network.getParser().getSParser("VariableSymbolParser"))\ .setParseAction(lambda s,l,t: types.String("".join([str(x) for x in t.asList()])) ) | pp.Literal("?")\ .setParseAction(lambda s,l,t: types.String("?") ) ).setParseAction(lambda s,l,t: t.asList()) trapParser = pp.SkipTo(constantParser | variableParser).setParseAction( lambda s, l, t: types.String(t[0].strip())) wrapperParser = pp.ZeroOrMore(variableParser | constantParser | trapParser).setParseAction( lambda s, l, t: t.asList()) return wrapperParser.parseString(theString, True).asList()
def test_NullStringIfFirstArgIsGreaterThanSecond(self): self.assertTrue( self.forInput(types.Integer(3), types.Integer(1), types.String("ciao")).expect(types.String("")))
def test_SymbolIsNotEqualStringWithSameContent(self): s1 = types.Symbol("FirstSymbol") s2 = types.String("FirstSymbol") self.assertFalse(s1 == s2)
def test_StringLength(self): self.assertTrue( self.forInput(types.String("12345678")).expect(types.Integer(8)))
def test_ZeroLength(self): self.assertTrue( self.forInput(types.String("")).expect(types.Integer(0)))
def test_SubStingOfSymbol(self): self.assertTrue( self.forInput(types.Integer(1), types.Integer(3), types.Symbol("ciao")).expect(types.String("cia")))
def test_SingleCharFromString(self): self.assertTrue( self.forInput(types.Integer(3), types.Integer(3), types.String("ciao")).expect(types.String("a")))
def test_EvalReturnFalseIfVariableIsTheOnlyParsed(self): self.assertTrue( self.forInput(types.String("?a")).expect(types.Symbol("FALSE")))