def format(world, raw_data):
    """Deserialize a player character saved in ShinyFormat and adds it to 
    the world.
    
    raw_data - the data to be deserialized into a player object.
    world - The World instance
    """
    pc = json.loads(_match_shiny_tag('Player', raw_data))
    items = json.loads(_match_shiny_tag('Inv Items', raw_data))
    # Build the area from the assembled dictionary data
    try:
        new_pc = Player(('foo', 'bar'))
        new_pc.playerize(pc)
        new_pc.save()
        # Inventory time!
        containers = {}  # old_container_dbid : [new_containee1, ...]
        old_new = {}  # old dbid's mapped to their new ones

        for item in items:
            my_container = item[0].get('container')
            old_dbid = item[0]['dbid']
            del item[0]['dbid']
            if item[0].get('owner'):
                item[0]['owner'] = new_pc.dbid
            else:
                del item[0]['container']
            i = GameItem(item[0])
            i.save()
            load_item_types(i, item[1])
            old_new[old_dbid] = i.dbid
            if my_container:
                if containers.get(my_container):
                    containers[my_container].append(i)
                else:
                    containers[my_container] = [i]

        for old_container_dbid, containees_list in containers.items():
            for containee in containees_list:
                containee.container = old_new.get(old_container_dbid)
                containee.save()

    except Exception as e:
        # if anything went wrong, make sure we destroy any leftover character
        # data. This way, we won't run into problems if they try to import it
        # again, and we won't leave orphaned or erroneous data in the db.
        world.log.error(traceback.format_exc())
        try:
            new_pc.destruct()
        except:
            # if something goes wrong destroying the pc, it probably means we
            # didn't get far enough to have anything to destroy. Just ignore any
            # errors.
            pass

        raise SportError('There was a horrible error on import! '
                         'Aborting! Check logfile for details.')

    return 'Character "%s" has been successfully imported.' % new_pc.fancy_name(
    )
示例#2
0
 def setUp(self):
     ShinyTestCase.setUp(self)
     # add a builder
     from shinymud.data import config
     from shinymud.models.player import Player
     from shinymud.models.area import Area
     from shinymud.commands.build_commands import build_list
     from shinymud.modes.build_mode import BuildMode
     self.bob = Player(('bob', 'bar'))
     self.bob.mode = None
     self.bob.playerize({'name':'bob'})
     self.world.player_add(self.bob)
     self.bob.mode = BuildMode(self.bob)
     self.bob.permissions = self.bob.permissions | config.BUILDER
示例#3
0
    def test_set_command(self):
        from shinymud.models.area import Area
        from shinymud.data import config
        from shinymud.models.player import Player
        from shinymud.commands.commands import Set
        bob = Player(('bob', 'bar'))
        bob.mode = None
        bob.playerize({'name': 'bob', 'password': '******'})

        # Test setting e-mail
        Set(bob, 'email [email protected]', 'set').run()
        self.assertEqual('*****@*****.**', bob.email)

        # Test setting title
        Set(bob, 'title is the best EVAR', 'set').run()
        self.assertEqual('is the best EVAR', bob.title)

        # Try to set goto_appear and goto_disappear (both should fail
        # since this player shouldn't have permissions)
        Set(bob, 'goto_appear Bob pops in from nowhere.', 'set').run()
        eresult = 'You don\'t have the permissions to set that.'
        self.assertTrue(eresult in bob.outq)
        bob.outq = []
        Set(bob, 'goto_disappear foo', 'set').run()
        self.assertTrue(eresult in bob.outq)

        bob.permissions = bob.permissions | config.BUILDER

        # Try to set goto_appear and goto_disappear (both should now
        # succeed now that the player has adequate permissions)
        Set(bob, 'goto_appear Bob pops in from nowhere.', 'set').run()
        self.assertEqual('Bob pops in from nowhere.', bob.goto_appear)
        bob.outq = []
        Set(bob, 'goto_disappear foo', 'set').run()
        self.assertEqual('foo', bob.goto_disappear)
def format(world, raw_data):
    """Deserialize a player character saved in ShinyFormat and adds it to 
    the world.
    
    raw_data - the data to be deserialized into a player object.
    world - The World instance
    """
    pc = json.loads(_match_shiny_tag('Player', raw_data))
    items = json.loads(_match_shiny_tag('Inv Items', raw_data))
    # Build the area from the assembled dictionary data
    try:
        new_pc = Player(('foo', 'bar'))
        new_pc.playerize(pc)
        new_pc.save()
        # Inventory time!
        containers = {} # old_container_dbid : [new_containee1, ...]
        old_new = {} # old dbid's mapped to their new ones
        
        for item in items:
            my_container = item[0].get('container')
            old_dbid = item[0]['dbid']
            del item[0]['dbid']
            if item[0].get('owner'):
                item[0]['owner'] = new_pc.dbid
            else:
                del item[0]['container']
            i = GameItem(item[0])
            i.save()
            load_item_types(i, item[1])
            old_new[old_dbid] = i.dbid
            if my_container:
                if containers.get(my_container):
                    containers[my_container].append(i)
                else:
                    containers[my_container] = [i]
        
        for old_container_dbid, containees_list in containers.items():
            for containee in containees_list:
                containee.container = old_new.get(old_container_dbid)
                containee.save()
            
    except Exception as e:
        # if anything went wrong, make sure we destroy any leftover character
        # data. This way, we won't run into problems if they try to import it
        # again, and we won't leave orphaned or erroneous data in the db.
        world.log.error(traceback.format_exc())
        try:
            new_pc.destruct()
        except:
            # if something goes wrong destroying the pc, it probably means we
            # didn't get far enough to have anything to destroy. Just ignore any
            # errors.
            pass
        
        raise SportError('There was a horrible error on import! '
                         'Aborting! Check logfile for details.')
    
    return 'Character "%s" has been successfully imported.' % new_pc.fancy_name()
示例#5
0
    def run(self):
        """Start the connection-handler thread running.
        This thread will accept connections, create a Player object for the
        player logging in, and then add that Player object to the world.
        """

        self.listener.listen(5)
        self.world.log.debug("Listener started")
        while 1:
            try:
                connection = WebsocketConnection(self.listener.accept(),
                                                 self.world.log, self.host,
                                                 self.port)
            except Exception as e:
                self.world.log.debug(str(e))
            else:
                new_player = Player(connection)
                self.world.log.info("Websocket: Client logging in from: %s" %
                                    str(connection.addr))
                # new_player.conn.setblocking(0)
                # The player_add function in the world requires access to the player_list,
                # which the main thread edits quite a bit -- that's why we need a lock
                # before we add a player
                self.world.player_list_lock.acquire()
                self.world.player_add(new_player)
                self.world.player_list_lock.release()
示例#6
0
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name': 'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | config.BUILDER

        self.area = Area.create({'name': 'foo'})
示例#7
0
 def test_set_command(self):
     from shinymud.models.area import Area
     from shinymud.data import config
     from shinymud.models.player import Player
     from shinymud.commands.commands import Set
     bob = Player(('bob', 'bar'))
     bob.mode = None
     bob.playerize({'name':'bob', 'password':'******'})
     
     # Test setting e-mail
     Set(bob, 'email [email protected]', 'set').run()
     self.assertEqual('*****@*****.**', bob.email)
     
     # Test setting title
     Set(bob, 'title is the best EVAR', 'set').run()
     self.assertEqual('is the best EVAR', bob.title)
     
     # Try to set goto_appear and goto_disappear (both should fail
     # since this player shouldn't have permissions)
     Set(bob, 'goto_appear Bob pops in from nowhere.', 'set').run()
     eresult = 'You don\'t have the permissions to set that.'
     self.assertTrue(eresult in bob.outq)
     bob.outq = []
     Set(bob, 'goto_disappear foo', 'set').run()
     self.assertTrue(eresult in bob.outq)
     
     bob.permissions = bob.permissions | config.BUILDER
     
     # Try to set goto_appear and goto_disappear (both should now
     # succeed now that the player has adequate permissions)
     Set(bob, 'goto_appear Bob pops in from nowhere.', 'set').run()
     self.assertEqual('Bob pops in from nowhere.', bob.goto_appear)
     bob.outq = []
     Set(bob, 'goto_disappear foo', 'set').run()
     self.assertEqual('foo', bob.goto_disappear)
示例#8
0
    def test_goto_command(self):
        from shinymud.models.area import Area
        from shinymud.data import config
        from shinymud.models.player import Player
        from shinymud.commands.commands import Goto
        blarg_area = Area.create({'name': 'blarg'})
        foo_area = Area.create({'name': 'foo'})
        blarg_room = blarg_area.new_room()
        foo_room = foo_area.new_room()
        bob = Player(('bob', 'bar'))
        bob.mode = None
        bob.playerize({'name': 'bob', 'password': '******'})
        self.world.player_add(bob)
        bob.permissions = bob.permissions | config.BUILDER
        generic_fail = 'Type "help goto" for help with this command.'

        # We should fail if we only specify a room number when we aren't in
        # an area
        Goto(bob, '%s' % foo_room.id, 'goto').run()
        self.assertEqual(bob.location, None)
        bob.world.log.debug(bob.outq)
        self.assertTrue(generic_fail in bob.outq)

        # We should fail if we try to go to a room in an area that doesn't
        # exist
        message = 'Area "food" doesn\'t exist.'
        Goto(bob, '1 food', 'goto').run()
        self.assertEqual(bob.location, None)
        bob.world.log.debug(bob.outq)
        self.assertTrue(message in bob.outq)

        # We should fail if we try to go to a room that doesn't exist (in an
        # area that does)
        message = 'Room "4005" doesn\'t exist in area blarg.'
        Goto(bob, '4005 blarg', 'goto').run()
        self.assertEqual(bob.location, None)
        bob.world.log.debug(bob.outq)
        self.assertTrue(message in bob.outq)

        # We should succeed in going to a room and area that exists
        Goto(bob, '%s %s' % (foo_room.id, foo_room.area.name), 'goto').run()
        self.assertEqual(bob.location, foo_room)

        Goto(bob, '%s %s' % (blarg_room.id, blarg_room.area.name),
             'goto').run()
        self.assertEqual(bob.location, blarg_room)

        blarg_r2 = blarg_area.new_room()
        Goto(bob, '%s' % (blarg_r2.id), 'goto').run()
        self.assertEqual(bob.location, blarg_r2)

        # We should get a help message if there is only white space given
        bob.outq = []
        Goto(bob, '   ', 'goto').run()
        fail = 'Type "help goto" for help with this command.'
        self.assertTrue(fail in bob.outq)
