Best Python code snippet using slash
monitor.py
Source:monitor.py
1#!/usr/bin/env python2import smtplib3import os4import subprocess5import time6import datetime7from configuration import settings, sites8from sys import platform as system_platform9class Color(object):10 """11 Colorize strings in terminal12 """13 RED = '\033[31m'14 GREEN = '\033[32m'15 YELLOW = '\033[33m'16 BLUE = '\033[34m'17 RESET = '\033[0m'18 def __init__(self):19 # Check if the system is windows, as ANSI escape codes do not work there20 self.should_colorize = True21 if system_platform == "win32":22 self.should_colorize = False23 def red(self, string):24 """25 Turns a string red26 """27 if not self.should_colorize:28 return string29 return "%s%s%s" % (self.RED, string, self.RESET)30 def green(self, string):31 """32 Turns a string green33 """34 if not self.should_colorize:35 return string36 return "%s%s%s" % (self.GREEN, string, self.RESET)37 def blue(self, string):38 """39 Turns a string blue40 """41 if not self.should_colorize:42 return string43 return "%s%s%s" % (self.BLUE, string, self.RESET)44 def yellow(self, string):45 """46 Turns a string yellow47 """48 if not self.should_colorize:49 return string50 return "%s%s%s" % (self.YELLOW, string, self.RESET)51class UptimeLogger(object):52 """53 Creates a file to check the last status of the hostname. Works by creating a file when the site is down54 and removing it when it is up55 """56 def __init__(self, hostname):57 # Set the file name58 self.file_location = os.path.join(os.getcwd(), 'down_sites_list.txt')59 self.hostname = hostname60 # Create the down site file if it does not exist61 if not os.path.isfile(self.file_location):62 open(self.file_location, 'w+').close()63 def was_up(self):64 """65 Checks if the site was up last time. Returns a boolean66 """67 site_list = open(self.file_location, 'r')68 down_sites = site_list.readlines()69 site_list.close()70 # Check if the site was down71 for site in down_sites:72 if site.strip() == self.hostname:73 # The hostname was found in the file, which means it was down previously74 return False75 # The hostname was not found in the file76 return True77 def mark_down(self):78 """79 Mark the site as down80 """81 # Check if the file already exists in the list82 if not self.was_up():83 return84 site_list = open(self.file_location, 'a')85 site_list.write(self.hostname + "\n")86 site_list.close()87 def mark_up(self):88 """89 Mark the site as up90 """91 # Check if the site was not in the list initially92 if self.was_up():93 return94 site_list = open(self.file_location, 'r')95 down_sites = site_list.readlines()96 site_list.close()97 new_sites_list = []98 for site in down_sites:99 # Check for the site and remove it if found100 if site.strip() == self.hostname:101 continue102 new_sites_list.append(site)103 # Write the new list104 site_list = open(self.file_location, 'w')105 site_list.writelines(new_sites_list)106 site_list.close()107class UptimeChecker(object):108 """109 Checks the uptime of a site110 """111 def __init__(self, hostname):112 self.hostname = hostname113 self.check_up()114 def check_up(self):115 """116 Checks if the site is up and sets the class variables did_change and is_up117 """118 process = subprocess.Popen(119 'ping -c 1 ' + self.hostname,120 stdout=subprocess.PIPE,121 stderr=subprocess.PIPE,122 shell=True123 )124 process.wait()125 uptime_logger = UptimeLogger(self.hostname)126 self.did_change = False127 color = Color()128 if process.returncode == 0:129 # If the site is up, check if the site was previously down130 self.is_up = True131 if uptime_logger.was_up():132 # The site is still up133 print color.blue("Site %s is still up" % self.hostname)134 else:135 # The site went from down to up136 print color.green("Site %s went back up" % self.hostname)137 self.did_change = True138 uptime_logger.mark_up()139 else:140 # If the site was not previously down, send the email141 self.is_up = False142 if uptime_logger.was_up():143 # Site went down144 print color.red("Site %s went down" % self.hostname)145 self.did_change = True146 uptime_logger.mark_down()147 else:148 # Site is still down149 print color.yellow("Site %s is still down" % self.hostname)150 return self.is_up151ts = time.time()152st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')153"""Sends an e-mail to the specified recipient."""154sender = settings["monitor_email"]155recipient = settings["recipient_email"]156subject = settings["email_subject"]157headers = ["From: " + sender,158 "Subject: " + subject,159 "To: " + recipient,160 "MIME-Version: 1.0",161 "Content-Type: text/html"]162headers = "\r\n".join(headers)163session = smtplib.SMTP(settings["monitor_server"], settings["monitor_server_port"])164session.ehlo()165session.starttls()166session.ehlo()167session.login(settings["monitor_email"], settings["monitor_password"])168for site in sites:169 checker = UptimeChecker(site)170 # The site status changed from it's last value, so send an email171 if checker.did_change:172 if checker.is_up:173 # The site went back up174 body = "%s went back up at %s" % (site, st)175 session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)176 else:177 # The site went down178 body = "%s went down at %s" % (site, st)179 session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)...
test_add_option_colorize.py
Source:test_add_option_colorize.py
...109def test_pycharm_fixed(monkeypatch, stream):110 monkeypatch.setitem(os.environ, "PYCHARM_HOSTED", "1")111 monkeypatch.setattr(stream, "isatty", lambda: False)112 assert not stream.isatty()113 assert loguru._colorama.should_colorize(stream)114@pytest.mark.parametrize("stream", [None, Stream(False), Stream(None)])115def test_pycharm_ignored(monkeypatch, stream):116 monkeypatch.setitem(os.environ, "PYCHARM_HOSTED", "1")117 assert not loguru._colorama.should_colorize(stream)118@pytest.mark.parametrize("stream", [sys.__stdout__, sys.__stderr__])119def test_mintty_fixed_windows(monkeypatch, stream):120 monkeypatch.setattr(os, "name", "nt")121 monkeypatch.setitem(os.environ, "TERM", "xterm")122 monkeypatch.setattr(stream, "isatty", lambda: False)123 assert not stream.isatty()124 assert loguru._colorama.should_colorize(stream)125@pytest.mark.parametrize("stream", [None, Stream(False), Stream(None)])126def test_mintty_ignored_windows(monkeypatch, stream):127 monkeypatch.setattr(os, "name", "nt")128 monkeypatch.setitem(os.environ, "TERM", "xterm")129 assert not loguru._colorama.should_colorize(stream)130@pytest.mark.parametrize("stream", [sys.__stdout__, sys.__stderr__])131def test_mintty_not_fixed_linux(monkeypatch, stream):132 monkeypatch.setattr(os, "name", "posix")133 monkeypatch.setitem(os.environ, "TERM", "xterm")134 monkeypatch.setattr(stream, "isatty", lambda: False)135 assert not stream.isatty()136 assert not loguru._colorama.should_colorize(stream)137@pytest.mark.parametrize("stream", [None, Stream(False), Stream(None)])138def test_mintty_ignored_linux(monkeypatch, stream):139 monkeypatch.setattr(os, "name", "posix")140 monkeypatch.setitem(os.environ, "TERM", "xterm")...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!