def add(self, scriptclass, key=None, autostart=True): """ Add a script to this object. Args: scriptclass (Scriptclass, Script or str): Either a class object inheriting from DefaultScript, an instantiated script object or a python path to such a class object. key (str, optional): Identifier for the script (often set in script definition and listings) autostart (bool, optional): Start the script upon adding it. """ if self.obj.__dbclass__.__name__ == "PlayerDB": # we add to a Player, not an Object script = create.create_script(scriptclass, key=key, player=self.obj, autostart=autostart) else: # the normal - adding to an Object script = create.create_script(scriptclass, key=key, obj=self.obj, autostart=autostart) if not script: logger.log_err("Script %s could not be created and/or started." % scriptclass) return False return True
def add(self, scriptclass, key=None, autostart=True): """ Add a script to this object. Args: scriptclass (Scriptclass, Script or str): Either a class object inheriting from DefaultScript, an instantiated script object or a python path to such a class object. key (str, optional): Identifier for the script (often set in script definition and listings) autostart (bool, optional): Start the script upon adding it. """ if self.obj.__dbclass__.__name__ == "AccountDB": # we add to an Account, not an Object script = create.create_script(scriptclass, key=key, account=self.obj, autostart=autostart) else: # the normal - adding to an Object script = create.create_script(scriptclass, key=key, obj=self.obj, autostart=autostart) if not script: logger.log_err("Script %s could not be created and/or started." % scriptclass) return False return True
def add(self, scriptclass, key=None, autostart=True): """ Add a script to this object. scriptclass - either a class object inheriting from Script, an instantiated script object or a python path to such a class object. key - optional identifier for the script (often set in script definition) autostart - start the script upon adding it """ if self.obj.__dbclass__.__name__ == "PlayerDB": # we add to a Player, not an Object script = create.create_script(scriptclass, key=key, player=self.obj, autostart=autostart) else: # the normal - adding to an Object script = create.create_script(scriptclass, key=key, obj=self.obj, autostart=autostart) if not script: logger.log_errmsg( "Script %s could not be created and/or started." % scriptclass) return False return True
def setUp(self): """ Sets up testing environment """ self.player = create.create_player("TestPlayer", email="*****@*****.**", password="******", typeclass=self.player_typeclass) self.player2 = create.create_player("TestPlayer2", email="*****@*****.**", password="******", typeclass=self.player_typeclass) self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True) self.room1.db.desc = "room_desc" settings.DEFAULT_HOME = "#%i" % self.room1.id # we must have a default home self.room2 = create.create_object(self.room_typeclass, key="Room2") self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2) self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1) self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1) self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1) self.char1.permissions.add("Immortals") self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1) self.char1.player = self.player self.player.db._last_puppet = self.char1 self.char2.player = self.player2 self.player2.db._last_puppet = self.char2 self.script = create.create_script(self.script_typeclass, key="Script") self.player.permissions.add("Immortals") # set up a fake session dummysession = ServerSession() dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS) dummysession.sessid = 1 SESSIONS.portal_connect(dummysession.get_sync_data()) # note that this creates a new Session! session = SESSIONS.session_from_sessid(1) # the real session SESSIONS.login(session, self.player, testmode=True) self.session = session
def schedule(callback, repeat=False, **kwargs): """ Call the callback when the game time is up. Args: callback (function): The callback function that will be called. This must be a top-level function since the script will be persistent. repeat (bool, optional): Should the callback be called regularly? day, month, etc (str: int): The time units to call the callback; should match the keys of TIME_UNITS. Returns: script (Script): The created script. Examples: schedule(func, min=5, sec=0) # Will call next hour at :05. schedule(func, hour=2, min=30, sec=0) # Will call the next day at 02:30. Notes: This function will setup a script that will be called when the time corresponds to the game time. If the game is stopped for more than a few seconds, the callback may be called with a slight delay. If `repeat` is set to True, the callback will be called again next time the game time matches the given time. The time is given in units as keyword arguments. """ seconds = real_seconds_until(**kwargs) script = create_script("evennia.contrib.custom_gametime.GametimeScript", key="GametimeScript", desc="A timegame-sensitive script", interval=seconds, start_delay=True, repeats=-1 if repeat else 1) script.db.callback = callback script.db.gametime = kwargs return script
def init_gametime(): """ This is called once, when the server starts for the very first time. """ # create the GameTime script and start it game_time = create_script(GameTime) game_time.start()
def copy_script(self, original_script, new_key=None, new_obj=None, new_locks=None): """ Make an identical copy of the original_script. Args: original_script (Script): The Script to copy. new_key (str, optional): Rename the copy. new_obj (Object, optional): Place copy on different Object. new_locks (str, optional): Give copy different locks from the original. Returns: script_copy (Script): A new Script instance, copied from the original. """ typeclass = original_script.typeclass_path new_key = new_key if new_key is not None else original_script.key new_obj = new_obj if new_obj is not None else original_script.obj new_locks = new_locks if new_locks is not None else original_script.db_lock_storage from evennia.utils import create new_script = create.create_script(typeclass, key=new_key, obj=new_obj, locks=new_locks, autostart=True) return new_script
def setUp(self): """ Sets up testing environment """ self.account = create.create_account("TestAccount", email="*****@*****.**", password="******", typeclass=self.account_typeclass) self.account2 = create.create_account("TestAccount2", email="*****@*****.**", password="******", typeclass=self.account_typeclass) self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True) self.room1.db.desc = "room_desc" settings.DEFAULT_HOME = "#%i" % self.room1.id # we must have a default home # Set up fake prototype module for allowing tests to use named prototypes. settings.PROTOTYPE_MODULES = "evennia.utils.tests.data.prototypes_example" self.room2 = create.create_object(self.room_typeclass, key="Room2") self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2) self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1) self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1) self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1) self.char1.permissions.add("Developer") self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1) self.char1.account = self.account self.account.db._last_puppet = self.char1 self.char2.account = self.account2 self.account2.db._last_puppet = self.char2 self.script = create.create_script(self.script_typeclass, key="Script") self.account.permissions.add("Developer") # set up a fake session dummysession = ServerSession() dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS) dummysession.sessid = 1 SESSIONS.portal_connect(dummysession.get_sync_data()) # note that this creates a new Session! session = SESSIONS.session_from_sessid(1) # the real session SESSIONS.login(session, self.account, testmode=True) self.session = session
def setUp(self): """ Sets up testing environment """ self.player = create.create_player("TestPlayer", email="*****@*****.**", password="******", typeclass=self.player_typeclass) self.player2 = create.create_player("TestPlayer2", email="*****@*****.**", password="******", typeclass=self.player_typeclass) self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True) self.room1.db.desc = "room_desc" settings.DEFAULT_HOME = "#%i" % self.room1.id # we must have a default home self.room2 = create.create_object(self.room_typeclass, key="Room2") self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2) self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1) self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1) self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1) self.char1.permissions.add("Immortals") self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1) self.char1.player = self.player self.player.db._last_puppet = self.char1 self.char2.player = self.player2 self.player2.db._last_puppet = self.char2 self.script = create.create_script(self.script_typeclass, key="Script") self.player.permissions.add("Immortals") # set up a fake session session = ServerSession() session.init_session("telnet", ("localhost", "testmode"), SESSIONS) session.sessid = 1 SESSIONS.portal_connect(session.get_sync_data()) SESSIONS.login(SESSIONS.session_from_sessid(1), self.player, testmode=True) self.session = session
def create(cls, key, **kwargs): """ Provides a passthrough interface to the utils.create_script() function. Args: key (str): Name of the new object. Returns: object (Object): A newly created object of the given typeclass. errors (list): A list of errors in string form, if any. """ errors = [] obj = None kwargs["key"] = key # If no typeclass supplied, use this class kwargs["typeclass"] = kwargs.pop("typeclass", cls) try: obj = create.create_script(**kwargs) except Exception as e: errors.append( "The script '%s' encountered errors and could not be created." % key) logger.log_err(e) return obj, errors
def setUp(self): """ Sets up testing environment """ self.account = create.create_account("TestAccount", email="*****@*****.**", password="******", typeclass=self.account_typeclass) self.account2 = create.create_account("TestAccount2", email="*****@*****.**", password="******", typeclass=self.account_typeclass) self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True) self.room1.db.desc = "room_desc" settings.DEFAULT_HOME = "#%i" % self.room1.id # we must have a default home # Set up fake prototype module for allowing tests to use named prototypes. settings.PROTOTYPE_MODULES = "evennia.utils.tests.data.prototypes_example" self.room2 = create.create_object(self.room_typeclass, key="Room2") self.exit = create.create_object(self.exit_typeclass, key='out', location=self.room1, destination=self.room2) self.obj1 = create.create_object(self.object_typeclass, key="Obj", location=self.room1, home=self.room1) self.obj2 = create.create_object(self.object_typeclass, key="Obj2", location=self.room1, home=self.room1) self.char1 = create.create_object(self.character_typeclass, key="Char", location=self.room1, home=self.room1) self.char1.permissions.add("Developer") self.char2 = create.create_object(self.character_typeclass, key="Char2", location=self.room1, home=self.room1) self.char1.account = self.account self.account.db._last_puppet = self.char1 self.char2.account = self.account2 self.account2.db._last_puppet = self.char2 self.script = create.create_script(self.script_typeclass, key="Script") self.account.permissions.add("Developer") # set up a fake session dummysession = ServerSession() dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS) dummysession.sessid = 1 SESSIONS.portal_connect(dummysession.get_sync_data() ) # note that this creates a new Session! session = SESSIONS.session_from_sessid(1) # the real session SESSIONS.login(session, self.account, testmode=True) self.session = session
def init_magic_advancement(): """ This is called on startup, when you want to enable the magic system. """ try: ScriptDB.objects.get(db_key='Magic Weekly') except ScriptDB.DoesNotExist: magic_system = create.create_script(MagicAdvancementScript) magic_system.start()
def schedule(callback, repeat=False, sec=None, min=None, hour=None, day=None, month=None, year=None): """ Call a callback at a given in-game time. Args: callback (function): The callback function that will be called. Note that the callback must be a module-level function, since the script will be persistent. repeat (bool, optional): Defines if the callback should be called regularly at the specified time. sec (int or None): Number of absolute game seconds at which to run repeat. min (int or None): Number of absolute minutes. hour (int or None): Number of absolute hours. day (int or None): Number of absolute days. month (int or None): Number of absolute months. year (int or None): Number of absolute years. Returns: script (Script): The created Script handling the sceduling. Examples: schedule(func, min=5, sec=0) # Will call 5 minutes past the next (in-game) hour. schedule(func, hour=2, min=30, sec=0) # Will call the next (in-game) day at 02:30. """ seconds = real_seconds_until(sec=sec, min=min, hour=hour, day=day, month=month, year=year) script = create_script( "evennia.utils.gametime.TimeScript", key="TimeScript", desc="A gametime-sensitive script", interval=seconds, start_delay=True, repeats=-1 if repeat else 1, ) script.db.callback = callback script.db.gametime = { "sec": sec, "min": min, "hour": hour, "day": day, "month": month, "year": year, } return script
def test_create_script_w_repeats_equal_1_persisted(self): class TestScriptB1(DefaultScript): def at_script_creation(self): self.key = 'test_script' self.interval = 10 self.repeats = 1 self.persistent = True # script is already stopped (interval=1, start_delay=False) script = create.create_script(TestScriptB1, key='test_script') assert script is None
def test_memplot(self, mock_time, mocked_open, mocked_os, mocked_idmapper): from evennia.utils.create import create_script mocked_idmapper.cache_size.return_value = (9, 5000) mock_time.time = Mock(return_value=6000.0) script = create_script(memplot.Memplot) script.db.starttime = 0.0 mocked_os.popen.read.return_value = 5000.0 script.at_repeat() handle = mocked_open() handle.write.assert_called_with('100.0, 0.001, 0.001, 9\n') script.stop()
def use_on_target(self, target, caller): """ We fetch or create a perfume script on the target character, and set it to have a copy of our scent_desc, which the character will then append to their description. """ try: script = target.scriptdb_set.get(db_key="Appearance") except ScriptDB.DoesNotExist: script = create.create_script(AppearanceScript, obj=target) script.set_scent(self)
def get_script(): """ Returns the ScriptDB instance :return: """ from evennia.scripts.models import ScriptDB try: script = ScriptDB.objects.get(db_key=GAMETIME_SCRIPT_NAME) return script except ScriptDB.DoesNotExist: return create_script(GameTime)
def test_create_script_w_repeats_equal_1_persisted(self): class TestScriptB1(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 1 self.persistent = True # script is already stopped (interval=1, start_delay=False) script = create.create_script(TestScriptB1, key="test_script") assert script is None
def _get_script(self): """Get or create the script.""" if type(self).script: return type(self).script try: script = ScriptDB.objects.get(db_key="generator_script") except ScriptDB.DoesNotExist: script = create_script("contrib.random_string_generator.RandomStringGeneratorScript") type(self).script = script return script
def test_create_script(self): class TestScriptA(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.persistent = False script = create.create_script(TestScriptA, key="test_script") assert script is not None assert script.interval == 10 assert script.key == "test_script" script.stop()
def test_create_script(self): class TestScriptA(DefaultScript): def at_script_creation(self): self.key = 'test_script' self.interval = 10 self.persistent = False script = create.create_script(TestScriptA, key='test_script') assert script is not None assert script.interval == 10 assert script.key == 'test_script' script.stop()
def copy_script(self, original_script, new_key=None, new_obj=None, new_locks=None): """ Make an identical copy of the original_script """ typeclass = original_script.typeclass_path new_key = new_key if new_key is not None else original_script.key new_obj = new_obj if new_obj is not None else original_script.obj new_locks = new_locks if new_locks is not None else original_script.db_lock_storage from evennia.utils import create new_script = create.create_script(typeclass, key=new_key, obj=new_obj, locks=new_locks, autostart=True) return new_script
def _get_script(self): """Get or create the script.""" if type(self).script: return type(self).script try: script = ScriptDB.objects.get(db_key="generator_script") except ScriptDB.DoesNotExist: script = create_script( "contrib.random_string_generator.RandomStringGeneratorScript") type(self).script = script return script
def add(self, scriptclass, key=None, autostart=True): """ Add a script to this object. Args: scriptclass (Scriptclass, Script or str): Either a class object inheriting from DefaultScript, an instantiated script object or a python path to such a class object. key (str, optional): Identifier for the script (often set in script definition and listings) autostart (bool, optional): Start the script upon adding it. """ if self.obj.__dbclass__.__name__ == "AccountDB": # we add to an Account, not an Object script = create.create_script(scriptclass, key=key, account=self.obj, autostart=autostart) else: # the normal - adding to an Object. We wait to autostart so we can differentiate # a failing creation from a script that immediately starts/stops. script = create.create_script(scriptclass, key=key, obj=self.obj, autostart=False) if not script: logger.log_err("Script %s failed to be created/started." % scriptclass) return False if autostart: script.start() if not script.id: # this can happen if the script has repeats=1 or calls stop() in at_repeat. logger.log_info("Script %s started and then immediately stopped; " "it could probably be a normal function." % scriptclass) return True
def set_room_occupied(self, occupant): owner = self.owner zones = GLOBAL_SCRIPTS.zone_ledger.db.zones uid = None if not owner.tags.get('occupied', category='rooms'): owner.tags.add('occupied', category='rooms') if owner.tags.get(category='zone_id'): uid = owner.tags.get(category='zone_id') if uid is not None: # Zone script doesn't exist. Generate a new one. if uid not in zones: zone_script = create_script( typeclass='typeclasses.scripts.Script', key=uid, persistent=True, autostart=True) zone_script.attributes.add('occupants', []) zone_script.attributes.add('rooms', []) zone_script.attributes.add('sentients', []) # Pass the room's zone_type to the zone_script. if owner.tags.get(category='zone_type'): zone_type = owner.tags.get(category='zone_type') zone_script.tags.add(zone_type, category='zone_type') # Spawn sentients. if owner.tags.get('has_spawn'): zone_script.spawn.start_spawner() # Find and add all rooms for this zone. zone_objects_list = search_object_by_tag(key=uid, category='zone_id') zone_rooms = [] for i in zone_objects_list: if i.is_typeclass('rooms.rooms.Room'): zone_rooms.append(i) zone_script.db.rooms = zone_rooms # Add a reference to the zone script to the ledger for later retrieval. zones[uid] = zone_script # Zone script exists. Update it. zone_script = zones.get(uid) if zone_script is not None: zone_occupants = list(zone_script.db.occupants) if occupant not in zone_occupants: zone_script.db.occupants.append(occupant)
def test_create_script_w_repeats_equal_2(self): class TestScriptC(DefaultScript): def at_script_creation(self): self.key = 'test_script' self.interval = 10 self.repeats = 2 self.persistent = False script = create.create_script(TestScriptC, key='test_script') assert script is not None assert script.interval == 10 assert script.repeats == 2 assert script.key == 'test_script' script.stop()
def test_create_script_w_repeats_equal_2(self): class TestScriptC(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 2 self.persistent = False script = create.create_script(TestScriptC, key="test_script") assert script is not None assert script.interval == 10 assert script.repeats == 2 assert script.key == "test_script" script.stop()
def test_create_script_w_repeats_equal_1_and_delayed(self): class TestScriptD(DefaultScript): def at_script_creation(self): self.key = 'test_script' self.interval = 10 self.start_delay = True self.repeats = 1 self.persistent = False script = create.create_script(TestScriptD, key='test_script') assert script is not None assert script.interval == 10 assert script.repeats == 1 assert script.key == 'test_script' script.stop()
def setUp(self): """Create the callback handler.""" super().setUp() self.handler = create_script("evennia.contrib.ingame_python.scripts.EventHandler") # Copy old events if necessary if OLD_EVENTS: self.handler.ndb.events = dict(OLD_EVENTS) # Alter typeclasses self.char1.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventCharacter") self.char2.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventCharacter") self.room1.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventRoom") self.room2.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventRoom") self.exit.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventExit")
def test_create_script_w_repeats_equal_1_and_delayed(self): class TestScriptD(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.start_delay = True self.repeats = 1 self.persistent = False script = create.create_script(TestScriptD, key="test_script") assert script is not None assert script.interval == 10 assert script.repeats == 1 assert script.key == "test_script" script.stop()
def test_attr_creation_func(self): """ Test of assigning attributes during creation """ attrvalue = {'test1': 1, 'test2': 'boo'} # creation-function direct call script = create.create_script(key='script_broken', attributes=[('testname', attrvalue, '')]) self.assertTrue(script) self.assertEqual(script.db.testname, None) # since the category is '' and not None self.assertEqual(script.attributes.get("testname", category=''), attrvalue) script.stop()
def setUp(self): """Create the callback handler.""" super(TestDefaultCallbacks, self).setUp() self.handler = create_script( "evennia.contrib.ingame_python.scripts.EventHandler") # Copy old events if necessary if OLD_EVENTS: self.handler.ndb.events = dict(OLD_EVENTS) # Alter typeclasses self.char1.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventCharacter") self.char2.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventCharacter") self.room1.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventRoom") self.room2.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventRoom") self.exit.swap_typeclass("evennia.contrib.ingame_python.typeclasses.EventExit")
def time_event(obj, event_name, number, parameters): """ Create a time-related event. Args: obj (Object): the object on which sits the event. event_name (str): the event's name. number (int): the number of the event. parameters (str): the parameter of the event. """ seconds, usual, key = get_next_wait(parameters) script = create_script("evennia.contrib.ingame_python.scripts.TimeEventScript", interval=seconds, obj=obj) script.key = key script.desc = "event on {}".format(key) script.db.time_format = parameters script.db.number = number script.ndb.usual = usual
def get_NET(): """Return the storage and NET singleton object. The NET is both a global storage and an object with NET-specific methods. See the `Net` class in `typeclasses/scripts`.. This function only retrieves the net (writes in `NET`) or create it if it doesn't already exist. """ global NET if NET: return NET try: NET = ScriptDB.objects.get(db_key="global_NET") except ScriptDB.DoesNotExist: print("Creating the net...") NET = create_script("typeclasses.scripts.Net") return NET
def time_event(obj, event_name, number, parameters): """ Create a time-related event. Args: obj (Object): the object on which sits the event. event_name (str): the event's name. number (int): the number of the event. parameters (str): the parameter of the event. """ seconds, usual, key = get_next_wait(parameters) script = create_script("evennia.contrib.events.scripts.TimeEventScript", interval=seconds, obj=obj) script.key = key script.desc = "event on {}".format(key) script.db.time_format = parameters script.db.number = number script.ndb.usual = usual
def schedule(callback, repeat=False, sec=None, min=None, hour=None, day=None, month=None, year=None): """ Call a callback at a given in-game time. Args: callback (function): The callback function that will be called. Note that the callback must be a module-level function, since the script will be persistent. repeat (bool, optional): Defines if the callback should be called regularly at the specified time. sec (int or None): Number of absolute game seconds at which to run repeat. min (int or None): Number of absolute minutes. hour (int or None): Number of absolute hours. day (int or None): Number of absolute days. month (int or None): Number of absolute months. year (int or None): Number of absolute years. Returns: script (Script): The created Script handling the sceduling. Examples: schedule(func, min=5, sec=0) # Will call 5 minutes past the next (in-game) hour. schedule(func, hour=2, min=30, sec=0) # Will call the next (in-game) day at 02:30. """ seconds = real_seconds_until(sec=sec, min=min, hour=hour, day=day, month=month, year=year) script = create_script("evennia.utils.gametime.TimeScript", key="TimeScript", desc="A gametime-sensitive script", interval=seconds, start_delay=True, repeats=-1 if repeat else 1) script.db.callback = callback script.db.gametime = { "sec": sec, "min": min, "hour": hour, "day": day, "month": month, "year": year, } return script
def test_characters(self): """test adding and removing characters from a handler""" # the default script already has characters; create our own ch = create.create_script('typeclasses.combat_handler.CombatHandler', key="Script") self.assertEqual(len(ch.db.characters), 0) self.assertEqual(len(ch.db.action_count), 0) self.assertEqual(len(ch.db.turn_actions), 0) # add a character ch.add_character(self.char1) self.assertEqual(len(ch.db.characters), 1) self.assertEqual(len(ch.db.action_count), 1) self.assertEqual(len(ch.db.turn_actions), 1) self.assertEqual(len(ch.db.distances), 0) # add a second character (NPC) ch.add_character(self.obj1) self.assertEqual(len(ch.db.characters), 2) self.assertEqual(len(ch.db.action_count), 2) self.assertEqual(len(ch.db.turn_actions), 2) self.assertEqual(len(ch.db.distances), 1) self.assertIn(self.char1.id, ch.db.characters) self.assertIn(self.char1.id, ch.db.action_count) self.assertIn(self.char1.id, ch.db.turn_actions) self.assertIn(self.obj1.id, ch.db.characters) self.assertIn(self.obj1.id, ch.db.action_count) self.assertIn(self.obj1.id, ch.db.turn_actions) self.assertIn(frozenset((self.char1.id, self.obj1.id)), ch.db.distances) # remove the NPC; this ends the combat ch.remove_character(self.obj1) self.assertFalse(ch.is_valid())
def setup(self): if not self.bot: new_bot = create_script("classes.scripts.TelnetBot", key=self.game_name) self.bot = new_bot self.save()
def test_cmd_rpevent(self, mock_datetime, mock_inform_staff, mock_get_week): from evennia.utils.create import create_script from typeclasses.scripts.event_manager import EventManager from world.dominion.models import Organization, AssetOwner script = create_script(typeclass=EventManager, key="Event Manager") script.post_event = Mock() now = datetime.now() mock_datetime.strptime = datetime.strptime mock_datetime.now = Mock(return_value=now) mock_get_week.return_value = 1 self.setup_cmd(social.CmdCalendar, self.account1) self.call_cmd("/submit", "You must /create a form first.") self.call_cmd("/create test_event", 'Starting project. It will not be saved until you submit it.' ' Does not persist through logout/server reload.|' 'Name: test_event\nMain Host: Testaccount\nPublic: Public\n' 'Description: None\nDate: None\nLocation: None\nLargesse: Small') self.call_cmd("/largesse", 'Level Cost Prestige \n' 'Small 0 0 ' 'Average 100 1000 ' 'Refined 1000 5000 ' 'Grand 10000 20000 ' 'Extravagant 100000 100000 ' 'Legendary 500000 400000') self.call_cmd("/desc test description", 'Desc of event set to:\ntest description') self.call_cmd('/submit', 'Please correct the following errors:\n' 'Date: This field is required.\n' 'Plotroom: You must give either a location or a plot room.\n' 'Name: test_event\nMain Host: Testaccount\nPublic: Public\n' 'Description: test description\nDate: None\nLocation: None\nLargesse: Small') self.call_cmd("/date 26:35 sdf", "Date did not match 'mm/dd/yy hh:mm' format. You entered: 26:35 sdf") self.call_cmd("/date 1/1/01 12:35", "You cannot make an event for the past.") datestr = now.strftime("%x %X") self.call_cmd("/date 12/12/30 12:00", ('Date set to 12/12/30 12:00:00.|' + ('Current time is {} for comparison.|'.format(datestr)) + 'Number of events within 2 hours of that date: 0')) self.call_cmd("/gm testaccount", "Testaccount is now marked as a gm.\n" "Reminder - please only add a GM for an event if it's an actual " "player-run plot. Tagging a social event as a PRP is strictly prohibited. " "If you tagged this as a PRP in error, use gm on them again to remove them.") self.char1.db.currency = -1.0 self.call_cmd("/largesse grand", 'That requires 10000 to buy. You have -1.0.') self.char1.db.currency = 10000 self.call_cmd("/largesse grand", "Largesse level set to grand for 10000.") org = Organization.objects.create(name="test org") org.members.create(player=self.dompc2, rank=10) self.call_cmd("/invite test org", 'Invited test org to attend.') self.call_cmd("/invite testaccount2", "Invited Testaccount2 to attend.") self.call_cmd("/location here", 'Room set to Room.') self.call_cmd("/location room2", 'Room set to Room2.') self.call_cmd("/location", 'Room set to Room.') self.call_cmd('/submit', 'You pay 10000 coins for the event.|' 'New event created: test_event at 12/12/30 12:00:00.') self.assertEqual(self.char1.db.currency, 0) event = RPEvent.objects.get(name="test_event") self.assertTrue(event.gm_event) self.assertEqual(org.events.first(), event) self.assertEqual(self.dompc2.events.first(), event) self.assertEqual(event.location, self.room) script.post_event.assert_called_with(event, self.account, '{wName:{n test_event\n{wMain Host:{n Testaccount\n{wPublic:{n Public\n' '{wDescription:{n test description\n{wDate:{n 2030-12-12 12:00:00\n' '{wLocation:{n Room\n{wLargesse:{n Grand\n{wGMs:{n Testaccount\n' '{wRisk:{n Normal Risk\n{wInvitations:{n Testaccount2\n') mock_inform_staff.assert_called_with('New event created by Testaccount: test_event, ' 'scheduled for 12/12/30 12:00:00.') self.call_cmd("/sponsor test org,200=1", "You do not have permission to spend funds for test org.") org.locks.add("withdraw:rank(10)") org.save() org.members.create(player=self.dompc, rank=1) assets = AssetOwner.objects.create(organization_owner=org) self.call_cmd("/sponsor test org,200=1", 'test org does not have enough social resources.') assets.social = 200 assets.save() self.call_cmd("/sponsor test org,200=1", "test org is now sponsoring test_event for 200 social resources.") self.assertEqual(assets.social, 0) self.call_cmd("/uninvite testaccount2=2", "No event found by that number.") self.call_cmd("/uninvite testaccount2=1", "Removed Testaccount2's invitation.") self.call_cmd("/uninvite testaccount2=1", "They are not invited.") self.call_cmd("/invite testaccount2=1", "Invited Testaccount2 to attend.") self.call_cmd("/invite testaccount2=1", "They are already invited.") self.call_cmd("/uninvite test org=1", "Removed test org's invitation.") self.call_cmd("/uninvite test org=1", "That organization is not invited.") self.call_cmd("/invite test org=1", 'test org has new @informs. Use @informs/org test org/1 to read them.|' 'Invited test org to attend.') self.call_cmd("/invite test org=1", 'That organization is already invited.') self.call_cmd("1", 'Name: test_event\nHosts: Testaccount\nGMs: Testaccount\nOrgs: test org\nLocation: Room\n' 'Event Scale: Grand\nDate: 12/12/30 12:00\nDesc:\ntest description\n' 'Event Page: http://play.arxgame.org/dom/cal/detail/1/')
def save_prototype(**kwargs): """ Create/Store a prototype persistently. Kwargs: prototype_key (str): This is required for any storage. All other kwargs are considered part of the new prototype dict. Returns: prototype (dict or None): The prototype stored using the given kwargs, None if deleting. Raises: prototypes.ValidationError: If prototype does not validate. Note: No edit/spawn locks will be checked here - if this function is called the caller is expected to have valid permissions. """ kwargs = homogenize_prototype(kwargs) def _to_batchtuple(inp, *args): "build tuple suitable for batch-creation" if is_iter(inp): # already a tuple/list, use as-is return inp return (inp, ) + args prototype_key = kwargs.get("prototype_key") if not prototype_key: raise ValidationError("Prototype requires a prototype_key") prototype_key = str(prototype_key).lower() # we can't edit a prototype defined in a module if prototype_key in _MODULE_PROTOTYPES: mod = _MODULE_PROTOTYPE_MODULES.get(prototype_key, "N/A") raise PermissionError("{} is a read-only prototype " "(defined as code in {}).".format(prototype_key, mod)) # make sure meta properties are included with defaults stored_prototype = DbPrototype.objects.filter(db_key=prototype_key) prototype = stored_prototype[0].prototype if stored_prototype else {} kwargs['prototype_desc'] = kwargs.get("prototype_desc", prototype.get("prototype_desc", "")) prototype_locks = kwargs.get( "prototype_locks", prototype.get('prototype_locks', "spawn:all();edit:perm(Admin)")) is_valid, err = validate_lockstring(prototype_locks) if not is_valid: raise ValidationError("Lock error: {}".format(err)) kwargs['prototype_locks'] = prototype_locks prototype_tags = [ _to_batchtuple(tag, _PROTOTYPE_TAG_META_CATEGORY) for tag in make_iter(kwargs.get("prototype_tags", prototype.get('prototype_tags', [])))] kwargs["prototype_tags"] = prototype_tags prototype.update(kwargs) if stored_prototype: # edit existing prototype stored_prototype = stored_prototype[0] stored_prototype.desc = prototype['prototype_desc'] if prototype_tags: stored_prototype.tags.clear(category=_PROTOTYPE_TAG_CATEGORY) stored_prototype.tags.batch_add(*prototype['prototype_tags']) stored_prototype.locks.add(prototype['prototype_locks']) stored_prototype.attributes.add('prototype', prototype) else: # create a new prototype stored_prototype = create_script( DbPrototype, key=prototype_key, desc=prototype['prototype_desc'], persistent=True, locks=prototype_locks, tags=prototype['prototype_tags'], attributes=[("prototype", prototype)]) return stored_prototype.prototype
def setUp(self): self.scr = create_script(DoNothing)
def func(self): """implement method""" caller = self.caller args = self.args if args: if "start" in self.switches: # global script-start mode new_script = create.create_script(args) if new_script: caller.msg("Global script %s was started successfully." % args) else: caller.msg( "Global script %s could not start correctly. See logs." % args) return # test first if this is a script match scripts = ScriptDB.objects.get_all_scripts(key=args) if not scripts: # try to find an object instead. objects = ObjectDB.objects.object_search(args) if objects: scripts = [] for obj in objects: # get all scripts on the object(s) scripts.extend( ScriptDB.objects.get_all_scripts_on_obj(obj)) else: # we want all scripts. scripts = ScriptDB.objects.get_all_scripts() if not scripts: caller.msg("No scripts are running.") return if not scripts: string = "No scripts found with a key '%s', or on an object named '%s'." % ( args, args) caller.msg(string) return if self.switches and self.switches[0] in ('stop', 'del', 'delete', 'kill'): # we want to delete something if len(scripts) == 1: # we have a unique match! if 'kill' in self.switches: string = "Killing script '%s'" % scripts[0].key scripts[0].stop(kill=True) else: string = "Stopping script '%s'." % scripts[0].key scripts[0].stop() # import pdb # DEBUG # pdb.set_trace() # DEBUG ScriptDB.objects.validate() # just to be sure all is synced else: # multiple matches. string = "Multiple script matches. Please refine your search:\n" string += format_script_list(scripts) elif self.switches and self.switches[0] in ("validate", "valid", "val"): # run validation on all found scripts nr_started, nr_stopped = ScriptDB.objects.validate(scripts=scripts) string = "Validated %s scripts. " % ScriptDB.objects.all().count() string += "Started %s and stopped %s scripts." % (nr_started, nr_stopped) else: # No stopping or validation. We just want to view things. string = format_script_list(scripts) caller.msg(string)
def save_prototype(prototype): """ Create/Store a prototype persistently. Args: prototype (dict): The prototype to save. A `prototype_key` key is required. Returns: prototype (dict or None): The prototype stored using the given kwargs, None if deleting. Raises: prototypes.ValidationError: If prototype does not validate. Note: No edit/spawn locks will be checked here - if this function is called the caller is expected to have valid permissions. """ in_prototype = prototype in_prototype = homogenize_prototype(in_prototype) def _to_batchtuple(inp, *args): "build tuple suitable for batch-creation" if is_iter(inp): # already a tuple/list, use as-is return inp return (inp, ) + args prototype_key = in_prototype.get("prototype_key") if not prototype_key: raise ValidationError("Prototype requires a prototype_key") prototype_key = str(prototype_key).lower() # we can't edit a prototype defined in a module if prototype_key in _MODULE_PROTOTYPES: mod = _MODULE_PROTOTYPE_MODULES.get(prototype_key, "N/A") raise PermissionError("{} is a read-only prototype " "(defined as code in {}).".format( prototype_key, mod)) # make sure meta properties are included with defaults in_prototype["prototype_desc"] = in_prototype.get( "prototype_desc", prototype.get("prototype_desc", "")) prototype_locks = in_prototype.get( "prototype_locks", prototype.get("prototype_locks", _PROTOTYPE_FALLBACK_LOCK)) is_valid, err = validate_lockstring(prototype_locks) if not is_valid: raise ValidationError("Lock error: {}".format(err)) in_prototype["prototype_locks"] = prototype_locks prototype_tags = [ _to_batchtuple(tag, _PROTOTYPE_TAG_META_CATEGORY) for tag in make_iter( in_prototype.get("prototype_tags", prototype.get("prototype_tags", []))) ] in_prototype["prototype_tags"] = prototype_tags stored_prototype = DbPrototype.objects.filter(db_key=prototype_key) if stored_prototype: # edit existing prototype stored_prototype = stored_prototype[0] stored_prototype.desc = in_prototype["prototype_desc"] if prototype_tags: stored_prototype.tags.clear(category=PROTOTYPE_TAG_CATEGORY) stored_prototype.tags.batch_add(*in_prototype["prototype_tags"]) stored_prototype.locks.add(in_prototype["prototype_locks"]) stored_prototype.attributes.add("prototype", in_prototype) else: # create a new prototype stored_prototype = create_script( DbPrototype, key=prototype_key, desc=in_prototype["prototype_desc"], persistent=True, locks=prototype_locks, tags=in_prototype["prototype_tags"], attributes=[("prototype", in_prototype)], ) return stored_prototype.prototype
def func(self): """implement method""" caller = self.caller args = self.args if args: if "start" in self.switches: # global script-start mode new_script = create.create_script(args) if new_script: caller.msg("Global script %s was started successfully." % args) else: caller.msg("Global script %s could not start correctly. See logs." % args) return # test first if this is a script match scripts = ScriptDB.objects.get_all_scripts(key=args) if not scripts: # try to find an object instead. objects = ObjectDB.objects.object_search(args) if objects: scripts = [] for obj in objects: # get all scripts on the object(s) scripts.extend(ScriptDB.objects.get_all_scripts_on_obj(obj)) else: # we want all scripts. scripts = ScriptDB.objects.get_all_scripts() if not scripts: caller.msg("No scripts are running.") return if not scripts: string = "No scripts found with a key '%s', or on an object named '%s'." % (args, args) caller.msg(string) return if self.switches and self.switches[0] in ('stop', 'del', 'delete', 'kill'): # we want to delete something if len(scripts) == 1: # we have a unique match! if 'kill' in self.switches: string = "Killing script '%s'" % scripts[0].key scripts[0].stop(kill=True) else: string = "Stopping script '%s'." % scripts[0].key scripts[0].stop() # import pdb # DEBUG # pdb.set_trace() # DEBUG ScriptDB.objects.validate() # just to be sure all is synced else: # multiple matches. string = "Multiple script matches. Please refine your search:\n" string += format_script_list(scripts) elif self.switches and self.switches[0] in ("validate", "valid", "val"): # run validation on all found scripts nr_started, nr_stopped = ScriptDB.objects.validate(scripts=scripts) string = "Validated %s scripts. " % ScriptDB.objects.all().count() string += "Started %s and stopped %s scripts." % (nr_started, nr_stopped) else: # No stopping or validation. We just want to view things. string = format_script_list(scripts) caller.msg(string)
def func(self): caller = self.caller create.create_script("world.scripts.heartbeat.Heartbeat", report_to="#1", interval="10", persistent="true")