示例#9
0
class TestBuildCommands(ShinyTestCase):
    def setUp(self):
        ShinyTestCase.setUp(self)
        # add a builder
        from shinymud.data import config
        from shinymud.models.player import Player
        from shinymud.models.area import Area
        from shinymud.commands.build_commands import build_list
        from shinymud.modes.build_mode import BuildMode
        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name':'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | config.BUILDER
    
    def _clean_test_file(self, path):
        try:
            os.remove(path)
        except Exception, e:
            self.world.log.debug('Error removing test file:' + str(e))
示例#10
0
文件: main.py 项目: semtle/ShinyMUD
def create_god(world):
    """Create a god character and save it to this MUD's db."""
    from shinymud.models.player import Player

    save = {'permissions': GOD | PLAYER}
    player = Player(('foo', 'bar'))

    save['name'] = ''
    print "Please choose a name for your character. It should contain \n" +\
          "alphanumeric characters (letters and numbers) ONLY."
    while not save['name']:
        playername = (raw_input("Name: ")).strip()
        if not playername.isalpha():
            print "That is not a valid name. Please choose another."
        else:
            row = player.world.db.select(
                'password,dbid FROM player WHERE name=?', [playername])
            if row:
                print "A player with that name already exists. Please choose Another."
            else:
                print "You're sure you want your name to be '%s'?" % playername
                choice = (raw_input("Yes/No: ")).strip()
                if choice.lower().startswith('y'):
                    save['name'] = playername
                else:
                    print "Ok, we'll start over. Which name do you REALLY want?"

    save['password'] = ''
    while not save['password']:
        passwd1 = (raw_input(CLEAR + "Choose a password: "******"Re-enter password to confirm: " +
                             CONCEAL)).strip()
        if passwd1 == passwd2:
            save['password'] = hashlib.sha1(passwd1).hexdigest()
            print CLEAR
        else:
            print CLEAR + "Your passwords did not match. Please try again."

    save['gender'] = ''
    print "What gender shall your character be?"
    while not save['gender']:
        print "Choose from: neutral, female, or male."
        gender = (raw_input('Gender: ')).strip()
        if len(gender) and gender[0].lower() in ['m', 'f', 'n']:
            save['gender'] = {
                'm': 'male',
                'f': 'female',
                'n': 'neutral'
            }[gender[0].lower()]
        else:
            print "That's not a valid gender."

    player.playerize(save)
    player.save()
    print 'Your character, %s, has been created.' % player.fancy_name()
示例#11
0
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.npc import Npc
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.PERMS = config.PERMS

        #"bob" is created so we can tell build mode functions which player called them.
        #We probably don't need bob since this functionality is only important when permissions
        #are concerned in build commands. We'll create and pass him in anyways for now.
        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name': 'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | self.PERMS['builder']

        self.area = Area.create({'name': 'foo'})
示例#12
0
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.npc import Npc
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.PERMS = config.PERMS

        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name': 'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | self.PERMS['builder']

        self.area = Area.create({'name': 'foo'})
        self.room = self.area.new_room()

        self.area2 = Area.create({'name': 'SimCity'})
        self.area2_script = self.area2.new_script()
示例#13
0
 def test_goto_command(self):
     from shinymud.models.area import Area
     from shinymud.data import config
     from shinymud.models.player import Player
     from shinymud.commands.commands import Goto
     blarg_area = Area.create({'name':'blarg'})
     foo_area = Area.create({'name':'foo'})
     blarg_room = blarg_area.new_room()
     foo_room = foo_area.new_room()
     bob = Player(('bob', 'bar'))
     bob.mode = None
     bob.playerize({'name':'bob', 'password':'******'})
     self.world.player_add(bob)
     bob.permissions = bob.permissions | config.BUILDER
     generic_fail = 'Type "help goto" for help with this command.'
     
     # We should fail if we only specify a room number when we aren't in
     # an area 
     Goto(bob, '%s' % foo_room.id, 'goto').run()
     self.assertEqual(bob.location, None)
     bob.world.log.debug(bob.outq)
     self.assertTrue(generic_fail in bob.outq)
     
     # We should fail if we try to go to a room in an area that doesn't 
     # exist
     message = 'Area "food" doesn\'t exist.'
     Goto(bob, '1 food', 'goto').run()
     self.assertEqual(bob.location, None)
     bob.world.log.debug(bob.outq)
     self.assertTrue(message in bob.outq)
     
     # We should fail if we try to go to a room that doesn't exist (in an
     # area that does)
     message = 'Room "4005" doesn\'t exist in area blarg.'
     Goto(bob, '4005 blarg', 'goto').run()
     self.assertEqual(bob.location, None)
     bob.world.log.debug(bob.outq)
     self.assertTrue(message in bob.outq)
     
     # We should succeed in going to a room and area that exists
     Goto(bob, '%s %s' % (foo_room.id, foo_room.area.name), 'goto').run()
     self.assertEqual(bob.location, foo_room)
     
     Goto(bob, '%s %s' % (blarg_room.id, blarg_room.area.name), 'goto').run()
     self.assertEqual(bob.location, blarg_room)
     
     blarg_r2 = blarg_area.new_room()
     Goto(bob, '%s' % (blarg_r2.id), 'goto').run()
     self.assertEqual(bob.location, blarg_r2)
     
     # We should get a help message if there is only white space given
     bob.outq = []
     Goto(bob, '   ', 'goto').run()
     fail = 'Type "help goto" for help with this command.'
     self.assertTrue(fail in bob.outq)
示例#14
0
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.bob = Player(("bob", "bar"))
        self.bob.mode = None
        self.bob.playerize({"name": "bob"})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | config.BUILDER

        self.area = Area.create({"name": "foo"})
示例#15
0
文件: main.py 项目: ei-grad/ShinyMUD
def create_god(world):
    """Create a god character and save it to this MUD's db."""
    from shinymud.models.player import Player
    
    save = {'permissions': GOD | PLAYER}
    player = Player(('foo', 'bar'))
    
    save['name'] = ''
    print "Please choose a name for your character. It should contain \n" +\
          "alphanumeric characters (letters and numbers) ONLY."
    while not save['name']:
        playername = (raw_input("Name: ")).strip()
        if not playername.isalpha():
            print "That is not a valid name. Please choose another."
        else:
            row = player.world.db.select('password,dbid FROM player WHERE name=?', [playername])
            if row:
                print "A player with that name already exists. Please choose Another."
            else:
                print "You're sure you want your name to be '%s'?" % playername
                choice = (raw_input("Yes/No: ")).strip()
                if choice.lower().startswith('y'):
                    save['name'] = playername
                else:
                    print "Ok, we'll start over. Which name do you REALLY want?"
    
    save['password'] = ''
    while not save['password']:
        passwd1 = (raw_input(CLEAR + "Choose a password: "******"Re-enter password to confirm: " + CONCEAL)).strip()
        if passwd1 == passwd2:
            save['password'] = hashlib.sha1(passwd1).hexdigest()
            print CLEAR
        else:
            print CLEAR + "Your passwords did not match. Please try again."
    
    save['gender'] = ''
    print "What gender shall your character be?"
    while not save['gender']:
        print "Choose from: neutral, female, or male."
        gender = (raw_input('Gender: ')).strip()
        if len(gender) and gender[0].lower() in ['m', 'f', 'n']:
            save['gender'] = {'m':'male', 'f':'female', 'n':'neutral'}[gender[0].lower()]
        else:
            print "That's not a valid gender."
    
    player.playerize(save)
    player.save()
    print 'Your character, %s, has been created.' % player.fancy_name()
示例#16
0
 def setUp(self):
     ShinyTestCase.setUp(self)
     from shinymud.models.player import Player
     from shinymud.models.npc import Npc
     from shinymud.models.area import Area
     from shinymud.models.room import Room
     from shinymud.modes.build_mode import BuildMode
     from shinymud.data import config
     
     self.PERMS = config.PERMS
     
     #"bob" is created so we can tell build mode functions which player called them.
     #We probably don't need bob since this functionality is only important when permissions
     #are concerned in build commands. We'll create and pass him in anyways for now.
     self.bob = Player(('bob', 'bar'))
     self.bob.mode = None
     self.bob.playerize({'name':'bob'})
     self.world.player_add(self.bob)
     self.bob.mode = BuildMode(self.bob)
     self.bob.permissions = self.bob.permissions | self.PERMS['builder']
     
     self.area = Area.create({'name': 'foo'})
示例#17
0
 def setUp(self):
     ShinyTestCase.setUp(self)
     from shinymud.models.player import Player
     from shinymud.models.npc import Npc
     from shinymud.models.area import Area
     from shinymud.models.room import Room
     from shinymud.modes.build_mode import BuildMode
     from shinymud.data import config
     
     self.PERMS = config.PERMS
     
     self.bob = Player(('bob', 'bar'))
     self.bob.mode = None
     self.bob.playerize({'name':'bob'})
     self.world.player_add(self.bob)
     self.bob.mode = BuildMode(self.bob)
     self.bob.permissions = self.bob.permissions | self.PERMS['builder']
     
     self.area = Area.create({'name': 'foo'})
     self.room = self.area.new_room()
     
     self.area2 = Area.create({'name': 'SimCity'})
     self.area2_script = self.area2.new_script()
