def test_list_feeds(self): another_chan = self.server.get_channel_by_address("another_channel") # Get feed list rss_check_class = self.function_dispatcher.get_function_by_name("check subscription") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: SubscriptionCheck rfl = rss_check_obj.get_sub_repo(self.hallo) # Add RSS feeds to feed list rf1 = RssSub(self.server, self.test_chan, "http://spangle.org.uk/hallo/test_rss.xml?1", title="test_feed1", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf1) rf2 = RssSub(self.server, another_chan, "http://spangle.org.uk/hallo/test_rss.xml?2", title="test_feed2", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf2) rf3 = RssSub(self.server, self.test_chan, "http://spangle.org.uk/hallo/test_rss.xml?3", title="test_feed3", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf3) # Run FeedList and check output self.function_dispatcher.dispatch(EventMessage(self.server, self.test_chan, self.test_user, "rss list")) data = self.server.get_send_data(1, self.test_chan, EventMessage) data_split = data[0].text.split("\n") assert "subscriptions posting" in data_split[0].lower(), "Actual message: {}".format(data[0].text) assert "test_feed1" in data_split[1].lower() or "test_feed1" in data_split[2].lower() assert "test_feed3" in data_split[1].lower() or "test_feed3" in data_split[2].lower() assert "http://spangle.org.uk/hallo/test_rss.xml?1" in data_split[1].lower() or \ "http://spangle.org.uk/hallo/test_rss.xml?1" in data_split[2].lower() assert "http://spangle.org.uk/hallo/test_rss.xml?3" in data_split[1].lower() or \ "http://spangle.org.uk/hallo/test_rss.xml?3" in data_split[2].lower() assert "test_feed2" not in data_split[1].lower() and "test_feed2" not in data_split[2].lower() assert "http://spangle.org.uk/hallo/test_rss.xml?2" not in data_split[1].lower() and \ "http://spangle.org.uk/hallo/test_rss.xml?2" not in data_split[2].lower()
def test_xml(self): # Setup a feed list rfl = SubscriptionRepo() rf1 = RssSub(self.server, self.test_chan, "http://spangle.org.uk/hallo/test_rss.xml?1", title="test_feed1", update_frequency=Commons.load_time_delta("P0T3600S")) rfl.add_sub(rf1) rf2 = RssSub(self.server, self.test_chan, "http://spangle.org.uk/hallo/test_rss.xml?2", title="test_feed2", update_frequency=Commons.load_time_delta("P1TS")) rfl.add_sub(rf2) rf3 = RssSub(self.server, self.test_chan, "http://spangle.org.uk/hallo/test_rss.xml?3", title="test_feed3", update_frequency=Commons.load_time_delta("PT60S")) rfl.add_sub(rf3) # Save to XML and load try: try: os.rename("store/subscriptions.json", "store/subscriptions.json.tmp") except OSError: pass rfl.save_json() new_rfl = SubscriptionRepo.load_json(self.hallo) assert len(new_rfl.sub_list) == 3 finally: try: os.remove("store/subscriptions.json") except OSError: pass try: os.rename("store/subscriptions.json.tmp", "store/subscriptions.json") except OSError: pass
def test_remove_by_title(self): another_chan = self.server.get_channel_by_address("another_channel") # Get feed list rss_check_class = self.function_dispatcher.get_function_by_name("check subscription") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: SubscriptionCheck rfl = rss_check_obj.get_sub_repo(self.hallo) # Add RSS feeds to feed list rf1 = RssSub(self.server, self.test_chan, "http://spangle.org.uk/hallo/test_rss.xml?1", title="test_feed1", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf1) rf2 = RssSub(self.server, another_chan, "http://spangle.org.uk/hallo/test_rss.xml?2", title="test_feed1", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf2) rf3 = RssSub(self.server, self.test_chan, "http://spangle.org.uk/hallo/test_rss.xml?3", title="test_feed3", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf3) # Remove test feed self.function_dispatcher.dispatch(EventMessage(self.server, self.test_chan, self.test_user, "rss remove test_feed1")) data = self.server.get_send_data(1, self.test_chan, EventMessage) assert "removed rss subscription to test_feed1" in data[0].text.lower(), \ "Response did not contain expected string. Response was: {}".format(data[0].text) assert rf1 not in rfl.sub_list assert rf2 in rfl.sub_list assert rf3 in rfl.sub_list
def test_list_feeds(self): # Get feed list rss_check_class = self.function_dispatcher.get_function_by_name("e621 sub check") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: SubE621Check rfl = rss_check_obj.e621_sub_list # Add RSS feeds to feed list rf1 = E621Sub() rf1.search = "butt" rf1.server_name = self.server.name rf1.channel_name = self.test_chan.name rf1.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf1) rf2 = E621Sub() rf2.search = "deer" rf2.server_name = self.server.name rf2.channel_name = "another_channel" rf2.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf2) rf3 = E621Sub() rf3.search = "dragon" rf3.server_name = self.server.name rf3.channel_name = self.test_chan.name rf3.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf3) # Run FeedList and check output self.function_dispatcher.dispatch("e621 sub list", self.test_user, self.test_chan) data = self.server.get_send_data(1, self.test_chan, Server.MSG_MSG) data_split = data[0][0].split("\n") assert "e621 search subscriptions posting" in data_split[0].lower() assert "butt" in data_split[1].lower() or "butt" in data_split[2].lower() assert "deer" not in data_split[1].lower() and "deer" not in data_split[2].lower() assert "dragon" in data_split[1].lower() or "dragon" in data_split[2].lower()
def test_remove_no_match(self): # Get subscription list e621_check_class = self.function_dispatcher.get_function_by_name("e621 sub check") e621_check_obj = self.function_dispatcher.get_function_object(e621_check_class) # type: SubE621Check rfl = e621_check_obj.e621_sub_list # Add E621 searches to subscription list rf1 = E621Sub() rf1.search = "butt" rf1.server_name = self.server.name rf1.channel_name = self.test_chan.name rf1.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf1) rf2 = E621Sub() rf2.search = "deer" rf2.server_name = self.server.name rf2.channel_name = "another_channel" rf2.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf2) rf3 = E621Sub() rf3.search = "dragon" rf3.server_name = self.server.name rf3.channel_name = self.test_chan.name rf3.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf3) # Try to remove invalid search self.function_dispatcher.dispatch("e621 sub remove not_a_search", self.test_user, self.test_chan) data = self.server.get_send_data(1, self.test_chan, Server.MSG_MSG) assert "error" in data[0][0].lower() assert rf1 in rfl.sub_list assert rf2 in rfl.sub_list assert rf3 in rfl.sub_list
def run(self, line, user_obj, destination_obj): # See if last argument is check period. try: try_period = line.split()[-1] search_delta = Commons.load_time_delta(try_period) search = line[:-len(try_period)] except ISO8601ParseError: search = line search_delta = Commons.load_time_delta("PT300S") search = search.strip() # Get current RSS feed list function_dispatcher = user_obj.server.hallo.function_dispatcher sub_check_class = function_dispatcher.get_function_by_name("e621 sub check") sub_check_obj = function_dispatcher.get_function_object(sub_check_class) # type: SubE621Check e621_sub_list = sub_check_obj.e621_sub_list # type: E621SubList # Create new e621 search subscription e621_sub = E621Sub() e621_sub.server_name = user_obj.server.name e621_sub.search = search e621_sub.update_frequency = search_delta if destination_obj.is_channel(): e621_sub.channel_name = destination_obj.name else: e621_sub.user_name = destination_obj.name # Update feed first_results = e621_sub.check_subscription() # If no results, this is an invalid search subscription if len(first_results) == 0: return "Error, this does not appear to be a valid search, or does not have results." # Add new rss feed to list e621_sub_list.add_sub(e621_sub) # Save list e621_sub_list.to_xml() # Return output return "I have added new e621 subscription for the search \"" + e621_sub.search + "\""
def test_remove_multiple_matching_titles(self): # Get feed list rss_check_class = self.function_dispatcher.get_function_by_name("rss check") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: FeedCheck rfl = rss_check_obj.rss_feed_list # Add RSS feeds to feed list rf1 = RssFeed() rf1.url = "http://spangle.org.uk/hallo/test_rss.xml?1" rf1.title = "test_feed1" rf1.server_name = self.server.name rf1.channel_name = self.test_chan.name rf1.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_feed(rf1) rf2 = RssFeed() rf2.url = "http://spangle.org.uk/hallo/test_rss.xml?2" rf2.title = "test_feed1" rf2.server_name = self.server.name rf2.channel_name = "another_channel" rf2.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_feed(rf2) rf3 = RssFeed() rf3.url = "http://spangle.org.uk/hallo/test_rss.xml?3" rf3.title = "test_feed1" rf3.server_name = self.server.name rf3.channel_name = self.test_chan.name rf3.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_feed(rf3) # Remove test feed self.function_dispatcher.dispatch("rss remove test_feed1", self.test_user, self.test_chan) data = self.server.get_send_data(1, self.test_chan, Server.MSG_MSG) assert "error" in data[0][0].lower() assert rf1 in rfl.feed_list assert rf2 in rfl.feed_list assert rf3 in rfl.feed_list
def test_run_by_title(self): # Set up test servers and channels serv1 = ServerMock(self.hallo) serv1.name = "test_serv1" chan1 = serv1.get_channel_by_name("test_chan1") chan2 = serv1.get_channel_by_name("test_chan2") serv2 = ServerMock(self.hallo) serv2.name = "test_serv2" chan3 = serv2.get_channel_by_name("test_chan1") try: self.hallo.add_server(serv1) self.hallo.add_server(serv2) # Set up rss feeds rfl = RssFeedList() rf1 = RssFeed() rf1.url = "http://spangle.org.uk/hallo/test_rss.xml?1" rf1.title = "test_feed1" rf1.server_name = chan1.server.name rf1.channel_name = chan1.name rf1.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_feed(rf1) rf2 = RssFeed() rf2.url = "http://spangle.org.uk/hallo/test_rss.xml?2" rf2.title = "test_feed2" rf2.server_name = chan2.server.name rf2.channel_name = chan2.name rf2.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_feed(rf2) rf3 = RssFeed() rf3.url = "http://spangle.org.uk/hallo/test_rss.xml?3" rf3.title = "test_feed1" rf3.server_name = chan3.server.name rf3.channel_name = chan3.name rf3.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_feed(rf3) # Splice this rss feed list into the function dispatcher's rss check object rss_check_class = self.function_dispatcher.get_function_by_name("rss check") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: FeedCheck rss_check_obj.rss_feed_list = rfl # Invalid title self.function_dispatcher.dispatch("rss check Not a valid feed", self.test_user, self.test_chan) data = self.server.get_send_data(1, self.test_chan, Server.MSG_MSG) assert "error" in data[0][0].lower() # Correct title but wrong channel self.function_dispatcher.dispatch("rss check test_feed2", self.test_user, chan1) data = serv1.get_send_data(1, chan1, Server.MSG_MSG) assert "error" in data[0][0].lower() # Correct title check update self.function_dispatcher.dispatch("rss check test_feed2", self.test_user, chan2) data = serv1.get_send_data(1, chan2, Server.MSG_MSG) assert "feed updates were found" in data[0][0].lower() assert len(data[0][0].lower().split("\n")) == 4 # No updates rf2.title = "test_feed2" self.function_dispatcher.dispatch("rss check test_feed2", self.test_user, chan2) data = serv1.get_send_data(1, chan2, Server.MSG_MSG) assert "no updates" in data[0][0], "No further updates should be found." finally: self.hallo.remove_server(serv2) self.hallo.remove_server(serv1)
def run(self, line, user_obj, destination_obj=None): """WH40K Thought for the day. Format: thought_for_the_day""" thought_list = Commons.read_file_to_list('store/WH40K_ToTD2.txt') rand = Commons.get_random_int(0, len(thought_list) - 1)[0] if thought_list[rand][-1] not in ['.', '!', '?']: thought_list[rand] += "." return '"' + thought_list[rand] + '"'
def test_domain_name(self): url1 = "https://github.com/joshcoales" assert Commons.get_domain_name(url1) == "github", "Failed to get domain from url1" url2 = "http://spangle.org.uk/things/stuff/hallo.html.com" assert Commons.get_domain_name(url2) == "spangle", "Failed to get domain from url2" url3 = "irc://irc.freenode.net:6666" assert Commons.get_domain_name(url3) == "freenode", "Failed to get domain from url3" url4 = "http://www.longurlmaker.com/go?id=143GetShortyShrtndspread%2Bout1tprotractedlongishYepItlofty1stretch" \ "100RedirxMyURL1Sitelutionsspread%2Bout56706Ne1kfar%2Breachingstretchenlarged8U76SimURL01URLvi00distan" \ "tr1towering46URLcutNe14m3q5stringy0elongatedremote7RubyURLRubyURL0300lasting52ny54blnk.inRedirx0t0aks" \ "tretchedst765330DigBigf14922f8014v03121qeURl.ied99FhURL1MyURLFhURL8sustainedlingeringrunning07bYATUC6" \ "8yU7618farawaystretchedxlfarawaySHurlcU760stretched01drangyccmstretchkrunningrremote52ganglingMyURL81" \ "outstretchedTraceURL5aenduring60Is.gd5stretch69660Miniliengangling112vYATUC01drawn%2Bout29extensive1U" \ "RLcutc03ShredURLfspread%2Boutoutstretched1EzURLTinyURLhigh0301URL7WapURL0u7Redirx5229NutshellURLdrawn" \ "%2Boutwcfy68rangy4longish4SitelutionsG8LFwdURLe1stretchNanoRef56running2StartURLspun%2BoutShortURL165" \ "MooURL4bTightURL00URLPieprolongedWapURLw0TightURL61runningdistantShorl8951hw2MooURLelongatek8lofty1Ti" \ "nyURLc1qMetamark920bgelongate19n103c1dTinyLinkcontinuedlnk.in96591DecentURL0afar%2Breaching81elongish" \ "504zremotec0l0e0adistants11high04DecentURL2stretchYATUCSnipURLstringys7b8deepTightURL1PiURLpa7elongat" \ "edix0101Shim0Is.gdfar%2BreachingB65f8ctoweringNutshellURLWapURL1v9runningRubyURLURl.ie0ganglingEasyUR" \ "L1ShortURL161stringy0h8extensivePiURL14prolongedEzURLt710distant1100rNanoRefh5311450ShrinkURLFwdURL1m" \ "stretched119ganglingURLCuttera11fFhURL1b6tallFwdURLdlengthy110spun%2Bout7lastingf49Fly29loftyf5jXil0s" \ "pread%2Bout4lengthyrangystretch8up0URL.co.uklingeringegURLHawk48zlengthyb3prolonged58loftyg18drawn%2B" \ "outURLCutterURLHawk01cShortlinkshigh4remote1StartURLprolongedURLHawk0z03Shortlinks54gURLvi18elongated" \ "EasyURL18elongated04WapURL1lofty51spread%2Bout1Redirx1A2N5411zfar%2Breachingf001prolonged01a4dstretch" \ "sustainedoutstretchedShortURL612TraceURLURLvi00lasting28ec1URLcutcstringy827klengthyk1141DigBig9fcSHu" \ "rl1Beam.toShorl0tstretchxURLCutterYepItnblasting080stretched1FhURL15rangy1x6600continuedShredURLblnk." \ "inelongated00413outstretched0090146stretched589z05stringyc8sdielongatelongish6kprolongedfar%2Breachin" \ "gf36ubaTinyURL1TinyLink341028017EasyURLd1runningfar%2Breaching06stretching1U76spun%2Bout1cstretch" assert Commons.get_domain_name(url4) == "longurlmaker", "Failed to get domain from url4" url5 = "http://domains.ninja" assert Commons.get_domain_name(url5) == "domains", "Failed to get domain from url5"
def test_format_unix_time(self): unix1 = 0 assert Commons.format_unix_time(unix1) == "1970-01-01 00:00:00" unix2 = 1000000000 assert Commons.format_unix_time(unix2) == "2001-09-09 01:46:40" unix3 = 1234567890 assert Commons.format_unix_time(unix3) == "2009-02-13 23:31:30"
def test_chunk_string(self): chunks = Commons.chunk_string("a"*500, 100) assert len(chunks) == 5, "Did not return correct number of chunks" for chunk in chunks: assert len(chunk) <= 100, "Chunk of string is too long" chunks = Commons.chunk_string("", 100) assert len(chunks) == 0, "Did not handle empty string correctly."
def run(self, event): """ Say a message into a channel or server/channel pair (in the format "{server,channel}"). Format: say <channel> <message> """ # Setting up variables line = event.command_args hallo_obj = event.server.hallo # See if server and channel are specified as parameters server_name = Commons.find_parameter("server", line) if server_name is not None: line = line.replace("server={}".format(server_name), "").strip() channel_name = Commons.find_parameter("channel", line) if channel_name is not None: line = line.replace("channel={}".format(channel_name), "").strip() # If channel_name is not found as a parameter, see if server/channel is given as a first argument pair. if channel_name is None: destination_pair = line.split()[0] line = line[len(destination_pair):].strip() destination_separators = ["->", ">", ",", ".", "/", ":"] for destination_separator in destination_separators: if destination_pair.count(destination_separator) != 0: server_name = destination_pair.split(destination_separator)[0] channel_name = destination_pair.split(destination_separator)[1] break if channel_name is None: channel_name = destination_pair # Get server_obj list from server_name server_objs = [] if server_name is None: server_objs = [event.server] else: # Create a regex query from their input server_regex = re.escape(server_name).replace(r"\*", ".*") server_list = hallo_obj.server_list for server_obj in server_list: if not server_obj.is_connected(): continue if re.match(server_regex, server_obj.name, re.IGNORECASE): server_objs.append(server_obj) # If server is not recognised or found, respond with an error if len(server_objs) == 0: return event.create_response("Unrecognised server.") # Get channel_obj list from server_obj and channel_name channel_objs = [] for server_obj in server_objs: channel_regex = re.escape(channel_name).replace(r"\*", ".*") channel_list = server_obj.channel_list for channel_obj in channel_list: if not channel_obj.in_channel: continue if re.match(channel_regex, channel_obj.name, re.IGNORECASE): channel_objs.append(channel_obj) # If no channels were found that match, respond with an error if len(channel_objs) == 0: return event.create_response("Unrecognised channel.") # Send message to all matching channels for channel_obj in channel_objs: event.server.send(EventMessage(event.server, channel_obj, None, line, inbound=False)) return event.create_response("Message sent.")
def test_is_string_null(self): valid = ['0', 'false', 'off', 'disabled', 'disable', '', 'nul', 'null', 'none', 'nil'] invalid = ["true", "enable", "hello", "example", "test"] for valid_str in valid: assert Commons.is_string_null(valid_str), "Valid string judged to be not null, "+valid_str for invalid_str in invalid: assert not Commons.is_string_null(invalid_str), "Invalid string judged to be null, "+invalid_str
def create_from_input(input_evt, sub_repo): # Get event data server = input_evt.server destination = input_evt.channel if input_evt.channel is not None else input_evt.user clean_text = input_evt.command_args.strip().lower() text_split = clean_text.split() # Subreddit regex sub_regex = re.compile(r"r/([^\s]*)/?") if len(text_split) == 1: sub_name = clean_text if sub_regex.search(clean_text) is None else sub_regex.search(clean_text).group(1) reddit_sub = RedditSub(server, destination, sub_name) reddit_sub.check() return reddit_sub if len(text_split) > 2: raise SubscriptionException("Too many arguments. Please give a subreddit, and optionally, a check period.") try: search_delta = Commons.load_time_delta(text_split[0]) subreddit = text_split[1] except ISO8601ParseError: subreddit = text_split[0] search_delta = Commons.load_time_delta(text_split[1]) sub_name = clean_text if sub_regex.search(subreddit) is None else sub_regex.search(subreddit).group(1) reddit_sub = RedditSub(server, destination, sub_name, update_frequency=search_delta) reddit_sub.check() return reddit_sub
def run(self, line, user_obj, destination_obj=None): input_clean = line.strip().lower() url = "http://api.randomuser.me/0.6/?nat=gb&format=json" # Get api response json_dict = Commons.load_url_json(url) user_dict = json_dict['results'][0]['user'] # Construct response name = (user_dict['name']['title'] + " " + user_dict['name']['first'] + " " + user_dict['name']['last']).title() email = user_dict['email'] address = user_dict['location']['street'].title() + ", " address += user_dict['location']['city'].title() + ", " address += user_dict['location']['postcode'] username = user_dict['username'] password = user_dict['password'] date_of_birth = Commons.format_unix_time(int(user_dict['dob'])) phone_home = user_dict['phone'] phone_mob = user_dict['cell'] national_insurance = user_dict['NINO'] pronoun = "he" if user_dict['gender'] == "male" else "she" pronoun_possessive = "his" if user_dict['gender'] == "male" else "her" if input_clean not in ["more", "full", "verbose", "all"]: output = "I have generated this person: Say hello to " + name + ". " output += pronoun.title() + " was born at " + date_of_birth + "." return output output = "I have generated this person: Say hello to " + name + ". " output += pronoun.title() + " was born at " + date_of_birth + " and lives at " + address + ". " output += pronoun.title() + " uses the email " + email + ", the username \"" + username + \ "\" and usually uses the password \"" + password + "\". " output += pronoun_possessive.title() + " home number is " + phone_home + " but " output += pronoun_possessive + " mobile number is " + phone_mob + ". " output += pronoun_possessive + " national insurance number is " + national_insurance + "." return output
def test_check_calculation(self): valid = ["23", "2.123", "cos(12.2)", "tan(sin(atan(cosh(1))))", "pie", "1+2*3/4^5%6", "gamma(17)"] invalid = ["hello", "1&2", "$13.50", "1::", "cos(tan(12+t+15))"] for valid_str in valid: assert Commons.check_calculation(valid_str), "Valid string judged to be not calculation, "+valid_str for invalid_str in invalid: assert not Commons.check_calculation(invalid_str), "Invalid string judged to be calculation, "+invalid_str
def run(self, line, user_obj, destination_obj=None): # Get server object server_obj = user_obj.server # If no arguments given, turn the password for current channel off. line_clean = line.strip() if line_clean == '': destination_obj.password = None return "Channel password disabled." # If line has 1 argument, set password for current channel line_split = line_clean.split() if len(line_split) == 1: # Check if null was specified input_null = Commons.is_string_null(line_split[0]) if input_null: destination_obj.password = None return "Channel password disabled." else: destination_obj.password = line_split[0] return "Channel password set." # Otherwise line has 2 or more arguments. # Assume first is channel, and second is password. input_null = Commons.is_string_null(line_split[1]) target_channel_name = line_split[0] target_channel = server_obj.get_channel_by_name(target_channel_name) if input_null: target_channel.password = None return "Channel password disabled for " + target_channel.name + "." else: target_channel.password = line_split[1] return "Channel password set for " + target_channel.name + "."
def test_is_float_string(self): valid = ["23", "2.123", " 97"] invalid = ["127.0.0.1", "cos(12.2)", "tan(sin(atan(cosh(1))))", "pie", "1+2*3/4^5%6", "gamma(17)", "hello", "1&2", "$13.50", "1::", "cos(tan(12+t+15))", "9 7"] for valid_str in valid: assert Commons.is_float_string(valid_str), "Valid string judged to be not float, "+valid_str for invalid_str in invalid: assert not Commons.is_float_string(invalid_str), "Invalid string judged to be float, "+invalid_str
def run(self, line, user_obj, destination_obj=None): word_list = Commons.read_file_to_list('store/ouija_wordlist.txt') rand_list = Commons.get_random_int(0, len(word_list) - 1, 4) num_words = (rand_list[0] % 3) + 1 output_string = "I'm getting a message from the other side..." output_string += " ".join([word_list[rand_list[x + 2]] for x in range(num_words)]) output_string += "." return output_string
def test_run_by_search(self): # Set up test servers and channels serv1 = ServerMock(self.hallo) serv1.name = "test_serv1" chan1 = serv1.get_channel_by_name("test_chan1") chan2 = serv1.get_channel_by_name("test_chan2") serv2 = ServerMock(self.hallo) serv2.name = "test_serv2" chan3 = serv2.get_channel_by_name("test_chan1") try: self.hallo.add_server(serv1) self.hallo.add_server(serv2) # Set up rss feeds rfl = E621SubList() rf1 = E621Sub() rf1.search = "butt" rf1.server_name = chan1.server.name rf1.channel_name = chan1.name rf1.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf1) rf2 = E621Sub() rf2.search = "deer" rf2.server_name = chan2.server.name rf2.channel_name = chan2.name rf2.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf2) rf3 = E621Sub() rf3.search = "dragon" rf3.server_name = chan3.server.name rf3.channel_name = chan3.name rf3.update_frequency = Commons.load_time_delta("PT3600S") rfl.add_sub(rf3) # Splice this rss feed list into the function dispatcher's rss check object rss_check_class = self.function_dispatcher.get_function_by_name("e621 sub check") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: SubE621Check rss_check_obj.e621_sub_list = rfl # Invalid title self.function_dispatcher.dispatch("e621 sub check Not a valid search", self.test_user, self.test_chan) data = self.server.get_send_data(1, self.test_chan, Server.MSG_MSG) assert "error" in data[0][0].lower() # Correct title but wrong channel self.function_dispatcher.dispatch("e621 sub check deer", self.test_user, chan1) data = serv1.get_send_data(1, chan1, Server.MSG_MSG) assert "error" in data[0][0].lower() # Correct title check update self.function_dispatcher.dispatch("e621 sub check deer", self.test_user, chan2) data = serv1.get_send_data(1, chan2, Server.MSG_MSG) assert "search updates were found" in data[0][0].lower() assert len(data[0][0].lower().split("\n")) == 51 # No updates self.function_dispatcher.dispatch("e621 sub check deer", self.test_user, chan2) data = serv1.get_send_data(1, chan2, Server.MSG_MSG) assert "no updates" in data[0][0], "No further updates should be found." finally: self.hallo.remove_server(serv2) self.hallo.remove_server(serv1)
def test_string_to_bool(self): true_list = ['1', 'true', 't', 'yes', 'y', 'on', 'enabled', 'enable'] for true_str in true_list: assert Commons.string_to_bool(true_str) false_list = ['0', 'false', 'f', 'no', 'n', 'off', 'disabled', 'disable'] for false_str in false_list: assert not Commons.string_to_bool(false_str) invalid_list = ["hello", "example", "test"] for invalid_str in invalid_list: assert Commons.string_to_bool(invalid_str) is None
def log_ctcp(self, full_line, server_obj, user_obj, channel_obj): ctcp_command = full_line.split()[0] ctcp_arguments = ' '.join(full_line.split()[1:]) if ctcp_command.lower() == "action": output = Commons.current_timestamp() + " " output += "**" + user_obj.get_name() + ' ' + ctcp_arguments + '**' return output output = Commons.current_timestamp() + " " output += "<" + user_obj.get_name() + ' (CTCP)> ' + full_line return output
def test_load_time_delta(self): string1 = "20S" try: Commons.load_time_delta(string1) assert False, "String 1 should have failed to parse." except ISO8601ParseError: pass string2 = "P20" try: Commons.load_time_delta(string2) assert False, "String 2 should have failed to parse." except ISO8601ParseError: pass string3 = "P20S" try: Commons.load_time_delta(string3) assert False, "String 3 should have failed to parse." except ISO8601ParseError: pass string4 = "PTS" delta4 = Commons.load_time_delta(string4) assert delta4.seconds == 0, "delta4 seconds set incorrectly." assert delta4.days == 0, "delta4 days set incorrectly." string5 = "P1T1S" delta5 = Commons.load_time_delta(string5) assert delta5.seconds == 1, "delta5 seconds set incorrectly." assert delta5.days == 1, "delta5 days set incorrectly." string6 = "P10T3600S" delta6 = Commons.load_time_delta(string6) assert delta6.seconds == 3600, "delta6 seconds set incorrectly." assert delta6.days == 10, "delta6 days set incorrectly."
def test_format_time_delta(self): delta1 = timedelta(5, 5) assert Commons.format_time_delta(delta1) == "P5T5S" delta2 = timedelta(0, 50) assert Commons.format_time_delta(delta2) == "P0T50S" delta3 = timedelta(3, 0, 0, 0, 1) assert Commons.format_time_delta(delta3) == "P3T60S" delta4 = timedelta(2, 0, 0, 0, 0, 1) assert Commons.format_time_delta(delta4) == "P2T3600S" delta5 = timedelta(0, 0, 0, 0, 0, 0, 1) assert Commons.format_time_delta(delta5) == "P7T0S"
def test_run_all(self): # Set up test servers and channels serv1 = ServerMock(self.hallo) serv1.name = "test_serv1" chan1 = serv1.get_channel_by_address("test_chan1".lower(), "test_chan1") chan2 = serv1.get_channel_by_address("test_chan2".lower(), "test_chan2") serv2 = ServerMock(self.hallo) serv2.name = "test_serv2" chan3 = serv2.get_channel_by_address("test_chan1".lower(), "test_chan1") try: self.hallo.add_server(serv1) self.hallo.add_server(serv2) # Set up rss feeds rfl = SubscriptionRepo() rf1 = RssSub(chan1.server, chan1, "http://spangle.org.uk/hallo/test_rss.xml?1", title="test_feed1", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf1) rf2 = RssSub(chan2.server, chan2, "http://spangle.org.uk/hallo/test_rss.xml?2", title="test_feed2", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf2) rf3 = RssSub(chan3.server, chan3, "http://spangle.org.uk/hallo/test_rss.xml?3", title="test_feed1", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf3) # Splice this rss feed list into the function dispatcher's rss check object rss_check_class = self.function_dispatcher.get_function_by_name("check subscription") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: SubscriptionCheck rss_check_obj.subscription_repo = rfl # Test running all feed updates self.function_dispatcher.dispatch(EventMessage(self.server, self.test_chan, self.test_user, "rss check all")) # Check original calling channel data serv0_data = self.server.get_send_data(1, self.test_chan, EventMessage) assert "subscription updates were found" in serv0_data[0].text # Check test server 1 data serv1_data = serv1.get_send_data(6) chan1_count = 0 chan2_count = 0 for data_line in serv1_data: if data_line.channel == chan1: chan1_count += 1 if data_line.channel == chan2: chan2_count += 1 assert chan1_count == 3 assert chan2_count == 3 # Check test server 2 data serv2.get_send_data(3, chan3, EventMessage) # Test running with no new updates. self.function_dispatcher.dispatch(EventMessage(self.server, self.test_chan, self.test_user, "rss check all")) data = self.server.get_send_data(1, self.test_chan, EventMessage) assert "no updates" in data[0].text, "No further updates should be found." finally: self.hallo.remove_server(serv2) self.hallo.remove_server(serv1)
def run(self, event): rgb_list = Commons.get_random_int(0, 255, 3) hex_code = "{}{}{}".format(hex(rgb_list[0])[2:].zfill(2), hex(rgb_list[1])[2:].zfill(2), hex(rgb_list[2])[2:].zfill(2)).upper() url = "https://www.thecolorapi.com/id?hex={}".format(hex_code) human_url = "{}&format=html".format(url) colour_data = Commons.load_url_json(url) colour_name = colour_data["name"]["value"] output = "Randomly chosen colour is: {} #{} or rgb({},{},{}) {}".format(colour_name, hex_code, rgb_list[0], rgb_list[1], rgb_list[2], human_url) return event.create_response(output)
def test_run_by_title(self): # Set up test servers and channels serv1 = ServerMock(self.hallo) serv1.name = "test_serv1" chan1 = serv1.get_channel_by_address("test_chan1") chan2 = serv1.get_channel_by_address("test_chan2") user1 = serv1.get_user_by_address("test_user1") serv2 = ServerMock(self.hallo) serv2.name = "test_serv2" chan3 = serv2.get_channel_by_address("test_chan1") try: self.hallo.add_server(serv1) self.hallo.add_server(serv2) # Set up rss feeds rfl = SubscriptionRepo() rf1 = RssSub(chan1.server, chan1, "http://spangle.org.uk/hallo/test_rss.xml?1", title="test_feed1", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf1) rf2 = RssSub(chan2.server, chan2, "http://spangle.org.uk/hallo/test_rss.xml?2", title="test_feed2", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf2) rf3 = RssSub(chan3.server, chan3, "http://spangle.org.uk/hallo/test_rss.xml?3", title="test_feed1", update_frequency=Commons.load_time_delta("PT3600S")) rfl.add_sub(rf3) # Splice this rss feed list into the function dispatcher's rss check object rss_check_class = self.function_dispatcher.get_function_by_name("check subscription") rss_check_obj = self.function_dispatcher.get_function_object(rss_check_class) # type: SubscriptionCheck rss_check_obj.subscription_repo = rfl # Invalid title self.function_dispatcher.dispatch(EventMessage(self.server, self.test_chan, self.test_user, "rss check Not a valid feed")) data = self.server.get_send_data(1, self.test_chan, EventMessage) assert "error" in data[0].text.lower() # Correct title but wrong channel self.function_dispatcher.dispatch(EventMessage(serv1, chan1, user1, "rss check test_feed2")) data = serv1.get_send_data(1, chan1, EventMessage) assert "error" in data[0].text.lower() # Correct title check update self.function_dispatcher.dispatch(EventMessage(serv1, chan2, user1, "rss check test_feed2")) data = serv1.get_send_data(4, chan2, EventMessage) for x in range(3): assert "update on" in data[x].text.lower() assert "rss feed" in data[x].text.lower() assert "updates were found" in data[3].text.lower(), "Actual message: {}".format(data[0].text) # No updates rf2.title = "test_feed2" self.function_dispatcher.dispatch(EventMessage(serv1, chan2, user1, "rss check test_feed2")) data = serv1.get_send_data(1, chan2, EventMessage) assert "no updates" in data[0].text, "No further updates should be found." finally: self.hallo.remove_server(serv2) self.hallo.remove_server(serv1)
def test_string_from_file(self): true_list = ['1', 'true', 't', 'yes', 'y', 'on', 'enabled', 'enable'] for true_str in true_list: assert Commons.string_from_file(true_str) false_list = ['0', 'false', 'f', 'no', 'n', 'off', 'disabled', 'disable'] for false_str in false_list: assert not Commons.string_from_file(false_str) null_list = ['', 'nul', 'null', 'none', 'nil'] for null_str in null_list: assert Commons.string_from_file(null_str) is None invalid_list = ["hello", "example", "test"] for invalid_str in invalid_list: assert Commons.string_from_file(invalid_str) == invalid_str
def test_load_url_string(self): url1 = "https://httpbin.org/get" data1 = Commons.load_url_string(url1) data1split = data1.split("\n") assert data1split[0] == "{", "First line incorrect." assert data1split[1] == " \"args\": {}, ", "String response incorrect." url2 = "https://httpbin.org/headers" headers2 = [["User-Agent", "Example data"]] data2 = Commons.load_url_string(url2, headers2) data2split = data2.split("\n") assert data2split[0] == "{", "First line incorrect." assert data2split[1] == " \"headers\": {", "String response incorrect." assert "\"User-Agent\": \"Example data\"" in data2, "Headers missing from request."