class TestMECONotifier(unittest.TestCase):
    """
    Unit tests for the MECO Notifier.
    """

    def setUp(self):
        self.logger = SEKLogger(__name__)
        self.notifier = MSGNotifier()
        self.configer = MSGConfiger()

    def tearDown(self):
        pass

    def testInit(self):
        self.assertIsNotNone(self.notifier, "Notifier has been initialized.")

    def testEmailServer(self):
        """
        Test connecting to the email server.
        """

        errorOccurred = False
        user = self.configer.configOptionValue("Notifications", "email_username")
        password = self.configer.configOptionValue("Notifications", "email_password")

        server = smtplib.SMTP(self.configer.configOptionValue("Notifications", "smtp_server_and_port"))

        try:
            server.starttls()
        except smtplib.SMTPException as detail:
            self.logger.log("Exception: {}".format(detail))

        try:
            server.login(user, password)
        except smtplib.SMTPException as detail:
            self.logger.log("Exception: {}".format(detail))

        self.assertFalse(errorOccurred, "No errors occurred during SMTP setup.")

    def testSendEmailNotification(self):
        """
        Send a test notification by email.
        """

        if SEND_EMAIL:
            success = self.notifier.sendNotificationEmail(
                "This is a message from testSendEmailNotification.", testing=True
            )
            self.assertTrue(success, "Sending an email notification did not produce an" " exception.")
        else:
            self.assertTrue(True, "Email is not sent when SEND_EMAIL is False.")

    def testSendEmailAttachment(self):
        """
        Send a test notification with attachment by email.
        """

        if SEND_EMAIL:
            body = "Test message"
            testDataPath = self.configer.configOptionValue("Testing", "test_data_path")
            file = os.path.join(testDataPath, "graph.png")
            success = self.notifier.sendMailWithAttachments(body, [file], testing=True)
            success = success != True
            self.assertTrue(success, "Sending an email notification did not produce an" " exception.")
        else:
            self.assertTrue(True, "Email is not sent when SEND_EMAIL is False.")
Esempio n. 2
0
            sys.stderr.write("\n")
            msgBody += returnDict[key]

    except Exception as detail:
        msg = "\nAn exception occurred: {}\n".format(detail)
        logger.log(msg, 'error')
        msgBody += msg

    msgBody += "\n" + logLegend() + "\n"

    msg = "\nProcessed file count is %s.\n" % xmlGzCount
    logger.log(msg)
    msgBody += msg + "\n"

    plotter = MECOPlotting(COMMAND_LINE_ARGS.testing)

    try:
        plotter.plotReadingAndMeterCounts(databaseName)
        msg = "\nPlot is attached.\n"
    except Exception, e:
        msg = "\nAn exception occurred: Failed to generate plot: %s\n" % e
        logger.log(msg, 'error')

    msgBody += msg

    if COMMAND_LINE_ARGS.email:
        notifier.sendMailWithAttachments(msgBody, makePlotAttachments(),
                                         COMMAND_LINE_ARGS.testing)

    logger.log("msgBody = %s" % msgBody)
            sys.stderr.write("\n")
            msgBody += returnDict[key]

    except Exception as detail:
        msg = "\nAn exception occurred: {}\n".format(detail)
        logger.log(msg, 'error')
        msgBody += msg

    msgBody += "\n" + logLegend() + "\n"

    msg = "\nProcessed file count is %s.\n" % xmlGzCount
    logger.log(msg)
    msgBody += msg + "\n"

    plotter = MECOPlotting(COMMAND_LINE_ARGS.testing)

    try:
        plotter.plotReadingAndMeterCounts(databaseName)
        msg = "\nPlot is attached.\n"
    except Exception, e:
        msg = "\nAn exception occurred: Failed to generate plot: %s\n" % e
        logger.log(msg, 'error')

    msgBody += msg

    if COMMAND_LINE_ARGS.email:
        notifier.sendMailWithAttachments(msgBody, makePlotAttachments(),
                                         COMMAND_LINE_ARGS.testing)

    logger.log("msgBody = %s" % msgBody)
        hourlyNames = [k + 'hourly.txt.gz' for k in keepDates]

        for n in hourlyNames:
            fullPath = os.path.join(root, n)
            msg = fullPath
            print msg
            msgBody += "Processing %s.\n" % msg
            fileObject = gzip.open(fullPath, "rb")
            weatherDays = inserter.insertDataDict(conn, 'WeatherNOAA',
                                                  dataParser.parseWeatherData(
                                                      fileObject,
                                                      [KAHULUI_AIRPORT]),
                                                  commit = True)
            allDays += weatherDays

            fileObject.close()
            if TESTING:
                break