示例#18
0
    def test_chat_command(self):
        from shinymud.models.area import Area
        from shinymud.data import config
        from shinymud.models.player import Player
        from shinymud.commands.commands import Chat

        bob = Player(('bob', 'bar'))
        alice = Player(('alice', 'bar'))
        sam = Player(('sam', 'bar'))
        bob.mode = None
        bob.playerize({'name':'bob', 'password':'******'})
        bob.outq = []
        sam.mode = None
        sam.playerize({'name':'sam', 'password':'******'})
        sam.outq = []
        self.world.player_add(bob)
        self.world.player_add(sam)
        self.world.player_add(alice)
        
        Chat(bob, 'lol, hey guys!', 'chat').run()
        chat = config.chat_color + 'Bob chats, "lol, hey guys!"' + config.clear_fcolor
        self.assertTrue(chat in sam.outq)
        self.assertTrue(chat in bob.outq)
        self.assertFalse(chat in alice.outq)
        
        sam.channels['chat'] = False
        print sam.channels
        print bob.channels
        sam.outq = []
        bob.outq = []
        alice.outq = []
        
        Chat(bob, 'lol, hey guys!', 'chat').run()
        print sam.channels
        print sam.outq
        print bob.channels
        print bob.outq
        self.assertFalse(chat in sam.outq)
        self.assertTrue(chat in bob.outq)
        self.assertFalse(chat in alice.outq)
示例#19
0
class TestNpc(ShinyTestCase):
    
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.npc import Npc
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config
        
        self.PERMS = config.PERMS
        
        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name':'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | self.PERMS['builder']
        
        self.area = Area.create({'name': 'foo'})
        self.room = self.area.new_room()
        
        self.area2 = Area.create({'name': 'SimCity'})
        self.area2_script = self.area2.new_script()
    
    def tearDown(self):
        del self.area
        del self.area2
        del self.bob
        
    
    def test_existance(self):
        """Test if an NPC can exist within an area properly (unspawned)"""
        self.npc = self.area.new_npc()
        self.npc.characterize({'name': 'bobert'})
        self.assertTrue(self.npc in self.area.npcs.values())
    
    def test_build_add_remove_events(self):
        npc = self.area.new_npc()
        fail_message = 'Type "help events" for help with this command.'
        message = npc.build_add_event('', self.bob)
        self.assertEqual(message, fail_message)
        #test for non-existant scripts
        message = npc.build_add_event('pc_enter call script 1', self.bob)
        self.assertEqual(message, "Script 1 doesn't exist.")
        message = npc.build_add_event("hears 'spam' call script 0", self.bob)
        self.assertEqual(message, "Script 0 doesn't exist.")
        message = npc.build_add_event("hears 'spam' call script 602", self.bob)
        self.assertEqual(message, "Script 602 doesn't exist.")
        
        script = self.area.new_script()
        #Test basic add
        message = npc.build_add_event('pc_enter call script 1', self.bob)
        self.assertEqual(message, 'Event added.' )
        #Test invalid areas
        message = npc.build_add_event('pc_enter call script 1 from area AreaDontExist', self.bob)
        self.assertEqual(message, 'Area "AreaDontExist" doesn\'t exist.')
        message = npc.build_add_event('pc_enter call script 1 from area AreaDontExist 100', self.bob)
        self.assertEqual(message, 'Area "AreaDontExist" doesn\'t exist.')
        #Test invalid probabilities.
        message = npc.build_add_event('pc_enter call script 1 0', self.bob)
        self.assertEqual(message, 'Probability value must be between 1 and 100.')
        message = npc.build_add_event('pc_enter call script 1 101', self.bob)
        self.assertEqual(message, 'Probability value must be between 1 and 100.')
        message = npc.build_add_event('pc_enter call script 1 9999', self.bob)
        self.assertEqual(message, 'Probability value must be between 1 and 100.')
        #Test different froms of valid adds.
        message = npc.build_add_event('pc_enter call script 1 50', self.bob)
        self.assertEqual(message, 'Event added.')
        message = npc.build_add_event('pc_enter call script 1 from area SimCity', self.bob)
        self.assertEqual(message, 'Event added.')
        message = npc.build_add_event('pc_enter call script 1 from area SimCity 75', self.bob)
        self.assertEqual(message, 'Event added.')
        message = npc.build_add_event('pc_enter call 1 from SimCity 50', self.bob)
        self.assertEqual(message, 'Event added.')
        #Test for trigger 'hears'
        message = npc.build_add_event("hears 'food' call script 1", self.bob)
        self.assertEqual(message, 'Event added.' )
        #Test for trigger 'emoted'
        message = npc.build_add_event("emoted 'slap' call script 1", self.bob)
        self.assertEqual(message, 'Event added.' )
          #Technically invalid, but will be left to user responsibility for now. 
          #(it shouldn't ever cause a crash)
        message = npc.build_add_event("emoted 'emotedontexist' call script 1", self.bob)
        self.assertEqual(message, 'Event added.' )
        #Test for new items
        self.area.new_item()
        message = npc.build_add_event("given_item 'item 1' call script 1", self.bob)
        self.assertEqual(message, 'Event added.' )
          #Technically invalid, but will be left to user responsibility for now. 
          #(it shouldn't ever cause a crash)
        message = npc.build_add_event("given_item 'item 5' call script 1", self.bob)
        self.assertEqual(message, 'Event added.' )
        
        #we should now have 5 successfully added events in pc_enter
        self.assertEqual(len(npc.events['pc_enter']), 5)
        message = npc.build_remove_event("pc_enter -1", self.bob)
        self.assertEqual(message, 'Try: "remove event <event-trigger> <event-id>" or see "help npc events".' )
        self.assertEqual(len(npc.events['pc_enter']), 5)
        message = npc.build_remove_event("pc_enter 5", self.bob)
        self.assertEqual(message, "Npc 1 doesn't have the event pc_enter #5." )
        self.assertEqual(len(npc.events['pc_enter']), 5)
        message = npc.build_remove_event("pc_enter 4", self.bob)
        self.assertEqual(message, 'Event pc_enter, number 4 has been removed.')
        self.assertEqual(len(npc.events['pc_enter']), 4)
        message = npc.build_remove_event("given_item 1", self.bob)
        self.assertEqual(message, 'Event given_item, number 1 has been removed.')
        self.assertEqual(len(npc.events['pc_enter']), 4)
        self.assertEqual(len(npc.events['given_item']), 1)
    
    def test_build_add_remove_permissions(self):
        npc = self.area.new_npc()
          #set npc permissions to nothing.
        npc.permissions = 0
        message = npc.build_add_permission("dm", self.bob)
        self.assertEqual(message, "You need to be GOD in order to edit an npc's permissions.")
        #Current permission level needed for messing with npc perms is 'god'. (for when this test was written)
        #Change as needed!
        self.bob.permissions = self.bob.permissions | self.PERMS['god']
        #Bad input tests
        message = npc.build_add_permission("", self.bob)
        self.assertEqual(message, 'Try: "add permission <permission group>". See "help permissions".')
        message = npc.build_add_permission("monkey", self.bob)
        self.assertTrue('Valid permissions are: admin, player, builder, dm, god\n' in message)
        #good input tests
        message = npc.build_add_permission("god", self.bob)
        self.assertTrue('Shiny McShinerson now has god permissions.' in message)
        self.assertTrue(npc.permissions is self.PERMS['god'])
        message = npc.build_add_permission("dm", self.bob)
        self.assertTrue('Shiny McShinerson now has dm permissions.' in message)
        self.assertTrue(npc.permissions is self.PERMS['god'] | self.PERMS['dm'])
        self.assertTrue(npc.permissions is not self.PERMS['god'] | self.PERMS['dm'] | self.PERMS['admin'])
        message = npc.build_add_permission("admin", self.bob)
        self.assertTrue('Shiny McShinerson now has admin permissions.' in message)
        self.assertTrue(npc.permissions is self.PERMS['god'] | self.PERMS['dm'] | self.PERMS['admin'])
        
        #Removing Permissions
          #reset bobs permissions for next test
        self.bob.permissions = 0
        message = npc.build_remove_permission("dm", self.bob)
        self.assertEqual(message, "You need to be GOD in order to edit an npc's permissions.")
        #Current permission level needed for messing with npc perms is 'god'. (for when this test was written)
        #Change as needed!
        self.bob.permissions = self.bob.permissions | self.PERMS['god']
        #Bad input tests
        message = npc.build_remove_permission("", self.bob)
        self.assertEqual(message, 'Try: "remove permission <permission group>", or see "help permissions".')
        message = npc.build_remove_permission("monkey", self.bob)
        self.assertEqual("Shiny McShinerson doesn't have monkey permissions.", message)
        #Good input tests
        self.assertTrue(npc.permissions is self.PERMS['god'] | self.PERMS['dm'] | self.PERMS['admin'])
        message = npc.build_remove_permission("god", self.bob)
        self.assertEqual('Shiny McShinerson no longer has god permissions.', message)
        self.assertTrue(npc.permissions is self.PERMS['dm'] | self.PERMS['admin'])
        self.assertTrue(npc.permissions < self.PERMS['god'])
        message = npc.build_remove_permission("dm", self.bob)
        self.assertEqual('Shiny McShinerson no longer has dm permissions.', message)
        self.assertTrue(npc.permissions is self.PERMS['admin'])
        self.assertTrue(npc.permissions >= self.PERMS['dm'])
        message = npc.build_remove_permission("admin", self.bob)
        self.assertEqual('Shiny McShinerson no longer has admin permissions.', message)
        self.assertTrue(npc.permissions is 0)
    
    def test_build_add_remove_ai(self):
        npc = self.area.new_npc()
        
        #Test adding ai pack
        message = npc.build_add_ai("", self.bob)
        self.assertEqual('Try: "add ai <ai-pack-name>", or type "help ai packs".', message)
        message = npc.build_add_ai("doesnotexist", self.bob)
        self.assertEqual('"doesnotexist" is not a valid ai pack. See "help ai packs".', message)
        message = npc.build_add_ai("merchant", self.bob)
        self.assertEqual("This npc (Shiny McShinerson) is now a merchant.", message)
        message = npc.build_add_ai("merchant", self.bob)
        self.assertEqual('This npc (Shiny McShinerson) already has that ai pack.', message)
    
        #Test basic add behavior for ai pack
        message = str(npc)
        self.assertTrue("MERCHANT ATTRIBUTES:" in message)
        
        #Test removing ai pack
        message = npc.build_remove_ai("", self.bob)
        self.assertEqual('Try: "remove ai <ai-pack-name>", or type "help ai packs".', message)
        message = npc.build_remove_ai("doesnotexist", self.bob)
        self.assertEqual('This npc doesn\'t have the "doesnotexist" ai type.', message)
        message = npc.build_remove_ai("merchant", self.bob)
        self.assertEqual('Npc 1 (Shiny McShinerson) no longer has merchant ai.', message)
        message = npc.build_remove_ai("merchant", self.bob)
        self.assertEqual('This npc doesn\'t have the "merchant" ai type.', message)
