def testLose(self): """ Test the lead/follow functionality """ roomObj = self.createRoom(num=99990) leadCharName = "Leader" parasiteCharName = "Parasite" charList = self.multiCharacterSetUp([leadCharName, parasiteCharName], roomObj) leadCharObj = charList[0].charObj leadGameCmdObj = charList[0].gameCmdObj parasiteCharObj = charList[1].charObj parasiteGameCmdObj = charList[1].gameCmdObj # This should already be tested as part of follow assert not parasiteGameCmdObj.do_follow( leadCharObj.getName()) # always False assert parasiteCharObj.getFollow() is leadCharObj # Begin tests logger.debug("testLose: Lose case1: valid target") assert not leadGameCmdObj.do_lose( parasiteCharObj.getName()) # always False assert not parasiteCharObj.getFollow() is leadCharObj assert not leadGameCmdObj.do_lose("does-not-exist") assert parasiteCharObj.getFollow() is None
def testRoomShop(self): tmpRoomNum = 99999 roomObj = RoomFactory("Shop", tmpRoomNum) # instanciate room object roomObj._catalog = ["Armor/2", "Weapon/2"] charObj = self.getCharObj() charObj.setName("Lucky") charObj.setCoins(10) assert roomObj.isVendor() assert not roomObj.isRepairShop() assert not roomObj.isPawnShop() assert not roomObj.isBank() assert roomObj.getCatalog() != "" assert roomObj.getPriceBonus() == 100 assert roomObj.getCantAffordTxt() != "" assert roomObj.getCantCarryTxt() != "" assert roomObj.getSuccessTxt() != "" assert roomObj.getAbortedTxt() != "" assert roomObj.shopGetInfo() != "" assert roomObj.getTaxRate() >= 0 assert roomObj.getTaxAmount(100) == 0 assert roomObj.adjustPrice(1000) == 1000 obj = self.createObject(num=99999, type="Weapon", name="knife") logger.debug(roomObj.debug()) roomObj.recordTransaction(obj, saveRoomFlag=False) logger.debug(roomObj.debug()) assert roomObj.displayTransactions() != "" assert not roomObj.displayLedger() != "" roomObj._bank = True roomObj.recordTransaction("deposit/5000", saveRoomFlag=False) assert roomObj.displayLedger() != ""
def directMessage(self, data, who, header=None): """ output a message to specific user """ sentCount = 0 logger.debug("broadcast - " + str(data) + " - " + str(who)) if data[-1] != "\n": # Add newline if needed data += "\n" # toDo: this should be a name search, instead of a number from 'who' if self.isNum(who): if not header: header = (self.txtBanner("Private message from " + self.acctObj.getEmail()) + "\n> ") for client in self.getConnectionList(): if client.id == int(who): client.spoolOut(header + data) sentCount += 1 if sentCount: return True header = (self.txtBanner("No valid target for message." + " Sending to yourself") + "\n> ") self.spoolOut(header + data) # send to myself return False
def __init__(self, objId=0): self.objId = objId self._article = "a" self._longdesc = "" self._name = "" self._singledesc = "" self._pluraldesc = "" self._carry = True self._cursed = False self._enchanted = False # typially, enchanting is done by players self._hidden = False self._invisible = False self._magic = False self._permanent = False self._value = 1 self._weight = 1 self._alignmentsAllowed = [] self._classesAllowed = [] self._gendersAllowed = [] self._minLevelAllowed = 0 self._maxLevelAllowed = 100 self._instanceDebug = Object._instanceDebug self._isObject = True if self._instanceDebug: logger.debug("Object init called for " + str(self.getId())) return None
def showRoomNumsForAllChars(self): """ Dump the list of characters and their room number as debug output """ outStr = "--- Characters in the Game: " outStr += ", ".join([ "{0}-->{1}".format(c.getName(), c.getRoom().getId()) for c in self.getGameObj().getCharacterList() ]) logger.debug(outStr)
def testPlayerInventoryCount(self): self.populateInventory(self.testInventory) logger.debug("In " + __class__.__name__ + ": inv = " + str(self.getInventory())) inventoryCount = len(self.getInventory()) self.assertEqual(inventoryCount != 0, True, "Empty Inventory") out = ("Inventory: " + str(self.getInventory) + " - InventoryCount: " + str(inventoryCount)) status = bool(len(self.testInventory) == inventoryCount) self.assertEqual(status, True, out)
def _asyncLoop(self): """ Call the _asyncTasks method of the single game instance. * Thread control and tasks are handled in the game instance. """ if self._debugAsync: logger.debug("{} AsyncThread._asyncMain".format(self)) logger.info("{} Thread started (pid: {})".format(self, os.getpid())) while not self._stopFlag: self.gameObj.asyncTasks() self._lastRunTime = datetime.now() time.sleep(1)
def multiCharacterSetUp(self, nameList=["char1", "char2"], roomObj=None): """ Create X characters and place them in the same room Returns a list of nametuples, one element for each character """ # Create namedtuple and charList for resulting objects CharBlob = namedtuple('CharBlob', ['charObj', 'clientObj', 'gameCmdObj']) charList = [] # Create a roomObj for our characters, if it doesn't already exist. if not roomObj: roomObj = self.createRoom(num=99990) for name in nameList: if name == nameList[0]: # Set up the first character, which is special since the # framework creates it for us. charObj = self.getCharObj() charObj.setName(name) clientObj = charObj.client gameCmdObj = GameCmd(self.getGameCmdObj()) else: # Create the secondary characters clientObj, gameCmdObj = self.createAdditionalClient(name=name) charObj = clientObj.charObj # Store resulting character, client, and gameCmd objects in list # of namedtuples C = CharBlob(charObj, clientObj, gameCmdObj) charList.append(C) # Add the character to the room clientObj.getGameObj().joinRoom(roomObj, charObj) if len(nameList) > 1: logger.debug("multi: Verifying character setup") charNamesInGame = self.getCharNamesInGame( charList[0].clientObj.gameObj) charNamesInRoom = self.getCharNamesInRoom( charList[0].charObj.getRoom()) # logger.debug("multi: CharList={}".format(", ".join(charNamesInGame))) for oneCharName in nameList: # Check that our characters are all currently in the same game assert oneCharName in charNamesInGame, ( "Character {} is not in the game -- Chars:{}".format( oneCharName, charNamesInGame)) # Check that our characters are all currently in the same room assert oneCharName in charNamesInRoom, ( "Character {} is not in the room -- Chars:{}".format( oneCharName, charNamesInRoom)) return (charList)
def testCharacterList(self): testCharName1 = "TestAcctChar2" testCharName2 = "TestAcctChar3" self._acctObj.addCharacterToAccount(testCharName1) assert testCharName1 in self._acctObj.getCharacterList() self._acctObj.addCharacterToAccount(testCharName2) if self._instanceDebug: logger.debug(self._acctObj.showCharacterList()) assert re.search(testCharName2, self._acctObj.showCharacterList()) self._acctObj.removeCharacterFromAccount(testCharName1) assert testCharName1 not in self._acctObj.getCharacterList() assert self._acctObj.getMaxNumOfCharacters() == 5 assert self._acctObj.getCharacterList() == [testCharName2]
def getStatTotals(self, charObj, name="", silent=False): """ reusable method for getting stat totals. Useful for comparing/testing level up/down and death """ statTotal = 0 statStr = "" for stat in charObj.statList: val = getattr(charObj, stat) statTotal += val statStr += stat + "=" + str(val) + " " if not silent: logger.debug("{0:29}".format("getStatTotals " + name + "(" + str(statTotal) + "): ") + str(statStr)) return statTotal
def showList(self, targetStr, startNum=0, endNum=0): """ Display a list of objects. Show wizardAttributes """ ROW_FORMAT = "{0:3}:" fields_to_ignore = ["_article", "_pluraldesc", "_longdesc", "_desc"] long_fields = ["_singledesc", "_shortDesc"] headerList = ["id"] fullList = [] logger.debug( "showList: " + targetStr + " - " + str(startNum) + "-" + str(endNum) ) for itemNum in range(startNum, endNum): obj = self.getItemObj(targetStr, itemNum) if obj is None: continue if hasattr(obj, "_isNew"): continue dataList = [str(itemNum)] dataCount = 1 for att in obj.wizardAttributes: if att in fields_to_ignore: continue data = getattr(obj, att) if len(fullList) == 0: # build format on the fly if isinstance(data, int) or isinstance(data, bool): ROW_FORMAT += " {" + str(dataCount) + ":7.7}" elif att in long_fields: ROW_FORMAT += " {" + str(dataCount) + ":20.20}" else: ROW_FORMAT += " {" + str(dataCount) + ":10.10}" dataCount += 1 # store att names for use as a header headerList.append(str(att)) dataList.append(str(data)) fullList.append(dataList) ROW_FORMAT += "\n" if len(fullList) != 0: print(self.strCyan(ROW_FORMAT.format(*headerList))) for num, dataList in enumerate(fullList): msg = ROW_FORMAT.format(*dataList) if num % 3 == 0: msg = self.strYellow(msg) print(msg)
def yellMsg(self, roomObj, msg): """ shown to your room and rooms in adjoining directions """ received = False if not roomObj: return False roomNumbList = [roomObj.getId()] # Get ajacent directional rooms roomNumbList += list(roomObj.getAllAdjacentRooms()) if self._instanceDebug: logger.debug("yellMsg: ajoining rooms" + str(roomNumbList)) # If any of the rooms are active, display message there. for oneRoom in self.getActiveRoomList(): # foreach active room if oneRoom.getId() in roomNumbList: # if room id is an exit if self.roomMsg(oneRoom, msg): received = True # sent to at least one recipient return received
def promptForInput(self, promptStr, regex="", requirementsTxt=""): """ prompt for string input - return str or empty if none """ for x in range(1, self.getMaxPromptRetries()): # logger.debug("PromptForInput try " + str(x)) self.spoolOut(promptStr) oneStr = "" if self._sendAndReceive(): oneStr = self.getInputStr() else: logger.debug("S&R returned False") if oneStr == "" or not self.isRunning(): return "" elif regex == "" or re.search(regex, oneStr): return oneStr else: self.spoolOut(requirementsTxt) return ""
def enterHelp(client): client.spoolOut("Welcome to the help subsystem") contextMenu = "" while True: prompt = ( "Menu:\n" + contextMenu + "--------------------------------------------\n" + " topics - show the top level list of topics\n" + " exit - quit help and go back to the game\n" + "What would you like help with? : " ) helpIn = client.promptForInput(prompt) if helpIn == "exit" or helpIn == "quit": break elif helpIn == "topics": contextMenu = "" for oneTopic in gameCommands.keys(): logger.debug("topic: " + oneTopic) contextMenu = ( contextMenu + " " + oneTopic + " - " + "info about " + oneTopic + "\n" ) elif helpIn in gameCommands.keys(): contextMenu = "" for oneCommand in gameCommands[helpIn].keys(): contextMenu = ( contextMenu + " " + oneCommand + " - " + gameCommands[helpIn][oneCommand]["shortdesc"] + "\n" ) else: client.spoolOut("Unknown help topic " + helpIn + "\n") return None
def testTravelSouthAndThroughPortal(self): """ Use known test area which has a room to the south that contains a portal back to the start room """ startRoom = 320 southRoom = 319 portalDestination = startRoom gameCmdObj = self.getGameCmdObj() if self.debug: logger.debug(self.getCharObj().debug()) # Remember that all game commands return False so that command loop # continues self.joinRoom(startRoom) assert self.getCharObj().getRoom().getId() == startRoom logger.info("Command: s") assert not gameCmdObj.runcmd("s") assert self.getCharObj().getRoom().getId() == southRoom logger.info("Command: go portal") assert not gameCmdObj.runcmd("go portal") assert self.getCharObj().getRoom().getId() == portalDestination
def testRoomItemSquashing(self): """ Test that identically named items are consolidated when displayed """ # Create a room roomObj = RoomFactory("room", self._testRoomNum) roomObj._shortDesc = "in a test room" roomObj._desc = "in a long test room" # Create a few similar items and add them to room for num in range(1, 4): obj = self.createObject(num=99999, type="Weapon", name="toothpick") roomObj.addToInventory(obj) # Create a few similar items and add them to room for num in range(1, 3): cre = self.createCreature(num=99999, name="bug") roomObj.addToInventory(cre) disp = roomObj.displayItems(self.getCharObj()) logger.debug("disp: " + str(disp)) assert disp == "You see three toothpicks and two bugs\n"
def terminateClientConnection(self): """ terminate the connection and clean up loose ends """ if self._running: self.removeConnectionFromList() self._running = False self.lobbyObj = None if self.charObj: self.gameObj.leaveGame(self.charObj, saveChar=True) self.charObj = None self.gameObj = None self.acctObj = None try: self.socket.sendall(str.encode(common.globals.TERM_STR)) self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() except OSError: if self._debugServer: logger.debug("{} Server term - ".format(self) + "Couldn't close non-existent socket") return None
def createCharacter(self, name=_testCharName, gender=_testCharGender, cname=_testCharClassName, align=_testCharAlignment, client=None): if client is None: logger.debug( "createCharacter: instanciating new client for {}".format( name)) client = self.getClientObj() charObj = character.Character(client=client, acctName=self.getAcctObj().getId()) charObj.setName(name) charObj.setGender(gender) charObj.setClassName(cname) charObj.setAlignment(align) assert charObj.isValid() return charObj
def testRoomVsTarget(self): """ Verify that the target order (i.e. the when interacting with objects) is the same as the order of objects in a room """ # Create a room roomObj = RoomFactory("room", self._testRoomNum) roomObj._shortDesc = "in a test room" roomObj._desc = "in a long test room" # Create a few portals and add them to room for num in range(1, 4): obj = self.createObject(num=99990 + num, type="Portal", name="portal" + str(num)) roomObj.addToInventory(obj) disp = roomObj.displayItems(self.getCharObj()) logger.debug("disp: " + str(disp)) iList = roomObj.getInventory() logger.debug("inv: " + str([str(x) + " " + x.describe() for x in iList])) tList = [ targetSearch(iList, "por #1"), targetSearch(iList, "por #2"), targetSearch(iList, "por #3"), ] logger.debug("tList: " + str([str(x) + " " + x.describe() for x in tList])) assert iList == tList
def testLevelUp(self): charObj = self.createCharacter() charObj.setClassName("fighter") charObj.autoCustomize() charObj.setLevel(1) charObj._expToNextLevel = 1 logger.debug(charObj.debug()) assert not charObj.hasExpToTrain() charObj._expToNextLevel = 0 assert charObj.hasExpToTrain() statTotalPre = self.getStatTotals(charObj, name=("Lvl1")) charObj.levelUp() statTotalLvl2 = self.getStatTotals(charObj, name=("Lvl2")) assert charObj.getLevel() == 2 logger.debug(charObj.debug()) if charObj.getClassName() == "fighter" and charObj.getLevel() == 2: logger.debug("testLevelUp: _doubleUpStatLevels=" + str(charObj._doubleUpStatLevels)) assert statTotalLvl2 >= statTotalPre + 2 charObj._expToNextLevel = 10000 charObj.expBonus(percent=10) assert charObj.getExp() == 9000
def __init__(self, roomNum=1): self._roomNum = int(roomNum) # the room number, not seen by players super().__init__() Storage.__init__(self) Inventory.__init__(self) self._shortDesc = "" # the brief description of a room self._desc = "" # the full description of a room self._notifyDM = False # notify DM if someone enters this room self._safe = False # players/monsters can't attack here self._antiMagic = False # can't use magic spells here self._dark = False # players can't see here self._encounterRate = 100 # average seconds between encounters self._encounterList = [] # list of creature numbers for encounters self._permanentList = [] # perm object instances self._timeOfLastEncounter = getNeverDate() self._timeOfLastAttack = getNeverDate() self._instanceDebug = Room._instanceDebug # Override the inventory class - Set the number of items allowed in self.setInventoryTruncSize(12) # room before the items roll away # These are tmp properties that get reset everytime the room is empty self.initTmpAttributes() # Standard directions - 0=none self.n = 0 self.s = 0 self.e = 0 self.w = 0 self.u = 0 self.d = 0 self.o = 0 if self._instanceDebug: logger.debug("Room init called for " + str(self.getId())) return None
def broadcast(self, data, header=None): """ output a message to all users """ sentCount = 0 logger.debug("broadcast - " + str(data)) if data[-1] != "\n": # Add newline if needed data += "\n" if not header: header = (self.txtBanner("Broadcast message from " + self.acctObj.getEmail()) + "\n> ") for client in self.getConnectionList(): if client.id != self.id: client.spoolOut(header + data) sentCount += 1 if sentCount: return True header = (self.txtBanner("No valid target for message." + " Sending to yourself") + "\n> ") self.spoolOut(header + data) # send to myself return False
def verifyAcctPassword(self, promptStr="Enter Account Password: "******""" Prompt user to verify password, returns True if successful """ if not self.email or self.email == "": msg = "{} verifyAcctPassword failed. email not defined".format(self.client) logger.debug(msg) return False if self.load(["password"], logStr=__class__.__name__): for x in range(1, 4): if self.validatePassword(self.password, promptStr): return True else: self.client.spoolOut( "Password invalid for account " + self.email + " (attempt " + str(x) + " of 3).\n" ) if x == 3: msg = "{} Failed password verification for account {}" logger.warning(msg.format(self.client, self.email)) return False
def displayAndInfo(self, roomObj, loginfo=True): """ test and log a room's description and info """ roomDisplay = roomObj.display(self.getCharObj()) roomInfo = roomObj.getInfo() logger.debug("--- start display ---\n" + roomDisplay) logger.debug("--- end display ---") if loginfo: logger.debug("\n" + roomInfo) assert roomDisplay != "" assert roomInfo != ""
def testSkillsAndStats(self): _levelLoopNumber = 10 charObj = self.createCharacter() charObj._classname = "fighter" charObj._bludgeon = 10 charObj._slash = 20 assert charObj.getSkillPercentage("_bludgeon") == 10 assert charObj.rollToBumpSkillForLevel("_slash", percentChance=100) assert charObj.getSkillPercentage("_slash") == 30 logger.debug("Looping " + str(_levelLoopNumber) + " times - raise and lower level") firstStatCount = 0 # level up and then level down x times for i in range(0, _levelLoopNumber): statTotalPre = self.getStatTotals(charObj, name=("Pre" + str(i))) if not firstStatCount: firstStatCount = statTotalPre charObj.levelUpStats() statTotalPostUp = self.getStatTotals(charObj, name=("PostUp" + str(i))) assert statTotalPostUp > statTotalPre charObj.levelDownStats() statTotalPostDown = self.getStatTotals(charObj, name=("PostDown" + str(i))) assert statTotalPostDown < statTotalPostUp logger.debug("testSkillsAndStats: " + str(statTotalPre) + " --> " + str(statTotalPostUp) + " --> " + str(statTotalPostDown)) logger.debug("testSkillsAndStats: Final after " + str(_levelLoopNumber) + " times gaining and losing levels: " + str(firstStatCount) + " --> " + str(statTotalPostDown)) # after level up and then level down x times, postDown should # generally be lower, but extremely lucky cases may improve stats assert firstStatCount + 5 >= statTotalPostDown charObj._doubleUpStatLevels = [2, 3, 7] charObj.setLevel(1) assert charObj.getStatPoints(luckPoint=False) == 1, "level 1 - 1 pt" charObj.setLevel(2) assert charObj.getStatPoints(luckPoint=False) == 2, "level 2 - 2 pts" charObj.setLevel(3) assert charObj.getStatPoints(luckPoint=False) == 2, "level 3 - 2 pts" charObj.setLevel(4) assert charObj.getStatPoints(luckPoint=False) == 1, "level 4 - 1 pt" charObj.setLevel(5) assert charObj.getStatPoints(luckPoint=False) == 2, "level 5 - 2 pts"
def populateInventory(self, iList): for itemName in iList: iType, iNum = itemName.split("/") if object.isObjectFactoryType(iType.lower()): # Objects logger.debug("In " + __class__.__name__ + ": creating obj " + str(iType) + ":" + str(iNum)) item = object.ObjectFactory(iType, iNum) item.load() self.addToInventory(item) elif iType == "Creature": # Creatures item = creature.Creature(iNum) logger.debug("In " + __class__.__name__ + ": creating cre " + str(iType) + ":" + str(iNum)) item.load() self.addToInventory(item) else: logger.debug("In " + __class__.__name__ + ": unknown " + str(iType) + " in " + str(object.ObjFactoryTypes)) print("Unknown Item type") return None
def __del__(self): if self._instanceDebug: logger.debug("Object destructor called for " + str(self.getId()))
def testCreatureParley(self): creObj = self.createCreature(num=self.testCreatureNumber, name="bug") creObj._parleyAction = "None" creObj._parleyTeleportRooms = [320] creObj._parleyTxt = ["eats your eyeballs"] assert creObj.getParleyAction() == "None" assert creObj.getParleyTeleportRoomNum() == 320 # Test that the none type doesn't say "says" assert creObj.getParleyTxt() == "The bug eats your eyeballs" creObj._parleyTxt = ["bzzt"] # Test that other types say "says" creObj._parleyAction = "Custom" assert creObj.getParleyTxt() == "The bug says, Bzzt" # Test that no message is correct creObj._parleyTxt = [""] assert creObj.getParleyTxt() == "The bug does not respond" # Test that parly sale item works creObj._itemCatalog = ["Weapon/1"] creObj._numOfItemsCarried = [1] creObj.autoPopulateInventory() assert creObj.getParleySaleItem().getType() == "Weapon" charObj = self.getCharObj() charObj.setLevel(1) charObj.charisma = 10 charObj.setCoins(10) for onelvl in range(1, 10): creObj._level = onelvl logger.info("bribe amount for lvl " + str(creObj.getLevel()) + " = " + str(creObj.getDesiredBribe(charObj))) creObj._level = 6 # Test char does not have enough coins assert creObj.getDesiredBribe(charObj) == 3144 assert not creObj.acceptsBribe(charObj, 5000) assert charObj.getCoins() == 10 logger.debug(charObj.client.popOutSpool()) # Test successful bribe, coins are taken charObj.setCoins(10000) assert creObj.acceptsBribe(charObj, 5000) assert charObj.getCoins() == 5000 resultMsg = charObj.client.popOutSpool() logger.debug(resultMsg) # Test unsuccessful bribe, coins are taken charObj.setCoins(10000) assert not creObj.acceptsBribe(charObj, 100) assert charObj.getCoins() == 9900 resultMsg = charObj.client.popOutSpool() logger.debug(resultMsg) assert "3144" not in resultMsg.split(" ") # Test unsuccessful bribe, coins are not taken charObj.setCoins(10000) assert not creObj.acceptsBribe(charObj, 3000) assert charObj.getCoins() == 10000 resultMsg = charObj.client.popOutSpool() logger.debug(resultMsg) assert "3144" in resultMsg.split(" ") # Test unsuccessful bribe, coins taken, but amount is shown charObj.setCoins(10000) assert not creObj.acceptsBribe(charObj, 500) assert charObj.getCoins() == 9500 resultMsg = charObj.client.popOutSpool() logger.debug(resultMsg) assert "3144" in resultMsg.split(" ")
def testTransferInventoryToRoom(self): gameObj = self.getGameObj() charObj = self.getCharObj() charObj.setName("deadGuy") charObj.setHitPoints(10) roomObj = self.createRoom(num=99990) roomObj._inventory = [] charObj.setRoom(roomObj) logger.debug("Testing inventory transfer") self.addFiveItemsToCharacter(charObj) logger.debug("Char Before Trans: " + str(charObj.describeInventory())) logger.debug("Room Before Trans: " + str(roomObj.describeInventory())) assert len(roomObj.getInventory()) == 0 charObj.transferInventoryToRoom( charObj.getRoom(), gameObj.roomMsg, persist=True, verbose=False ) logger.debug("Room After Trans: " + str(roomObj.describeInventory())) logger.debug("Char After Trans: " + str(charObj.describeInventory())) assert len(roomObj.getInventory()) == 5 assert len(charObj.getInventory()) == 0 for obj in roomObj.getInventory(): assert obj.persistsThroughOneRoomLoad() roomObj.removeNonPermanents(removeTmpPermFlag=True) logger.debug("Room PostRemove: " + str(roomObj.describeInventory())) assert len(roomObj.getInventory()) == 5 for obj in roomObj.getInventory(): assert not obj.persistsThroughOneRoomLoad(), ( "Item " + str(obj.getItemId()) + " should no longer persist" )
def testFollow(self): """ Test the lead/follow functionality """ roomObj = self.createRoom(num=99990) roomObj._shortDesc = "room1" roomObj.s = "1" leadCharName = "Leader" parasiteCharName = "Parasite" charList = self.multiCharacterSetUp([leadCharName, parasiteCharName], roomObj) leadCharObj = charList[0].charObj leadGameCmdObj = charList[0].gameCmdObj parasiteCharObj = charList[1].charObj parasiteGameCmdObj = charList[1].gameCmdObj # Set player stats high so that follow always succeeds parasiteCharObj.setClassName("ranger") parasiteCharObj.dexterity = 25 parasiteCharObj.luck = 25 # Begin tests logger.debug("testFollow: Follow case1: invalid target") logger.debug("testFollowBad: FollowSettingPre={}".format( parasiteCharObj.getFollow())) assert not parasiteGameCmdObj.do_follow( "does-not-exist") # always False logger.debug(self.showOutput("testFollowBad", parasiteCharObj)) logger.debug("testFollowBad: FollowSettingPost={}".format( parasiteCharObj.getFollow())) assert parasiteCharObj.getFollow() is None logger.debug("testFollow: Follow case2: invalid self target") logger.debug("testFollowBad: FollowSettingPre={}".format( parasiteCharObj.getFollow())) assert not parasiteGameCmdObj.do_follow( parasiteCharObj.getName()) # always F logger.debug(self.showOutput("testFollowBad", parasiteCharObj)) logger.debug("testFollowBad: FollowSettingPost={}".format( parasiteCharObj.getFollow())) assert parasiteCharObj.getFollow() is None logger.debug("testFollow: Follow case3: valid target") logger.debug("testFollowGood: FollowSettingPre={}".format( parasiteCharObj.getFollow())) assert not parasiteGameCmdObj.do_follow( leadCharObj.getName()) # always False logger.debug(self.showOutput("testFollowGood", parasiteCharObj)) logger.debug("testFollowGood: FollowSettingPost={}".format( parasiteCharObj.getFollow())) assert parasiteCharObj.getFollow() is leadCharObj logger.debug("testFollow: Follow case4: lead moves south") parasiteCharObj._instanceDebug = True self.showRoomNumsForAllChars() leadGameCmdObj._lastinput = "s" assert not leadGameCmdObj.do_s("") # always False logger.debug(self.showOutput("testFollowGood", leadCharObj)) logger.debug(self.showOutput("testFollowGood", parasiteCharObj)) debugInfo = "LeadCharRoom={} - ParasiteCharRoom={}".format( leadCharObj.getRoom().getId(), parasiteCharObj.getRoom().getId()) self.showRoomNumsForAllChars() assert self.charIsInRoom(parasiteCharObj, leadCharObj.getRoom()), debugInfo parasiteCharObj._instanceDebug = False logger.debug("testFollow: Follow case5: unfollow") assert not parasiteGameCmdObj.do_unfollow("") # always False assert parasiteCharObj.getFollow() is None parasitePreRoomObj = parasiteCharObj.getRoom( ) # store pre-move roomObj assert not leadGameCmdObj.do_s("") # always False assert parasitePreRoomObj is parasiteCharObj.getRoom() # hasn't moved logger.debug(self.showOutput("testFollow", parasiteCharObj)) logger.debug("testFollow: Follow case6: follow non player") assert not parasiteGameCmdObj.do_follow("tow") # always False logger.debug(self.showOutput("testFollowBad", parasiteCharObj)) assert parasiteCharObj.getFollow() is None