示例#1
0
 def test_empty_queue_behaviour(self):
     self.instance = CommandManager()
     startQue = copy.copy(self.instance.commandQueue)
     self.instance.main_loop()
     endQue = copy.copy(self.instance.commandQueue)
     self.assertTrue((startQue == endQue), True)
     self.instance.myTimer.cancel()
示例#2
0
    def test_que_is_longer(self):
        self.instance = CommandManager()
        startLength = len(self.instance.commandQueue)
        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)
        endLength = len(self.instance.commandQueue)

        self.assertTrue((startLength != endLength), True)
        self.instance.myTimer.cancel()
示例#3
0
    def test_que_excludes_command(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)

        startContains = (command in self.instance.commandQueue)
        self.instance.delete_command(0)
        endContains = (command in self.instance.commandQueue)

        self.assertFalse(endContains, startContains)
        self.instance.myTimer.cancel()
示例#4
0
    def test_que_is_shorter(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)

        startLength = len(self.instance.commandQueue)
        self.instance.delete_command(0)
        endLength = len(self.instance.commandQueue)

        self.assertFalse((startLength == endLength), False)
        self.instance.myTimer.cancel()
示例#5
0
    def test_sets_new_timer(self):
        self.instance = CommandManager()
        oldTimer = copy.copy(self.instance.myTimer)
        command = ICommand(datetime(2017, 1, 5))

        self.instance.commandQueue.append(command)
        self.instance.create_new_timer()
        newTimer = copy.copy(self.instance.myTimer)

        self.assertFalse((oldTimer == newTimer), False)
        self.instance.myTimer.cancel()
示例#6
0
    def test_myTimer_is_not_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)

        startTimer = self.instance.myTimer
        self.instance.main_loop()
        endTimer = self.instance.myTimer

        self.assertTrue((startTimer == endTimer), True)
        self.instance.myTimer.cancel()