示例#20
0
    def test_chat_command(self):
        from shinymud.models.area import Area
        from shinymud.data import config
        from shinymud.models.player import Player
        from shinymud.commands.commands import Chat

        bob = Player(('bob', 'bar'))
        alice = Player(('alice', 'bar'))
        sam = Player(('sam', 'bar'))
        bob.mode = None
        bob.playerize({'name': 'bob', 'password': '******'})
        bob.outq = []
        sam.mode = None
        sam.playerize({'name': 'sam', 'password': '******'})
        sam.outq = []
        self.world.player_add(bob)
        self.world.player_add(sam)
        self.world.player_add(alice)

        Chat(bob, 'lol, hey guys!', 'chat').run()
        chat = config.chat_color + 'Bob chats, "lol, hey guys!"' + config.clear_fcolor
        self.assertTrue(chat in sam.outq)
        self.assertTrue(chat in bob.outq)
        self.assertFalse(chat in alice.outq)

        sam.channels['chat'] = False
        print sam.channels
        print bob.channels
        sam.outq = []
        bob.outq = []
        alice.outq = []

        Chat(bob, 'lol, hey guys!', 'chat').run()
        print sam.channels
        print sam.outq
        print bob.channels
        print bob.outq
        self.assertFalse(chat in sam.outq)
        self.assertTrue(chat in bob.outq)
        self.assertFalse(chat in alice.outq)
示例#21
0
 def test_tell_players(self):
     from shinymud.models.player import Player
     from shinymud.modes.build_mode import BuildMode
     from shinymud.modes.init_mode import InitMode
     from shinymud.data.config import wecho_color, clear_fcolor
     from shinymud.lib.connection_handlers.shiny_connections import ShinyConnection
     
     bob = Player('foo')
     bob.name = 'bob'
     alice = Player('foo')
     alice.name = 'alice'
     self.world.player_add(bob)
     self.world.player_add(alice)
     
     bob.mode = None
     bob.outq = []
     alice.mode = None
     alice.outq = []
     
     self.world.tell_players('hello world!')
     echo = wecho_color + 'hello world!' + clear_fcolor
     self.assertTrue(echo in bob.outq)
     self.assertTrue(echo in alice.outq)
     
     bob.mode = InitMode(bob)
     bob.outq = []
     alice.outq = []
     
     self.world.tell_players('hello all!')
     echo = wecho_color + 'hello all!' + clear_fcolor
     self.assertTrue(echo not in bob.outq)
     self.assertTrue(echo in alice.outq)
     
     bob.mode = BuildMode(bob)
     bob.outq = []
     alice.outq = []
     
     self.world.tell_players('hello!', ['alice'])
     echo = wecho_color + 'hello!' + clear_fcolor
     self.assertTrue(echo in bob.outq)
     self.assertTrue(echo not in alice.outq)
示例#22
0
    def test_shiny_player_format_containers(self):
        """Make sure shiny player format still works when player has containers
        in their inventory.
        """
        from shinymud.lib.sport_plugins.formatters.player_write_shiny_format import format as writeshiny
        from shinymud.lib.sport_plugins.formatters.player_read_shiny_format import format as readshiny
        from shinymud.lib.connection_handlers.shiny_connections import ShinyConnection
        from shinymud.models.player import Player
        sven = Player(('foo', 'bar'))
        sven.playerize({'name': 'sven', 'password': '******'})
        sven.save()
        area = self._create_area()
        item1 = area.new_item()
        item1.build_set_keywords('item1')
        item1.build_add_type('container')
        game1 = item1.load()

        item2 = area.new_item()
        item2.build_set_keywords('item2')
        item2.build_add_type('container')
        game2 = item2.load()
        self.assertTrue(game1.item_types['container'].item_add(game2))

        item3 = area.new_item()
        item3.build_set_keywords('item3')
        game3 = item3.load()
        self.assertTrue(game2.item_types['container'].item_add(game3))

        sven.item_add(game1)

        txt = writeshiny(sven)
        self.world.log.debug(txt)

        sven.destruct()

        row = self.world.db.select('* from player where name=?', ['sven'])
        self.assertFalse(row)
        row = self.world.db.select('* from game_item where owner=?',
                                   [sven.dbid])
        self.assertFalse(row)

        result = readshiny(self.world, txt)
        self.world.log.debug(result)
        self.assertEqual(result,
                         'Character "Sven" has been successfully imported.')
        row = self.world.db.select('* from player where name=?', ['sven'])[0]
        isven = Player(('foo', 'bar'))
        isven.playerize(row)

        self.assertEqual(len(isven.inventory), 1)
        s1 = isven.inventory[0]
        self.assertEqual(s1.keywords, ['item1'])
        s2 = s1.item_types['container'].get_item_by_kw('item2')
        self.assertEqual(s2.keywords, ['item2'])
        s3 = s2.item_types['container'].get_item_by_kw('item3')
        self.assertEqual(s3.keywords, ['item3'])
示例#23
0
    def test_shiny_player_format(self):
        from shinymud.lib.sport_plugins.formatters.player_write_shiny_format import format as writeshiny
        from shinymud.lib.sport_plugins.formatters.player_read_shiny_format import format as readshiny
        from shinymud.models.player import Player
        #create a playa
        sven = Player(('foo', 'bar'))
        sven.playerize({'name': 'sven', 'password': '******'})
        sven.permissions = 17
        sven.description = "I'm pretty adorable."
        sven.title = 'Super Sven'
        sven.save()
        area = self._create_area()
        sven.item_add(area.get_item('1').load())

        txt = writeshiny(sven)
        self.world.log.debug(txt)

        sven.destruct()
        # Sven should have been taken out of the database...
        row = self.world.db.select('* from player where name=?', ['sven'])
        self.assertFalse(row)
        row = self.world.db.select('* from game_item where owner=?',
                                   [sven.dbid])
        self.assertFalse(row)

        result = readshiny(self.world, txt)
        self.world.log.debug(result)
        self.assertEqual(result,
                         'Character "Sven" has been successfully imported.')

        # Sven should now be in the database, but not online
        row = self.world.db.select('* from player where name=?', ['sven'])[0]
        self.assertTrue(row)
        self.assertFalse(self.world.get_player('sven'))

        isven = Player(('foo', 'bar'))
        isven.playerize(row)

        row = self.world.db.select('* from game_item where owner=?',
                                   [isven.dbid])
        self.assertTrue(row)

        # Make sure that all attributes we set got imported correctly
        self.assertEqual(sven.password, isven.password)
        self.assertEqual(sven.description, isven.description)
        self.assertEqual(sven.name, isven.name)
        self.assertEqual(sven.title, isven.title)
        self.assertEqual(sven.permissions, isven.permissions)

        # Make sure that the inventory was correctly loaded
        self.assertEqual(len(sven.inventory), len(isven.inventory))
        item = isven.inventory[0]
        self.world.log.debug(item.create_save_dict())
        self.world.log.debug(item.item_types)
        self.assertFalse(sven.inventory[0] is isven.inventory[0])
        self.assertEqual(item.name, 'chair')
        self.assertTrue(item.has_type('furniture'))
        self.assertEqual(item.item_types['furniture'].capacity, 5)