if len(allDays) == 0:
    msgBody += "No weather data was processed."
else:
    setOfAllDays = set(allDays)
    msgBody += timeUtil.reportOfDays(setOfAllDays)

parseLog = ''

if COMMAND_LINE_ARGS.email:
    notifier.sendMailWithAttachments(msgBody, files = None,
                                     testing = COMMAND_LINE_ARGS.testing)
        for n in hourlyNames:
            fullPath = os.path.join(root, n)
            msg = fullPath
            print msg
            msgBody += "Processing %s.\n" % msg
            fileObject = gzip.open(fullPath, "rb")
            weatherDays = inserter.insertDataDict(conn,
                                                  'WeatherNOAA',
                                                  dataParser.parseWeatherData(
                                                      fileObject,
                                                      [KAHULUI_AIRPORT]),
                                                  commit=True)
            allDays += weatherDays

            fileObject.close()
            if TESTING:
                break

if len(allDays) == 0:
    msgBody += "No weather data was processed."
else:
    setOfAllDays = set(allDays)
    msgBody += timeUtil.reportOfDays(setOfAllDays)

parseLog = ''

if COMMAND_LINE_ARGS.email:
    notifier.sendMailWithAttachments(msgBody,
                                     files=None,
                                     testing=COMMAND_LINE_ARGS.testing)
Esempio n. 6
0
class TestMECONotifier(unittest.TestCase):
    """
    Unit tests for the MECO Notifier.
    """
    def setUp(self):
        self.logger = SEKLogger(__name__)
        self.notifier = MSGNotifier()
        self.configer = MSGConfiger()

    def tearDown(self):
        pass

    def testInit(self):
        self.assertIsNotNone(self.notifier, "Notifier has been initialized.")

    def testEmailServer(self):
        """
        Test connecting to the email server.
        """

        errorOccurred = False
        user = self.configer.configOptionValue('Notifications',
                                               'email_username')
        password = self.configer.configOptionValue('Notifications',
                                                   'email_password')

        server = smtplib.SMTP(
            self.configer.configOptionValue('Notifications',
                                            'smtp_server_and_port'))

        try:
            server.starttls()
        except smtplib.SMTPException as detail:
            self.logger.log("Exception: {}".format(detail))

        try:
            server.login(user, password)
        except smtplib.SMTPException as detail:
            self.logger.log("Exception: {}".format(detail))

        self.assertFalse(errorOccurred,
                         "No errors occurred during SMTP setup.")

    def testSendEmailNotification(self):
        """
        Send a test notification by email.
        """

        if SEND_EMAIL:
            success = self.notifier.sendNotificationEmail(
                'This is a message from testSendEmailNotification.',
                testing=True)
            self.assertTrue(
                success, "Sending an email notification did not produce an"
                " exception.")
        else:
            self.assertTrue(True,
                            "Email is not sent when SEND_EMAIL is False.")

    def testSendEmailAttachment(self):
        """
        Send a test notification with attachment by email.
        """

        if SEND_EMAIL:
            body = "Test message"
            testDataPath = self.configer.configOptionValue(
                'Testing', 'test_data_path')
            file = os.path.join(testDataPath, 'graph.png')
            success = self.notifier.sendMailWithAttachments(body, [file],
                                                            testing=True)
            success = (success != True)
            self.assertTrue(
                success, "Sending an email notification did not produce an"
                " exception.")
        else:
            self.assertTrue(True,
                            "Email is not sent when SEND_EMAIL is False.")