示例#7
0
    def test_head_is_not_same(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        command2 = ICommand(datetime(2018, 1, 5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        oldHead = (self.instance.commandQueue[:])[0]
        self.instance.execute_command()
        startHead = (self.instance.commandQueue[:])[0]
        self.assertTrue((oldHead != startHead), True)
        self.instance.myTimer.cancel()
示例#8
0
    def test_is_head_executed(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)
        head = copy.copy(self.instance.commandQueue[0])
        self.instance.main_loop()
        try:
            self.instance.commandQueue[0]
            self.fail("head is not executed")
            self.instance.myTimer.cancel()
        except IndexError:
            self.assertTrue(True, True)
            self.instance.myTimer.cancel()
示例#9
0
    def test_is_myTimer_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        command2 = ICommand(datetime(2018, 1, 5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        startTimer = copy.copy(self.instance.myTimer)
        self.instance.main_loop
        endTimer = copy.copy(self.instance.myTimer)

        self.assertTrue((startTimer != endTimer), True)
        self.instance.myTimer.cancel()
示例#10
0
class Adapter():
    def __init__(self):
        self.myCommandmanager = CommandManager()
        self.myCommandFactory = CommandFactory()

    def update_all_now(self):
        for counselor in Counselor.objects.all():
            command = self.myCommandFactory.new_ScrapeCommand(datetime.datetime.now(),counselor.url,counselorMatchDict,self.save_counselor_info)
            self.myCommandmanager.enqueue_command(command)

    def update_now(self, counselor):
        command = self.myCommandFactory.new_ScrapeCommand(datetime.datetime.now(),counselor.url,counselorMatchDict,self.save_counselor_info)
        self.myCommandmanager.enqueue_command(command)

    def schedule_update(self, datetime, counselorUrl):
        command = self.myCommandFactory.new_ScrapeCommand(datetime,counselorUrl,counselorMatchDict,self.save_counselor_info)
        self.myCommandmanager.enqueue_command(command)

    def save_counselor_info(self, infoDict, counselorUrl):
        dbTarget = Counselor.objects.get(url = counselorUrl)
        infoDict = convert_bad_encodings(infoDict)
        if dbTarget != None:
            dbTarget.name = infoDict["name"][0]
            dbTarget.email = infoDict["email"][0]
            dbTarget.office = infoDict["office"][0]
            dbTarget.studyArea = infoDict["studyarea"][0]
            dbTarget.save()

    def find_new_counselors(self, executionTime):
        cmd = self.myCommandFactory.new_FindNewCounselorsCommand(executionTime)
        self.myCommandmanager.enqueue_command(cmd)

    def get_scheduled_updates_info(self):
        info_list = []
        id = 0
        for cmd in self.myCommandmanager.commandQueue:
            command_info_dict = {
            "id": id,
            "name": str(type(cmd).__name__),
            "executionTime": str(cmd.executionTime)
            }
            info_list.append(command_info_dict)
            id += 1
        return info_list

    def delete_scheduled_update(self,cmdIndex):
        self.myCommandmanager.delete_command(cmdIndex)

    def clear_all_scheduled_updates(self):
        self.myCommandmanager.commandQueue = []
 def test_empty_queue_behaviour(self):
     self.instance = CommandManager()
     startQue = copy.copy(self.instance.commandQueue)
     self.instance.main_loop()
     endQue = copy.copy(self.instance.commandQueue)
     self.assertTrue((startQue == endQue), True)
     self.instance.myTimer.cancel()
示例#12
0
    def __init__(self, path, default, quiet):
        '''Constructs the bot object. Takes path, default, and quiet arguments from the command
        line input and sets the bot accordingly. Initializes logging, creates instances of
        necessary classes. Loads plugins, begins the connection.'''
        self._config_path = path
        self._default = default
        self._quiet = quiet
        self.logger = logging.getLogger("GorillaBot")
        self._configuration = Configure(self._config_path, self._default,
                                        self._quiet)
        settings = self._configuration.get_configuration()

        self.GorillaConnection = Connection(
            self, settings["host"], settings["port"], settings["nick"],
            settings["ident"], settings["realname"], settings["chans"],
            settings["botop"], settings["fullop"])
        self.GorillaCommander = CommandManager(self, self.GorillaConnection)
        self.GorillaConnection._connect()
示例#13
0
    def __init__(self, loop, token, owner, command_file):
        import logging

        self.__logger = logging.getLogger(__name__)

        TgBot.__init__(self, loop, token)
        self.__owner = re.sub('^@', '', owner) if owner is not None else None

        self.__command_manager = CommandManager(command_file)
    def test_que_is_longer(self):
        self.instance = CommandManager()
        startLength = len(self.instance.commandQueue)
        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)
        endLength = len(self.instance.commandQueue)

        self.assertTrue((startLength != endLength), True)
        self.instance.myTimer.cancel()
示例#15
0
class Bot(object):
    '''The Bot class is the core of the bot. It creates the connection and the responder. All messages
    that are received come through here, and are dispatched accordingly.'''
    
    def __init__(self, path, default, quiet):
        '''Constructs the bot object. Takes path, default, and quiet arguments from the command
        line input and sets the bot accordingly. Initializes logging, creates instances of
        necessary classes. Loads plugins, begins the connection.'''
        self._config_path = path
        self._default = default
        self._quiet = quiet
        self.logger = logging.getLogger("GorillaBot")
        self._configuration = Configure(self._config_path, self._default, self._quiet)
        settings = self._configuration.get_configuration()
        
        self.GorillaConnection = Connection(self, settings["host"], settings["port"],
                                            settings["nick"], settings["ident"],
                                            settings["realname"], settings["chans"],
                                            settings["botop"], settings["fullop"])
        self.GorillaCommander = CommandManager(self, self.GorillaConnection)
        self.GorillaConnection._connect()
        
    def dispatch(self, line):
        '''Determines the type of message received:
                If the message is a ping, it pongs back.
                If the message is from NickServ, it determines identification status.
                If the message contains a reply code, it forwards it to parse_number.
                If the message is a PRIVMSG, it forwards it to parse_message.'''
        
        # Probably will want to remove this at some point in the future, but for now I'm going
        # to hold on to it for debugging.
        self.logger.debug(line)
        
        # Responds to ping messages. Doesn't bother to send it to the CommandManager.
        if "PING" in line[0]:
            self.logger.debug("Ping received.")
            self.GorillaConnection.pong(line[1][1:])
            
        # Identifies messages from NickServ, sends to CommandManager
        elif "NickServ" in line[0]:
            self.GorillaCommander.nickserv_parse(line)
            
        # Identifies server message codes, sends to CommandManager
        elif len(line[1])==3:
            self.GorillaCommander.process_numcode(line[1], line)
            
        # Identifies PRIVMSGs, sends to CommandManager
        elif line[1]=="PRIVMSG":
            self.GorillaCommander.check_command(line)
           
        # Nick changes 
        elif line[1] == "NICK":
            self.GorillaCommander.nick_change(line)
示例#16
0
class Bot(object):
    '''The Bot class is the core of the bot. It creates the connection and the responder. All messages
    that are received come through here, and are dispatched accordingly.'''
    def __init__(self, path, default, quiet):
        '''Constructs the bot object. Takes path, default, and quiet arguments from the command
        line input and sets the bot accordingly. Initializes logging, creates instances of
        necessary classes. Loads plugins, begins the connection.'''
        self._config_path = path
        self._default = default
        self._quiet = quiet
        self.logger = logging.getLogger("GorillaBot")
        self._configuration = Configure(self._config_path, self._default,
                                        self._quiet)
        settings = self._configuration.get_configuration()

        self.GorillaConnection = Connection(
            self, settings["host"], settings["port"], settings["nick"],
            settings["ident"], settings["realname"], settings["chans"],
            settings["botop"], settings["fullop"])
        self.GorillaCommander = CommandManager(self, self.GorillaConnection)
        self.GorillaConnection._connect()

    def dispatch(self, line):
        '''Determines the type of message received:
                If the message is a ping, it pongs back.
                If the message is from NickServ, it determines identification status.
                If the message contains a reply code, it forwards it to parse_number.
                If the message is a PRIVMSG, it forwards it to parse_message.'''

        # Probably will want to remove this at some point in the future, but for now I'm going
        # to hold on to it for debugging.
        self.logger.debug(line)

        # Responds to ping messages. Doesn't bother to send it to the CommandManager.
        if "PING" in line[0]:
            self.logger.debug("Ping received.")
            self.GorillaConnection.pong(line[1][1:])

        # Identifies messages from NickServ, sends to CommandManager
        elif "NickServ" in line[0]:
            self.GorillaCommander.nickserv_parse(line)

        # Identifies server message codes, sends to CommandManager
        elif len(line[1]) == 3:
            self.GorillaCommander.process_numcode(line[1], line)

        # Identifies PRIVMSGs, sends to CommandManager
        elif line[1] == "PRIVMSG":
            self.GorillaCommander.check_command(line)

        # Nick changes
        elif line[1] == "NICK":
            self.GorillaCommander.nick_change(line)
    def test_que_excludes_command(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)

        startContains = (command in self.instance.commandQueue)
        self.instance.delete_command(0)
        endContains  = (command in self.instance.commandQueue)

        self.assertFalse(endContains,startContains)
        self.instance.myTimer.cancel()
    def test_que_is_shorter(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)

        startLength = len(self.instance.commandQueue)
        self.instance.delete_command(0)
        endLength = len(self.instance.commandQueue)

        self.assertFalse((startLength == endLength), False)
        self.instance.myTimer.cancel()
    def test_sets_new_timer(self):
        self.instance = CommandManager()
        oldTimer = copy.copy(self.instance.myTimer)
        command = ICommand(datetime(2017,1,5))

        self.instance.commandQueue.append(command)
        self.instance.create_new_timer()
        newTimer = copy.copy(self.instance.myTimer)

        self.assertFalse((oldTimer == newTimer),False)
        self.instance.myTimer.cancel()
    def test_myTimer_is_not_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)

        startTimer = self.instance.myTimer
        self.instance.main_loop()
        endTimer = self.instance.myTimer

        self.assertTrue((startTimer == endTimer), True)
        self.instance.myTimer.cancel()
    def test_head_is_not_same(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        command2 = ICommand(datetime(2018,1,5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        oldHead = (self.instance.commandQueue[:])[0]
        self.instance.execute_command()
        startHead = (self.instance.commandQueue[:])[0]
        self.assertTrue((oldHead != startHead),True)
        self.instance.myTimer.cancel()
    def test_is_myTimer_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        command2 = ICommand(datetime(2018,1,5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        startTimer = copy.copy(self.instance.myTimer)
        self.instance.main_loop
        endTimer = copy.copy(self.instance.myTimer)

        self.assertTrue((startTimer != endTimer), True)
        self.instance.myTimer.cancel()
    def test_is_head_executed(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)
        head = copy.copy(self.instance.commandQueue[0])
        self.instance.main_loop()
        try:
            self.instance.commandQueue[0]
            self.fail("head is not executed")
            self.instance.myTimer.cancel()
        except IndexError:
            self.assertTrue(True,True)
            self.instance.myTimer.cancel()
示例#24
0
    def __init__(self):

        self.mutex = Lock()
        self.command_manager = CommandManager()

        # Special fields
        self.special_commands = ["commands"]
        self.mod_commands = ["editcmd", "removecmd", "reactto", "removereact"]

        # Read password and nickname from local file.
        with open("pass.pw", 'r') as f:
            self.NICK = ""
            self.PASS = ""
            for line in f:
                username = re.search('^USERNAME = ([A-z0-9:]*)$', line)
                password = re.search('^PASSWORD = ([A-z0-9:]*)$', line)
                if username:
                    self.NICK = username.group(1)
                if password:
                    self.PASS = password.group(1)
        if self.NICK == "" or self.PASS == "":
            print "Username or password wasn't found, make sure file pass.pw is present in current folder."
            exit(1)

        # Setup fields for connecting to twitch.
        self.HOST = "irc.twitch.tv"
        self.PORT = 6667
        self.readbuffer = ""
        self.MODT = False
        self.channel = "crownjeweloftwitch"
        self.printColor(self.Color.FAIL, "Connecting to http://www.twitch.tv/" + self.channel)
       
        # Attempt to connect to the twitch channel.
        try:
            self.s = socket.socket()
            self.s.connect((self.HOST, self.PORT))
            self.s.send("PASS " + self.PASS + "\r\n")
            self.s.send("NICK " + self.NICK + "\r\n")
            self.s.send("JOIN #" + self.channel + " \r\n")
            self.keepReading = True

            # Get a list of all connected users in chat.
            self.update_chatters()
            self.printColor(self.Color.OKGREEN, "Connected!")
        except Exception as e:
            print "Could not connect to http://www.twitch.tv/" + self.channel
            print e
示例#25
0
 def __init__(self, path, default, quiet):
     '''Constructs the bot object. Takes path, default, and quiet arguments from the command
     line input and sets the bot accordingly. Initializes logging, creates instances of
     necessary classes. Loads plugins, begins the connection.'''
     self._config_path = path
     self._default = default
     self._quiet = quiet
     self.logger = logging.getLogger("GorillaBot")
     self._configuration = Configure(self._config_path, self._default, self._quiet)
     settings = self._configuration.get_configuration()
     
     self.GorillaConnection = Connection(self, settings["host"], settings["port"],
                                         settings["nick"], settings["ident"],
                                         settings["realname"], settings["chans"],
                                         settings["botop"], settings["fullop"])
     self.GorillaCommander = CommandManager(self, self.GorillaConnection)
     self.GorillaConnection._connect()
示例#26
0
 def test_que_contains_new_command(self):
     self.instance = CommandManager()
     command = ICommand(datetime(2017, 1, 5))
     self.instance.enqueue_command(command)
     self.assertTrue((command in self.instance.commandQueue), True)
     self.instance.myTimer.cancel()
示例#27
0
 def test_contains_myTimer(self):
     self.instance = CommandManager()
     self.assertTrue(type(self.instance.myTimer), datetime)
     self.instance.myTimer.cancel()
示例#28
0
 def test_is_commandQueue_empty(self):
     self.instance = CommandManager()
     self.instance.myTimer.cancel()
示例#29
0
 def test_contains_commandQueue(self):
     self.instance = CommandManager()
     self.assertTrue(type(self.instance.commandQueue), list)
     self.instance.myTimer.cancel()
示例#30
0
 def test_init(self):
     self.instance = CommandManager()
     self.assertTrue(type(self.instance), CommandManager)
     self.instance.myTimer.cancel()
 def test_que_contains_new_command(self):
     self.instance = CommandManager()
     command = ICommand(datetime(2017,1,5))
     self.instance.enqueue_command(command)
     self.assertTrue((command in self.instance.commandQueue), True)
     self.instance.myTimer.cancel()
示例#32
0
class Twitchbot:

    class Color:
        HEADER = '\033[95m'
        OKBLUE = '\033[94m'
        OKGREEN = '\033[92m'
        WARNING = '\033[93m'
        FAIL = '\033[91m'
        ENDC = '\033[0m'
        BOLD = '\033[1m'
        UNDERLINE = '\033[4m'

    def __init__(self):

        self.mutex = Lock()
        self.command_manager = CommandManager()

        # Special fields
        self.special_commands = ["commands"]
        self.mod_commands = ["editcmd", "removecmd", "reactto", "removereact"]

        # Read password and nickname from local file.
        with open("pass.pw", 'r') as f:
            self.NICK = ""
            self.PASS = ""
            for line in f:
                username = re.search('^USERNAME = ([A-z0-9:]*)$', line)
                password = re.search('^PASSWORD = ([A-z0-9:]*)$', line)
                if username:
                    self.NICK = username.group(1)
                if password:
                    self.PASS = password.group(1)
        if self.NICK == "" or self.PASS == "":
            print "Username or password wasn't found, make sure file pass.pw is present in current folder."
            exit(1)

        # Setup fields for connecting to twitch.
        self.HOST = "irc.twitch.tv"
        self.PORT = 6667
        self.readbuffer = ""
        self.MODT = False
        self.channel = "crownjeweloftwitch"
        self.printColor(self.Color.FAIL, "Connecting to http://www.twitch.tv/" + self.channel)
       
        # Attempt to connect to the twitch channel.
        try:
            self.s = socket.socket()
            self.s.connect((self.HOST, self.PORT))
            self.s.send("PASS " + self.PASS + "\r\n")
            self.s.send("NICK " + self.NICK + "\r\n")
            self.s.send("JOIN #" + self.channel + " \r\n")
            self.keepReading = True

            # Get a list of all connected users in chat.
            self.update_chatters()
            self.printColor(self.Color.OKGREEN, "Connected!")
        except Exception as e:
            print "Could not connect to http://www.twitch.tv/" + self.channel
            print e

    # Update the internal list of chatters and moderators.
    def update_chatters(self):
        response = urllib2.urlopen("https://tmi.twitch.tv/group/user/" + self.channel + "/chatters")
        html = response.read()
        parsed_json = json.loads(html)
        self.users = parsed_json.get("chatters")
        self.chatters_update = datetime.datetime.now()

    def minutes_since_last_chatters_update(self):
        return (self.chatters_update - datetime.datetime.now()).seconds / 60

    # Checks whether a user is mod, will update modlist if more than 3 minutes has passed since last update.
    def user_is_mod(self, user):
        if user in self.users.get("moderators"):
            return True
        elif user not in self.users.get("") and self.minutes_since_last_chatters_update() > 3:
            self.chatters_update = datetime.datetime.now();
            self.update_chatters()
        return user in self.mods 

    # Send a reaction of the given trigger to twitch chat. 
    def react_to(self, trigger):
        response = self.command_manager.get_response(trigger)
        self.send_message(response)

    # Scan messages for triggers.
    def look_for_triggers(self, message):
        for trigger in self.command_manager.get_react_triggers():
            if trigger in message:
                self.react_to(trigger)
                break

    # Parse a command that started with '!'.
    def parse_command(self, command_name, message, user):
        if command_name == "editcmd" and self.user_is_mod(user):
            matchobj = re.match(r"\s*(\w+)\s+(.*)$", message)
            command_to_change = matchobj.group(1)
            command_new_text  = matchobj.group(2)
            self.command_manager.update_command(command_to_change.lower(), command_new_text)
            self.send_message("Command '!" + command_to_change + "' has been updated to '" + command_new_text + "'.")
        elif command_name == "removecmd":
            matchobj = re.match(r"\s*(\w+)", message)
            command_to_remove = matchobj.group(1)
            self.command_manager.remove_command(command_to_remove)
            self.send_message("Command '!" + command_to_remove + "' was removed.")
        elif command_name == "commands":
            commands = self.command_manager.get_commands()
            self.send_message("Available commands are: !" + ", !".join(commands + self.special_commands))
        elif command_name == "reactto":
            matchobj = re.match(r"\s*'(.*?)'\s*'(.*?)'", message)
            trigger = matchobj.group(1)
            response = matchobj.group(2)
            self.command_manager.update_reaction(trigger.lower(), response)
            self.send_message("Response for '" + trigger + "' has been updated to '" + response + "'.")
        elif command_name == "removereact":
            matchobj = re.match(r"\s(.+)", message)
            reaction_to_remove = matchobj.group(1)
            self.command_manager.remove_reaction(reaction_to_remove)
            self.send_message("Reaction for '" + reaction_to_remove + "' was removed.")
        else:
            message_to_send = self.command_manager.get_text_from_db(command_name)
            if message_to_send is not None:
                self.send_message(message_to_send)

    # Print in a given color in the terminal window.
    def printColor(self, color, message):
        print color + message + self.Color.ENDC
    
    # Print a twitch message.
    def printMessage(self, color, username, message):
        print self.Color.HEADER + username + ": " + self.Color.ENDC + color + message + self.Color.ENDC

    # Send a message to twitch chat.
    def send_message(self, message):
        with self.mutex:
            if message == "":
                return
            self.s.send("PRIVMSG #" + self.channel + " :" + message + "\r\n")
            self.printColor(self.Color.OKBLUE, self.NICK + ": " + message)

    # Send a welcome message every 5 minutes.
    def send_welcome_message(self):
        message = self.command_manager.get_welcome_message()
        if message:
            self.send_message(message[0])
        

    # Stop reading twitch chat.
    def stop(self):
        self.keepReading = False

    # Read twitch chat.
    def read_chat(self):
        while self.keepReading:
            # Receive 256 bytes at a time.
            self.readbuffer = self.readbuffer + self.s.recv(256)
            temp = string.split(self.readbuffer, "\n")
            self.readbuffer = temp.pop()

            for line in temp:
                # Respond to twitch pings.
                parts = string.split(line, ":")
                if "PING" in parts[0]:
                    self.s.send("PONG %s\r\n" % parts[1])
                else:
                    try:
                        if "QUIT" not in parts[1] and "JOIN" not in parts[1] and "PART" not in parts[1]:
                            try:
                                message = ":".join(parts[2:])
                                message = message[:-1]
                            except:
                                message = ""

                            usernamesplit = string.split(parts[1], "!")
                            username = usernamesplit[0]

                            if self.MODT:
                                command = re.match(r"!(\w+)(.*)", message)
                                if command:
                                    self.parse_command(command.group(1).lower(), command.group(2), username)
                                else:
                                    self.look_for_triggers(message.lower())
                            for l in parts:
                                if "End of /NAMES list" in l:
                                    self.MODT = True
                        elif "PART" in parts[1]:
                            self.printColor(self.Color.FAIL, ":".join(parts))
                    except Exception as e:
                        print e
                        for l in parts:
                            print l

        print "Thread stopping"
class Test_CommandManager(ut.TestCase):
    def setUp(self):
        self.instance = CommandManager()
        self.instance.myTimer.cancel()

    #__init__: inits
    def test_init(self):
        self.instance = CommandManager()
        self.assertTrue(type(self.instance),CommandManager)
        self.instance.myTimer.cancel()
    #__init__: contains commandQueue
    def test_contains_commandQueue(self):
        self.instance = CommandManager()
        self.assertTrue(type(self.instance.commandQueue),list)
        self.instance.myTimer.cancel()
    #__init__: commandQueue is empty on init
    def test_is_commandQueue_empty(self):
        self.instance = CommandManager()
        self.instance.myTimer.cancel()
    #__init__: contains myTimer
    def test_contains_myTimer(self):
        self.instance = CommandManager()
        self.assertTrue(type(self.instance.myTimer),datetime)
        self.instance.myTimer.cancel()
    #enqueue_command: commandQueue is +1 longer after enqueue_command
    def test_que_is_longer(self):
        self.instance = CommandManager()
        startLength = len(self.instance.commandQueue)
        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)
        endLength = len(self.instance.commandQueue)

        self.assertTrue((startLength != endLength), True)
        self.instance.myTimer.cancel()
    #enqueue_command: commandQueue contains the queued command
    def test_que_contains_new_command(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)
        self.assertTrue((command in self.instance.commandQueue), True)
        self.instance.myTimer.cancel()
    #delete_command: commandQueue is -1 longer after delete_command
    def test_que_is_shorter(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)

        startLength = len(self.instance.commandQueue)
        self.instance.delete_command(0)
        endLength = len(self.instance.commandQueue)

        self.assertFalse((startLength == endLength), False)
        self.instance.myTimer.cancel()

    #delete_command: commandQueue does not contain the deleted command
    def test_que_excludes_command(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)

        startContains = (command in self.instance.commandQueue)
        self.instance.delete_command(0)
        endContains  = (command in self.instance.commandQueue)

        self.assertFalse(endContains,startContains)
        self.instance.myTimer.cancel()

    #create_new_timer: sets a new timer
    def test_sets_new_timer(self):
        self.instance = CommandManager()
        oldTimer = copy.copy(self.instance.myTimer)
        command = ICommand(datetime(2017,1,5))

        self.instance.commandQueue.append(command)
        self.instance.create_new_timer()
        newTimer = copy.copy(self.instance.myTimer)

        self.assertFalse((oldTimer == newTimer),False)
        self.instance.myTimer.cancel()
    #execute_command: Head is not the same after execute has been run
    def test_head_is_not_same(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        command2 = ICommand(datetime(2018,1,5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        oldHead = (self.instance.commandQueue[:])[0]
        self.instance.execute_command()
        startHead = (self.instance.commandQueue[:])[0]
        self.assertTrue((oldHead != startHead),True)
        self.instance.myTimer.cancel()
    #execute_command: myTimer is updated after execute has been run
    def test_myTimer_is_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        command2 = ICommand(datetime(2018,1,5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        startTimer = copy.copy(self.instance.myTimer)
        self.instance.execute_command()
        endTimer = copy.copy(self.instance.myTimer)

        self.assertTrue((startTimer != endTimer),True)
        self.instance.myTimer.cancel()
    #main_loop: if there is something in the que it should be executed
    def test_is_head_executed(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)
        head = copy.copy(self.instance.commandQueue[0])
        self.instance.main_loop()
        try:
            self.instance.commandQueue[0]
            self.fail("head is not executed")
            self.instance.myTimer.cancel()
        except IndexError:
            self.assertTrue(True,True)
            self.instance.myTimer.cancel()
    #main_loop: if commandQueue.length == 0 nothing should happen
    def test_empty_queue_behaviour(self):
        self.instance = CommandManager()
        startQue = copy.copy(self.instance.commandQueue)
        self.instance.main_loop()
        endQue = copy.copy(self.instance.commandQueue)
        self.assertTrue((startQue == endQue), True)
        self.instance.myTimer.cancel()

    #main_loop: if commandQueue.length > 1 the  timer should be updated
    def test_is_myTimer_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        command2 = ICommand(datetime(2018,1,5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        startTimer = copy.copy(self.instance.myTimer)
        self.instance.main_loop
        endTimer = copy.copy(self.instance.myTimer)

        self.assertTrue((startTimer != endTimer), True)
        self.instance.myTimer.cancel()
    #main_loop: if commandQueue.length == 1 the timer should not be updated
    def test_myTimer_is_not_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017,1,5))
        self.instance.enqueue_command(command)

        startTimer = self.instance.myTimer
        self.instance.main_loop()
        endTimer = self.instance.myTimer

        self.assertTrue((startTimer == endTimer), True)
        self.instance.myTimer.cancel()
 def setUp(self):
     self.instance = CommandManager()
     self.instance.myTimer.cancel()
 def test_init(self):
     self.instance = CommandManager()
     self.assertTrue(type(self.instance),CommandManager)
     self.instance.myTimer.cancel()
 def test_contains_commandQueue(self):
     self.instance = CommandManager()
     self.assertTrue(type(self.instance.commandQueue),list)
     self.instance.myTimer.cancel()
 def test_is_commandQueue_empty(self):
     self.instance = CommandManager()
     self.instance.myTimer.cancel()
示例#38
0
 def __init__(self):
     self.myCommandmanager = CommandManager()
     self.myCommandFactory = CommandFactory()
示例#39
0
class Test_CommandManager(ut.TestCase):
    def setUp(self):
        self.instance = CommandManager()
        self.instance.myTimer.cancel()

    #__init__: inits
    def test_init(self):
        self.instance = CommandManager()
        self.assertTrue(type(self.instance), CommandManager)
        self.instance.myTimer.cancel()

    #__init__: contains commandQueue
    def test_contains_commandQueue(self):
        self.instance = CommandManager()
        self.assertTrue(type(self.instance.commandQueue), list)
        self.instance.myTimer.cancel()

    #__init__: commandQueue is empty on init
    def test_is_commandQueue_empty(self):
        self.instance = CommandManager()
        self.instance.myTimer.cancel()

    #__init__: contains myTimer
    def test_contains_myTimer(self):
        self.instance = CommandManager()
        self.assertTrue(type(self.instance.myTimer), datetime)
        self.instance.myTimer.cancel()

    #enqueue_command: commandQueue is +1 longer after enqueue_command
    def test_que_is_longer(self):
        self.instance = CommandManager()
        startLength = len(self.instance.commandQueue)
        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)
        endLength = len(self.instance.commandQueue)

        self.assertTrue((startLength != endLength), True)
        self.instance.myTimer.cancel()

    #enqueue_command: commandQueue contains the queued command
    def test_que_contains_new_command(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)
        self.assertTrue((command in self.instance.commandQueue), True)
        self.instance.myTimer.cancel()

    #delete_command: commandQueue is -1 longer after delete_command
    def test_que_is_shorter(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)

        startLength = len(self.instance.commandQueue)
        self.instance.delete_command(0)
        endLength = len(self.instance.commandQueue)

        self.assertFalse((startLength == endLength), False)
        self.instance.myTimer.cancel()

    #delete_command: commandQueue does not contain the deleted command
    def test_que_excludes_command(self):
        self.instance = CommandManager()
        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)

        startContains = (command in self.instance.commandQueue)
        self.instance.delete_command(0)
        endContains = (command in self.instance.commandQueue)

        self.assertFalse(endContains, startContains)
        self.instance.myTimer.cancel()

    #create_new_timer: sets a new timer
    def test_sets_new_timer(self):
        self.instance = CommandManager()
        oldTimer = copy.copy(self.instance.myTimer)
        command = ICommand(datetime(2017, 1, 5))

        self.instance.commandQueue.append(command)
        self.instance.create_new_timer()
        newTimer = copy.copy(self.instance.myTimer)

        self.assertFalse((oldTimer == newTimer), False)
        self.instance.myTimer.cancel()

    #execute_command: Head is not the same after execute has been run
    def test_head_is_not_same(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        command2 = ICommand(datetime(2018, 1, 5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        oldHead = (self.instance.commandQueue[:])[0]
        self.instance.execute_command()
        startHead = (self.instance.commandQueue[:])[0]
        self.assertTrue((oldHead != startHead), True)
        self.instance.myTimer.cancel()

    #execute_command: myTimer is updated after execute has been run
    def test_myTimer_is_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        command2 = ICommand(datetime(2018, 1, 5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        startTimer = copy.copy(self.instance.myTimer)
        self.instance.execute_command()
        endTimer = copy.copy(self.instance.myTimer)

        self.assertTrue((startTimer != endTimer), True)
        self.instance.myTimer.cancel()

    #main_loop: if there is something in the que it should be executed
    def test_is_head_executed(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)
        head = copy.copy(self.instance.commandQueue[0])
        self.instance.main_loop()
        try:
            self.instance.commandQueue[0]
            self.fail("head is not executed")
            self.instance.myTimer.cancel()
        except IndexError:
            self.assertTrue(True, True)
            self.instance.myTimer.cancel()

    #main_loop: if commandQueue.length == 0 nothing should happen
    def test_empty_queue_behaviour(self):
        self.instance = CommandManager()
        startQue = copy.copy(self.instance.commandQueue)
        self.instance.main_loop()
        endQue = copy.copy(self.instance.commandQueue)
        self.assertTrue((startQue == endQue), True)
        self.instance.myTimer.cancel()

    #main_loop: if commandQueue.length > 1 the  timer should be updated
    def test_is_myTimer_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        command2 = ICommand(datetime(2018, 1, 5))
        self.instance.enqueue_command(command)
        self.instance.enqueue_command(command2)

        startTimer = copy.copy(self.instance.myTimer)
        self.instance.main_loop
        endTimer = copy.copy(self.instance.myTimer)

        self.assertTrue((startTimer != endTimer), True)
        self.instance.myTimer.cancel()

    #main_loop: if commandQueue.length == 1 the timer should not be updated
    def test_myTimer_is_not_updated(self):
        self.instance = CommandManager()

        command = ICommand(datetime(2017, 1, 5))
        self.instance.enqueue_command(command)

        startTimer = self.instance.myTimer
        self.instance.main_loop()
        endTimer = self.instance.myTimer

        self.assertTrue((startTimer == endTimer), True)
        self.instance.myTimer.cancel()
示例#40
0
 def setUp(self):
     self.instance = CommandManager()
     self.instance.myTimer.cancel()
示例#41
0
 def __init__(self):
     super(ServerManagerCLI,
           self).__init__(description='Server Manager CLI',
                          version='0.1',
                          command_manager=CommandManager('smgrcli.app'))
     self.command_manager.add_command_group('smgr.cli.common')
 def test_contains_myTimer(self):
     self.instance = CommandManager()
     self.assertTrue(type(self.instance.myTimer),datetime)
     self.instance.myTimer.cancel()