示例#24
0
class TestNpc(ShinyTestCase):
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.npc import Npc
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.PERMS = config.PERMS

        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name': 'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | self.PERMS['builder']

        self.area = Area.create({'name': 'foo'})
        self.room = self.area.new_room()

        self.area2 = Area.create({'name': 'SimCity'})
        self.area2_script = self.area2.new_script()

    def tearDown(self):
        del self.area
        del self.area2
        del self.bob

    def test_existance(self):
        """Test if an NPC can exist within an area properly (unspawned)"""
        self.npc = self.area.new_npc()
        self.npc.characterize({'name': 'bobert'})
        self.assertTrue(self.npc in self.area.npcs.values())

    def test_build_add_remove_events(self):
        npc = self.area.new_npc()
        fail_message = 'Type "help events" for help with this command.'
        message = npc.build_add_event('', self.bob)
        self.assertEqual(message, fail_message)
        #test for non-existant scripts
        message = npc.build_add_event('pc_enter call script 1', self.bob)
        self.assertEqual(message, "Script 1 doesn't exist.")
        message = npc.build_add_event("hears 'spam' call script 0", self.bob)
        self.assertEqual(message, "Script 0 doesn't exist.")
        message = npc.build_add_event("hears 'spam' call script 602", self.bob)
        self.assertEqual(message, "Script 602 doesn't exist.")

        script = self.area.new_script()
        #Test basic add
        message = npc.build_add_event('pc_enter call script 1', self.bob)
        self.assertEqual(message, 'Event added.')
        #Test invalid areas
        message = npc.build_add_event(
            'pc_enter call script 1 from area AreaDontExist', self.bob)
        self.assertEqual(message, 'Area "AreaDontExist" doesn\'t exist.')
        message = npc.build_add_event(
            'pc_enter call script 1 from area AreaDontExist 100', self.bob)
        self.assertEqual(message, 'Area "AreaDontExist" doesn\'t exist.')
        #Test invalid probabilities.
        message = npc.build_add_event('pc_enter call script 1 0', self.bob)
        self.assertEqual(message,
                         'Probability value must be between 1 and 100.')
        message = npc.build_add_event('pc_enter call script 1 101', self.bob)
        self.assertEqual(message,
                         'Probability value must be between 1 and 100.')
        message = npc.build_add_event('pc_enter call script 1 9999', self.bob)
        self.assertEqual(message,
                         'Probability value must be between 1 and 100.')
        #Test different froms of valid adds.
        message = npc.build_add_event('pc_enter call script 1 50', self.bob)
        self.assertEqual(message, 'Event added.')
        message = npc.build_add_event(
            'pc_enter call script 1 from area SimCity', self.bob)
        self.assertEqual(message, 'Event added.')
        message = npc.build_add_event(
            'pc_enter call script 1 from area SimCity 75', self.bob)
        self.assertEqual(message, 'Event added.')
        message = npc.build_add_event('pc_enter call 1 from SimCity 50',
                                      self.bob)
        self.assertEqual(message, 'Event added.')
        #Test for trigger 'hears'
        message = npc.build_add_event("hears 'food' call script 1", self.bob)
        self.assertEqual(message, 'Event added.')
        #Test for trigger 'emoted'
        message = npc.build_add_event("emoted 'slap' call script 1", self.bob)
        self.assertEqual(message, 'Event added.')
        #Technically invalid, but will be left to user responsibility for now.
        #(it shouldn't ever cause a crash)
        message = npc.build_add_event("emoted 'emotedontexist' call script 1",
                                      self.bob)
        self.assertEqual(message, 'Event added.')
        #Test for new items
        self.area.new_item()
        message = npc.build_add_event("given_item 'item 1' call script 1",
                                      self.bob)
        self.assertEqual(message, 'Event added.')
        #Technically invalid, but will be left to user responsibility for now.
        #(it shouldn't ever cause a crash)
        message = npc.build_add_event("given_item 'item 5' call script 1",
                                      self.bob)
        self.assertEqual(message, 'Event added.')

        #we should now have 5 successfully added events in pc_enter
        self.assertEqual(len(npc.events['pc_enter']), 5)
        message = npc.build_remove_event("pc_enter -1", self.bob)
        self.assertEqual(
            message,
            'Try: "remove event <event-trigger> <event-id>" or see "help npc events".'
        )
        self.assertEqual(len(npc.events['pc_enter']), 5)
        message = npc.build_remove_event("pc_enter 5", self.bob)
        self.assertEqual(message, "Npc 1 doesn't have the event pc_enter #5.")
        self.assertEqual(len(npc.events['pc_enter']), 5)
        message = npc.build_remove_event("pc_enter 4", self.bob)
        self.assertEqual(message, 'Event pc_enter, number 4 has been removed.')
        self.assertEqual(len(npc.events['pc_enter']), 4)
        message = npc.build_remove_event("given_item 1", self.bob)
        self.assertEqual(message,
                         'Event given_item, number 1 has been removed.')
        self.assertEqual(len(npc.events['pc_enter']), 4)
        self.assertEqual(len(npc.events['given_item']), 1)

    def test_build_add_remove_permissions(self):
        npc = self.area.new_npc()
        #set npc permissions to nothing.
        npc.permissions = 0
        message = npc.build_add_permission("dm", self.bob)
        self.assertEqual(
            message,
            "You need to be GOD in order to edit an npc's permissions.")
        #Current permission level needed for messing with npc perms is 'god'. (for when this test was written)
        #Change as needed!
        self.bob.permissions = self.bob.permissions | self.PERMS['god']
        #Bad input tests
        message = npc.build_add_permission("", self.bob)
        self.assertEqual(
            message,
            'Try: "add permission <permission group>". See "help permissions".'
        )
        message = npc.build_add_permission("monkey", self.bob)
        self.assertTrue(
            'Valid permissions are: admin, player, builder, dm, god\n' in
            message)
        #good input tests
        message = npc.build_add_permission("god", self.bob)
        self.assertTrue(
            'Shiny McShinerson now has god permissions.' in message)
        self.assertTrue(npc.permissions is self.PERMS['god'])
        message = npc.build_add_permission("dm", self.bob)
        self.assertTrue('Shiny McShinerson now has dm permissions.' in message)
        self.assertTrue(
            npc.permissions is self.PERMS['god'] | self.PERMS['dm'])
        self.assertTrue(npc.permissions is not self.PERMS['god']
                        | self.PERMS['dm'] | self.PERMS['admin'])
        message = npc.build_add_permission("admin", self.bob)
        self.assertTrue(
            'Shiny McShinerson now has admin permissions.' in message)
        self.assertTrue(npc.permissions is self.PERMS['god'] | self.PERMS['dm']
                        | self.PERMS['admin'])

        #Removing Permissions
        #reset bobs permissions for next test
        self.bob.permissions = 0
        message = npc.build_remove_permission("dm", self.bob)
        self.assertEqual(
            message,
            "You need to be GOD in order to edit an npc's permissions.")
        #Current permission level needed for messing with npc perms is 'god'. (for when this test was written)
        #Change as needed!
        self.bob.permissions = self.bob.permissions | self.PERMS['god']
        #Bad input tests
        message = npc.build_remove_permission("", self.bob)
        self.assertEqual(
            message,
            'Try: "remove permission <permission group>", or see "help permissions".'
        )
        message = npc.build_remove_permission("monkey", self.bob)
        self.assertEqual("Shiny McShinerson doesn't have monkey permissions.",
                         message)
        #Good input tests
        self.assertTrue(npc.permissions is self.PERMS['god'] | self.PERMS['dm']
                        | self.PERMS['admin'])
        message = npc.build_remove_permission("god", self.bob)
        self.assertEqual('Shiny McShinerson no longer has god permissions.',
                         message)
        self.assertTrue(
            npc.permissions is self.PERMS['dm'] | self.PERMS['admin'])
        self.assertTrue(npc.permissions < self.PERMS['god'])
        message = npc.build_remove_permission("dm", self.bob)
        self.assertEqual('Shiny McShinerson no longer has dm permissions.',
                         message)
        self.assertTrue(npc.permissions is self.PERMS['admin'])
        self.assertTrue(npc.permissions >= self.PERMS['dm'])
        message = npc.build_remove_permission("admin", self.bob)
        self.assertEqual('Shiny McShinerson no longer has admin permissions.',
                         message)
        self.assertTrue(npc.permissions is 0)

    def test_build_add_remove_ai(self):
        npc = self.area.new_npc()

        #Test adding ai pack
        message = npc.build_add_ai("", self.bob)
        self.assertEqual(
            'Try: "add ai <ai-pack-name>", or type "help ai packs".', message)
        message = npc.build_add_ai("doesnotexist", self.bob)
        self.assertEqual(
            '"doesnotexist" is not a valid ai pack. See "help ai packs".',
            message)
        message = npc.build_add_ai("merchant", self.bob)
        self.assertEqual("This npc (Shiny McShinerson) is now a merchant.",
                         message)
        message = npc.build_add_ai("merchant", self.bob)
        self.assertEqual(
            'This npc (Shiny McShinerson) already has that ai pack.', message)

        #Test basic add behavior for ai pack
        message = str(npc)
        self.assertTrue("MERCHANT ATTRIBUTES:" in message)

        #Test removing ai pack
        message = npc.build_remove_ai("", self.bob)
        self.assertEqual(
            'Try: "remove ai <ai-pack-name>", or type "help ai packs".',
            message)
        message = npc.build_remove_ai("doesnotexist", self.bob)
        self.assertEqual('This npc doesn\'t have the "doesnotexist" ai type.',
                         message)
        message = npc.build_remove_ai("merchant", self.bob)
        self.assertEqual(
            'Npc 1 (Shiny McShinerson) no longer has merchant ai.', message)
        message = npc.build_remove_ai("merchant", self.bob)
        self.assertEqual('This npc doesn\'t have the "merchant" ai type.',
                         message)
示例#25
0
 def test_shiny_player_format(self):
     from shinymud.lib.sport_plugins.formatters.player_write_shiny_format import format as writeshiny
     from shinymud.lib.sport_plugins.formatters.player_read_shiny_format import format as readshiny
     from shinymud.models.player import Player
     #create a playa
     sven = Player(('foo', 'bar'))
     sven.playerize({'name': 'sven', 'password': '******'})
     sven.permissions = 17
     sven.description = "I'm pretty adorable."
     sven.title = 'Super Sven'
     sven.save()
     area = self._create_area()
     sven.item_add(area.get_item('1').load())
     
     txt = writeshiny(sven)
     self.world.log.debug(txt)
     
     sven.destruct()
     # Sven should have been taken out of the database...
     row = self.world.db.select('* from player where name=?', ['sven'])
     self.assertFalse(row)
     row = self.world.db.select('* from game_item where owner=?', [sven.dbid])
     self.assertFalse(row)
     
     result = readshiny(self.world, txt)
     self.world.log.debug(result)
     self.assertEqual(result, 'Character "Sven" has been successfully imported.')
     
     # Sven should now be in the database, but not online
     row = self.world.db.select('* from player where name=?', ['sven'])[0]
     self.assertTrue(row)
     self.assertFalse(self.world.get_player('sven'))
     
     isven = Player(('foo', 'bar'))
     isven.playerize(row)
     
     row = self.world.db.select('* from game_item where owner=?', [isven.dbid])
     self.assertTrue(row)
     
     # Make sure that all attributes we set got imported correctly
     self.assertEqual(sven.password, isven.password)
     self.assertEqual(sven.description, isven.description)
     self.assertEqual(sven.name, isven.name)
     self.assertEqual(sven.title, isven.title)
     self.assertEqual(sven.permissions, isven.permissions)
     
     # Make sure that the inventory was correctly loaded
     self.assertEqual(len(sven.inventory), len(isven.inventory))
     item = isven.inventory[0]
     self.world.log.debug(item.create_save_dict())
     self.world.log.debug(item.item_types)
     self.assertFalse(sven.inventory[0] is isven.inventory[0])
     self.assertEqual(item.name, 'chair')
     self.assertTrue(item.has_type('furniture'))
     self.assertEqual(item.item_types['furniture'].capacity, 5)
示例#26
0
class TestTextEditMode(ShinyTestCase):
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name': 'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | config.BUILDER

        self.area = Area.create({'name': 'foo'})

    def tearDown(self):
        del self.area

    def test_help(self):
        from shinymud.modes.text_edit_mode import TextEditMode
        room = self.area.new_room()
        help_msg = "    @done - saves your progress and exits the editor.\n" +\
                   "    @cancel - quit the editor without saving changes.\n" +\
                   "    @show - display your progress so far, line by line.\n" +\
                   "    @preview - preview the formatted version of your text.\n" +\
                   "    @clear - clears ALL of your progress, giving you an empty slate.\n" +\
                   "    @delete line# - delete a specific line.\n" +\
                   "    @replace line# new_sentence - replace a line with a new sentence:\n" +\
                   "        e.g. \"@replace 5 My new sentence.\"\n" +\
                   "    @insert line# new_sentence - inserts a sentence at line#:\n" +\
                   "        e.g. \"@insert 1 My new sentence.\"\n"
        mode = TextEditMode(self.bob, room, 'description', room.description)
        mode.help()
        self.assertTrue(help_msg in self.bob.outq)

    def test_clear(self):
        from shinymud.modes.text_edit_mode import TextEditMode
        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, 'description', room.description)

        mode.edit_lines = ['This is a shiny new room!']
        mode.clear_description()
        mode.finish_editing()
        self.assertEqual(room.description, '')

    def test_delete_line(self):
        from shinymud.modes.text_edit_mode import TextEditMode
        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, 'description', room.description)

        #Manually give the room description so we don't depend on the new_room() defaults
        mode.edit_lines = [
            "This be a shiny room here!", "There be goblins here!",
            "And a pirate!"
        ]
        mode.delete_line(line='2')
        self.assertEqual(len(mode.edit_lines), 2)
        mode.finish_editing()
        self.assertFalse("There be goblins here!" in room.description)

        #stress testing
        mode = TextEditMode(self.bob, room, 'description', room.description)
        mode.delete_line(line='200')
        self.assertTrue("200 is not a valid line number." in self.bob.outq)

        #(regular expression parses non-digit input into args instead of line)
        mode.delete_line(args='YourMother')
        self.assertTrue(
            "'YourMother' is not a valid line number." in self.bob.outq)

    def test_replace_line(self):
        from shinymud.modes.text_edit_mode import TextEditMode
        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, 'description', room.description)

        #Manually give the room description so we don't depend on the new_room() defaults
        mode.edit_lines = [
            "This be a shiny room here!", "There be goblins here!",
            "And a pirate!"
        ]
        mode.replace_line(line='2', args='There be spam and eggs here!')
        self.assertEqual(len(mode.edit_lines), 3)
        mode.finish_editing()
        self.assertTrue('There be spam and eggs here!' in room.description)

        #stress testing
        mode = TextEditMode(self.bob, room, 'description', room.description)
        mode.replace_line(line='200')
        self.assertTrue("200 is not a valid line number." in self.bob.outq)

        #(regular expression parses non-digit input into args instead of line)
        mode.replace_line(args='YourMother')
        self.assertTrue(
            "'YourMother' is not a valid line number." in self.bob.outq)

    def test_insert_line(self):
        from shinymud.modes.text_edit_mode import TextEditMode
        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, 'description', room.description)

        #Manually give the room description so we don't depend on the new_room() defaults
        mode.edit_lines = [
            "This be a shiny room here!", "There be goblins here!",
            "And a pirate!"
        ]
        mode.insert_line(line='2', args='There be spam and eggs here!')
        self.assertEqual(len(mode.edit_lines), 4)
        mode.finish_editing()
        self.assertTrue('There be spam and eggs here!' in room.description)

        #stress testing
        mode = TextEditMode(self.bob, room, 'description', room.description)
        mode.insert_line(line='200')
        self.assertTrue("200 is not a valid line number." in self.bob.outq)

        mode.insert_line(args='YourMother')
        self.assertTrue(
            "'YourMother' is not a valid line number." in self.bob.outq)

    def test_cancel_edit(self):
        from shinymud.modes.text_edit_mode import TextEditMode
        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, 'description', room.description)

        mode.edit_lines = [
            "This be a shiny room here!", "There be goblins here!",
            "And a pirate!"
        ]
        mode.finish_editing()
        mode = TextEditMode(self.bob, room, 'description', room.description)
        mode.insert_line(line='2', args='There be spam and eggs here!')
        mode.cancel_edit()
        self.assertFalse('There be spam and eggs here!' in room.description)
示例#27
0
class TestTextEditMode(ShinyTestCase):
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.bob = Player(("bob", "bar"))
        self.bob.mode = None
        self.bob.playerize({"name": "bob"})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | config.BUILDER

        self.area = Area.create({"name": "foo"})

    def tearDown(self):
        del self.area

    def test_help(self):
        from shinymud.modes.text_edit_mode import TextEditMode

        room = self.area.new_room()
        help_msg = (
            "    @done - saves your progress and exits the editor.\n"
            + "    @cancel - quit the editor without saving changes.\n"
            + "    @show - display your progress so far, line by line.\n"
            + "    @preview - preview the formatted version of your text.\n"
            + "    @clear - clears ALL of your progress, giving you an empty slate.\n"
            + "    @delete line# - delete a specific line.\n"
            + "    @replace line# new_sentence - replace a line with a new sentence:\n"
            + '        e.g. "@replace 5 My new sentence."\n'
            + "    @insert line# new_sentence - inserts a sentence at line#:\n"
            + '        e.g. "@insert 1 My new sentence."\n'
        )
        mode = TextEditMode(self.bob, room, "description", room.description)
        mode.help()
        self.assertTrue(help_msg in self.bob.outq)

    def test_clear(self):
        from shinymud.modes.text_edit_mode import TextEditMode

        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, "description", room.description)

        mode.edit_lines = ["This is a shiny new room!"]
        mode.clear_description()
        mode.finish_editing()
        self.assertEqual(room.description, "")

    def test_delete_line(self):
        from shinymud.modes.text_edit_mode import TextEditMode

        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, "description", room.description)

        # Manually give the room description so we don't depend on the new_room() defaults
        mode.edit_lines = ["This be a shiny room here!", "There be goblins here!", "And a pirate!"]
        mode.delete_line(line="2")
        self.assertEqual(len(mode.edit_lines), 2)
        mode.finish_editing()
        self.assertFalse("There be goblins here!" in room.description)

        # stress testing
        mode = TextEditMode(self.bob, room, "description", room.description)
        mode.delete_line(line="200")
        self.assertTrue("200 is not a valid line number." in self.bob.outq)

        # (regular expression parses non-digit input into args instead of line)
        mode.delete_line(args="YourMother")
        self.assertTrue("'YourMother' is not a valid line number." in self.bob.outq)

    def test_replace_line(self):
        from shinymud.modes.text_edit_mode import TextEditMode

        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, "description", room.description)

        # Manually give the room description so we don't depend on the new_room() defaults
        mode.edit_lines = ["This be a shiny room here!", "There be goblins here!", "And a pirate!"]
        mode.replace_line(line="2", args="There be spam and eggs here!")
        self.assertEqual(len(mode.edit_lines), 3)
        mode.finish_editing()
        self.assertTrue("There be spam and eggs here!" in room.description)

        # stress testing
        mode = TextEditMode(self.bob, room, "description", room.description)
        mode.replace_line(line="200")
        self.assertTrue("200 is not a valid line number." in self.bob.outq)

        # (regular expression parses non-digit input into args instead of line)
        mode.replace_line(args="YourMother")
        self.assertTrue("'YourMother' is not a valid line number." in self.bob.outq)

    def test_insert_line(self):
        from shinymud.modes.text_edit_mode import TextEditMode

        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, "description", room.description)

        # Manually give the room description so we don't depend on the new_room() defaults
        mode.edit_lines = ["This be a shiny room here!", "There be goblins here!", "And a pirate!"]
        mode.insert_line(line="2", args="There be spam and eggs here!")
        self.assertEqual(len(mode.edit_lines), 4)
        mode.finish_editing()
        self.assertTrue("There be spam and eggs here!" in room.description)

        # stress testing
        mode = TextEditMode(self.bob, room, "description", room.description)
        mode.insert_line(line="200")
        self.assertTrue("200 is not a valid line number." in self.bob.outq)

        mode.insert_line(args="YourMother")
        self.assertTrue("'YourMother' is not a valid line number." in self.bob.outq)

    def test_cancel_edit(self):
        from shinymud.modes.text_edit_mode import TextEditMode

        room = self.area.new_room()
        mode = TextEditMode(self.bob, room, "description", room.description)

        mode.edit_lines = ["This be a shiny room here!", "There be goblins here!", "And a pirate!"]
        mode.finish_editing()
        mode = TextEditMode(self.bob, room, "description", room.description)
        mode.insert_line(line="2", args="There be spam and eggs here!")
        mode.cancel_edit()
        self.assertFalse("There be spam and eggs here!" in room.description)
示例#28
0
    def test_give_command(self):
        from shinymud.models.area import Area
        from shinymud.data import config
        from shinymud.models.player import Player
        from shinymud.commands.commands import Give
        area = Area.create({'name': 'blarg'})
        room = area.new_room()
        bob = Player(('bob', 'bar'))
        bob.mode = None
        bob.playerize({'name': 'bob', 'password': '******'})
        alice = Player(('alice', 'bar'))
        alice.mode = None
        alice.playerize({'name': 'alice', 'password': '******'})
        self.world.player_add(bob)
        self.world.player_add(alice)

        room.add_char(bob)
        room.add_char(alice)
        alice.location = room
        bob.location = room
        proto_npc = area.new_npc()
        npc = proto_npc.load()
        room.add_char(npc)

        item = area.new_item()
        item.build_set_keywords('bauble', bob)
        item.build_set_name('a bauble', bob)
        bob.item_add(item.load())

        self.assertEqual(len(bob.inventory), 1)
        Give(bob, 'bauble to alice', 'give').run()
        self.assertEqual(len(bob.inventory), 0)
        self.assertEqual(len(alice.inventory), 1)
        to_alice = 'Bob gives you a bauble.'
        self.assertTrue(to_alice in alice.outq)
        to_bob = 'You give a bauble to Alice.'
        self.assertTrue(to_bob in bob.outq)

        Give(alice, 'bauble to shiny', 'give').run()
        self.assertEqual(len(alice.inventory), 0)
        self.assertEqual(len(npc.inventory), 1)
        to_alice = 'You give a bauble to %s.' % npc.name
        alice.world.log.debug(alice.outq)
        self.assertTrue(to_alice in alice.outq)
        to_shiny = 'Alice gives you a bauble.'
        self.assertTrue(to_shiny in npc.actionq)

        #Test Money
        bob.currency = 100
        com = config.CURRENCY + ' to alice'
        #Test give one currency unit
        self.assertEqual(alice.currency, 0)
        Give(bob, com, 'give').run()
        self.assertEqual(bob.currency, 99)
        self.assertEqual(alice.currency, 1)
        #test give multiple currencies
        com = '99' + config.CURRENCY + ' to alice'
        Give(bob, com, 'give').run()
        self.assertEqual(bob.currency, 0)
        self.assertEqual(alice.currency, 100)
        #test give more than bob has
        com = '1000' + config.CURRENCY + ' to alice'
        Give(bob, com, 'give').run()
        self.assertEqual(bob.currency, 0)
        self.assertEqual(alice.currency, 100)
示例#29
0
class TestAiPacks(ShinyTestCase):
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.npc import Npc
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config

        self.PERMS = config.PERMS

        #"bob" is created so we can tell build mode functions which player called them.
        #We probably don't need bob since this functionality is only important when permissions
        #are concerned in build commands. We'll create and pass him in anyways for now.
        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name': 'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | self.PERMS['builder']

        self.area = Area.create({'name': 'foo'})

    def tearDown(self):
        del self.area
        del self.bob

    def test_merchant_build_add_remove_item(self):
        npc = self.area.new_npc()
        npc.build_add_ai("merchant", self.bob)
        ai = npc.ai_packs['merchant']
        self.area.new_item()

        #Add items
        message = ai.build_add_item("", self.bob)
        self.assertEqual(
            message,
            'Try "add item <item-id> from area <area-name> price <price>" or see "help merchant".'
        )
        message = ai.build_add_item("BLARG", self.bob)
        self.assertEqual(
            message,
            'Try "add item <item-id> from area <area-name> price <price>" or see "help merchant".'
        )
        message = ai.build_add_item(
            "1 from area_which_does_not_exist price 20", self.bob)
        self.assertEqual(message,
                         'Area "area_which_does_not_exist" doesn\'t exist.')
        message = ai.build_add_item("2 from foo price 20", self.bob)
        self.assertEqual(message, "Item 2 doesn't exist.")
        message = ai.build_add_item("1 from foo price 30", self.bob)
        self.assertEqual(message, "Merchant now sells New Item.")

        #remove items
        message = ai.build_remove_item("", self.bob)
        self.assertEqual(
            message, 'Try "remove item <item-id>", or see "help merchant".')
        message = ai.build_remove_item("BLARG", self.bob)
        self.assertEqual(
            message, 'Try "remove item <item-id>", or see "help merchant".')
        message = ai.build_remove_item("6203", self.bob)
        self.assertEqual(message, "That item doesn't exist.")
        message = ai.build_remove_item("0", self.bob)
        self.assertEqual(message, "That item doesn't exist.")
        message = ai.build_remove_item("-1", self.bob)
        self.assertEqual(
            message, 'Try "remove item <item-id>", or see "help merchant".')
        message = ai.build_remove_item("1", self.bob)
        self.assertEqual(message, 'Merchant no longer sells New Item.')

        #Clean up everything in the area so future tests don't have problems
        self.area.destroy_npc(1)
        self.area.destroy_item(1)

    def test_merchant_build_add_remove_types(self):
        #We'll need a merchant npc for this test!
        npc = self.area.new_npc()
        npc.build_add_ai("merchant", self.bob)
        ai = npc.ai_packs['merchant']

        #Test adding types with good and bad user input.
        tests = {
            "": 'Try "add type <item-type>", or see "help merchant".',
            "BLARG":
            'blarg is not a valid item type. See "help merchant" for details.',
            'equippable':
            'Merchant will now buy items of type equippable from players.',
            'plain': 'Merchant will now buy items of type plain from players.'
        }
        for (input_m, output_m) in tests.iteritems():
            self.assertEqual(ai.build_add_type(input_m, self.bob), output_m)

        #Test user input for removing types. Note: We test these inputs below with two
        #input types already added from the tests above. (equippable and plain)
        tests = {
            "": 'Try "remove type <item-type>", or see "help merchant".',
            "BLARG":
            'blarg is not a valid item type. See "help merchant" for details.',
            "equippable": 'Merchant no longer buys items of type equippable.',
            "plain": 'Merchant no longer buys items of type plain.'
        }
        for (input_m, output_m) in tests.iteritems():
            self.assertEqual(ai.build_remove_type(input_m, self.bob), output_m)

        #test trying to remove a vaild item type again, after we already did.
        message = ai.build_remove_type("equippable", self.bob)
        self.assertEqual(
            message, "Merchant already doesn't buy items of type equippable.")

        #cleanup for additional tests
        self.area.destroy_npc(1)
        self.area.destroy_item(1)

    def test_merchant_volatile_items(self):
        #Merchants can sell items from different areas, which can be
        #destroyed or re-imported/recreated at random. Make sure that
        #Merchants can still keep track of items amidst such chaos!
        from shinymud.models.area import Area
        #Create our merchant
        npc = self.area.new_npc()
        npc.build_add_ai("merchant", self.bob)
        ai = npc.ai_packs['merchant']

        #Create our area, with which we will have our missing 'dead item'
        area2 = Area.create({'name': 'bar'})
        item = area2.new_item()
        item.name = 'trucknuts'
        item.save()

        #add item to area, make sure it added correctly
        message = ai.build_add_item('1 from area bar price 2000')
        self.assertEqual(message, 'Merchant now sells trucknuts.')
        self.assertEqual(item,
                         ai.sale_items.verify_item(ai.sale_items.live[0]))
        self.assertEqual([], ai.sale_items.dead)

        #Destroy the area, with the item we're selling.
        self.world.destroy_area('bar', self.bob)
        self.assertFalse(self.world.area_exists('bar'))

        #ask for a copy of the merch list, make sure the item is not still
        #trying to be sold (dead)
        ai.sale_items.merch_list()  # updates live,dead lists
        self.assertEqual([], ai.sale_items.live)
        self.assertTrue('trucknuts' in ai.sale_items.dead[0].values())

        #Recreate the same area and item
        area2 = Area.create({'name': 'bar'})
        item = area2.new_item()
        item.name = 'trucknuts'
        item.save()

        #Update the list. Our item should be resurrected!
        ai.sale_items.merch_list()
        self.assertTrue('trucknuts' in ai.sale_items.live[0].values())
        self.assertEqual([], ai.sale_items.dead)
示例#30
0
 def test_give_command(self):
     from shinymud.models.area import Area
     from shinymud.data import config
     from shinymud.models.player import Player
     from shinymud.commands.commands import Give
     area = Area.create({'name':'blarg'})
     room = area.new_room()
     bob = Player(('bob', 'bar'))
     bob.mode = None
     bob.playerize({'name':'bob', 'password':'******'})
     alice = Player(('alice', 'bar'))
     alice.mode = None
     alice.playerize({'name':'alice', 'password':'******'})
     self.world.player_add(bob)
     self.world.player_add(alice)
     
     room.add_char(bob)
     room.add_char(alice)
     alice.location = room
     bob.location = room
     proto_npc = area.new_npc()
     npc = proto_npc.load()
     room.add_char(npc)
     
     item = area.new_item()
     item.build_set_keywords('bauble', bob)
     item.build_set_name('a bauble', bob)
     bob.item_add(item.load())
     
     self.assertEqual(len(bob.inventory), 1)
     Give(bob, 'bauble to alice', 'give').run()
     self.assertEqual(len(bob.inventory), 0)
     self.assertEqual(len(alice.inventory), 1)
     to_alice = 'Bob gives you a bauble.'
     self.assertTrue(to_alice in alice.outq)
     to_bob = 'You give a bauble to Alice.'
     self.assertTrue(to_bob in bob.outq)
     
     Give(alice, 'bauble to shiny', 'give').run()
     self.assertEqual(len(alice.inventory), 0)
     self.assertEqual(len(npc.inventory), 1)
     to_alice = 'You give a bauble to %s.' % npc.name
     alice.world.log.debug(alice.outq)
     self.assertTrue(to_alice in alice.outq)
     to_shiny = 'Alice gives you a bauble.'
     self.assertTrue(to_shiny in npc.actionq)
     
     #Test Money
     bob.currency = 100
     com = config.CURRENCY + ' to alice'
     #Test give one currency unit
     self.assertEqual(alice.currency, 0)
     Give(bob, com, 'give').run()
     self.assertEqual(bob.currency, 99)
     self.assertEqual(alice.currency, 1)
     #test give multiple currencies
     com = '99' + config.CURRENCY + ' to alice'
     Give(bob, com, 'give').run()
     self.assertEqual(bob.currency, 0)
     self.assertEqual(alice.currency, 100)
     #test give more than bob has
     com = '1000' + config.CURRENCY + ' to alice'
     Give(bob, com, 'give').run()
     self.assertEqual(bob.currency, 0)
     self.assertEqual(alice.currency, 100)
示例#31
0
 def test_shiny_player_format_containers(self):
     """Make sure shiny player format still works when player has containers
     in their inventory.
     """
     from shinymud.lib.sport_plugins.formatters.player_write_shiny_format import format as writeshiny
     from shinymud.lib.sport_plugins.formatters.player_read_shiny_format import format as readshiny
     from shinymud.lib.connection_handlers.shiny_connections import ShinyConnection
     from shinymud.models.player import Player
     sven = Player(('foo', 'bar'))
     sven.playerize({'name': 'sven', 'password': '******'})
     sven.save()
     area = self._create_area()
     item1 = area.new_item()
     item1.build_set_keywords('item1')
     item1.build_add_type('container')
     game1 = item1.load()
     
     item2 = area.new_item()
     item2.build_set_keywords('item2')
     item2.build_add_type('container')
     game2 = item2.load()
     self.assertTrue(game1.item_types['container'].item_add(game2))
     
     item3 = area.new_item()
     item3.build_set_keywords('item3')
     game3 = item3.load()
     self.assertTrue(game2.item_types['container'].item_add(game3))
     
     sven.item_add(game1)
     
     txt = writeshiny(sven)
     self.world.log.debug(txt)
     
     sven.destruct()
     
     row = self.world.db.select('* from player where name=?', ['sven'])
     self.assertFalse(row)
     row = self.world.db.select('* from game_item where owner=?', [sven.dbid])
     self.assertFalse(row)
     
     result = readshiny(self.world, txt)
     self.world.log.debug(result)
     self.assertEqual(result, 'Character "Sven" has been successfully imported.')
     row = self.world.db.select('* from player where name=?', ['sven'])[0]
     isven = Player(('foo', 'bar'))
     isven.playerize(row)
     
     self.assertEqual(len(isven.inventory), 1)
     s1 = isven.inventory[0]
     self.assertEqual(s1.keywords, ['item1'])
     s2 = s1.item_types['container'].get_item_by_kw('item2')
     self.assertEqual(s2.keywords, ['item2'])
     s3 = s2.item_types['container'].get_item_by_kw('item3')
     self.assertEqual(s3.keywords, ['item3'])
示例#32
0
class TestAiPacks(ShinyTestCase):
    
    def setUp(self):
        ShinyTestCase.setUp(self)
        from shinymud.models.player import Player
        from shinymud.models.npc import Npc
        from shinymud.models.area import Area
        from shinymud.models.room import Room
        from shinymud.modes.build_mode import BuildMode
        from shinymud.data import config
        
        self.PERMS = config.PERMS
        
        #"bob" is created so we can tell build mode functions which player called them.
        #We probably don't need bob since this functionality is only important when permissions
        #are concerned in build commands. We'll create and pass him in anyways for now.
        self.bob = Player(('bob', 'bar'))
        self.bob.mode = None
        self.bob.playerize({'name':'bob'})
        self.world.player_add(self.bob)
        self.bob.mode = BuildMode(self.bob)
        self.bob.permissions = self.bob.permissions | self.PERMS['builder']
        
        self.area = Area.create({'name': 'foo'})
    
    def tearDown(self):
        del self.area
        del self.bob
        
    def test_merchant_build_add_remove_item(self):
        npc = self.area.new_npc()
        npc.build_add_ai("merchant", self.bob)
        ai = npc.ai_packs['merchant']
        self.area.new_item()
        
        
        #Add items
        message = ai.build_add_item("", self.bob)
        self.assertEqual(message, 'Try "add item <item-id> from area <area-name> price <price>" or see "help merchant".')
        message = ai.build_add_item("BLARG", self.bob)
        self.assertEqual(message, 'Try "add item <item-id> from area <area-name> price <price>" or see "help merchant".')
        message = ai.build_add_item("1 from area_which_does_not_exist price 20", self.bob)
        self.assertEqual(message, 'Area "area_which_does_not_exist" doesn\'t exist.')
        message = ai.build_add_item("2 from foo price 20", self.bob)
        self.assertEqual(message, "Item 2 doesn't exist.")
        message = ai.build_add_item("1 from foo price 30", self.bob)
        self.assertEqual(message, "Merchant now sells New Item.")
        
        #remove items
        message = ai.build_remove_item("", self.bob)
        self.assertEqual(message, 'Try "remove item <item-id>", or see "help merchant".')
        message = ai.build_remove_item("BLARG", self.bob)
        self.assertEqual(message, 'Try "remove item <item-id>", or see "help merchant".')
        message = ai.build_remove_item("6203", self.bob)
        self.assertEqual(message, "That item doesn't exist.")
        message = ai.build_remove_item("0", self.bob)
        self.assertEqual(message, "That item doesn't exist.")
        message = ai.build_remove_item("-1", self.bob)
        self.assertEqual(message, 'Try "remove item <item-id>", or see "help merchant".')
        message = ai.build_remove_item("1", self.bob)
        self.assertEqual(message, 'Merchant no longer sells New Item.')
        
        #Clean up everything in the area so future tests don't have problems
        self.area.destroy_npc(1)
        self.area.destroy_item(1)
        
    def test_merchant_build_add_remove_types(self):
        #We'll need a merchant npc for this test!
        npc = self.area.new_npc()
        npc.build_add_ai("merchant", self.bob)
        ai = npc.ai_packs['merchant']
        
        #Test adding types with good and bad user input.
        tests = {
            "": 'Try "add type <item-type>", or see "help merchant".',
            "BLARG": 'blarg is not a valid item type. See "help merchant" for details.',
            'equippable': 'Merchant will now buy items of type equippable from players.',
            'plain': 'Merchant will now buy items of type plain from players.'
        }
        for (input_m, output_m) in tests.iteritems():
            self.assertEqual(ai.build_add_type(input_m, self.bob), output_m)
              
        #Test user input for removing types. Note: We test these inputs below with two
        #input types already added from the tests above. (equippable and plain)
        tests = {
            "":'Try "remove type <item-type>", or see "help merchant".',
            "BLARG":'blarg is not a valid item type. See "help merchant" for details.',
            "equippable":'Merchant no longer buys items of type equippable.',
            "plain":'Merchant no longer buys items of type plain.'
        }   
        for (input_m, output_m) in tests.iteritems():
            self.assertEqual(ai.build_remove_type(input_m, self.bob), output_m)
            
        #test trying to remove a vaild item type again, after we already did.
        message = ai.build_remove_type("equippable", self.bob)
        self.assertEqual(message, "Merchant already doesn't buy items of type equippable.")
        
        #cleanup for additional tests
        self.area.destroy_npc(1)
        self.area.destroy_item(1)
        
    def test_merchant_volatile_items(self):
        #Merchants can sell items from different areas, which can be
        #destroyed or re-imported/recreated at random. Make sure that
        #Merchants can still keep track of items amidst such chaos!
        from shinymud.models.area import Area
        #Create our merchant
        npc = self.area.new_npc()
        npc.build_add_ai("merchant", self.bob)
        ai = npc.ai_packs['merchant']
        
        #Create our area, with which we will have our missing 'dead item'
        area2 = Area.create({'name':'bar'})
        item = area2.new_item()
        item.name = 'trucknuts'
        item.save()
        
        #add item to area, make sure it added correctly
        message = ai.build_add_item('1 from area bar price 2000')
        self.assertEqual(message, 'Merchant now sells trucknuts.')
        self.assertEqual(item, ai.sale_items.verify_item(ai.sale_items.live[0]))
        self.assertEqual([], ai.sale_items.dead)
        
        #Destroy the area, with the item we're selling.
        self.world.destroy_area('bar', self.bob)
        self.assertFalse(self.world.area_exists('bar'))
        
        #ask for a copy of the merch list, make sure the item is not still
        #trying to be sold (dead)
        ai.sale_items.merch_list() # updates live,dead lists
        self.assertEqual([], ai.sale_items.live)
        self.assertTrue('trucknuts' in ai.sale_items.dead[0].values())
    
        #Recreate the same area and item
        area2 = Area.create({'name':'bar'})
        item = area2.new_item()
        item.name = 'trucknuts'
        item.save()
        
        #Update the list. Our item should be resurrected!
        ai.sale_items.merch_list()
        self.assertTrue('trucknuts' in ai.sale_items.live[0].values())
        self.assertEqual([], ai.sale_items.dead)