Esempio n. 1
0
    def test_config(self):
        # Verify that config exists, that it's a dictionary, and that it's
        # empty.
        self.assertTrue(type(config.config) is dict)
        self.assertEqual(len(config.config), 0)

        # Verify that attempting to get a non-existant key out of the
        # dictionary returns None.
        self.assertIsNone(config.GetConfig('rabbit'))
        self.assertIsNone(config.GetConfig('key1'))

        config.AddConfig('key1', 16)
        config.AddConfig('key2', 32)
        config.AddConfig('key3', 'third value')

        # Verify that after 3 calls to AddConfig we have 3 values in the
        # dictionary.
        self.assertEqual(len(config.config), 3)

        # Verify that GetConfig works and gets the expected values.
        self.assertIs(config.GetConfig('key2'), 32)
        self.assertIs(config.GetConfig('key3'), 'third value')
        self.assertIs(config.GetConfig('key1'), 16)

        # Re-set config.
        config.config.clear()

        # Verify that config exists, that it's a dictionary, and that it's
        # empty.
        self.assertTrue(type(config.config) is dict)
        self.assertEqual(len(config.config), 0)
Esempio n. 2
0
def test_GetConfig_PortType():
    # These options result in port type of uart
    UartOpts = ["uart", "usb", "UART", "USB"]
    for uart in UartOpts:
        with patch.dict('os.environ', {"PORT_TYPE": uart}):
            c = config.GetConfig()
            assert c.PortType == "uart"

    # Anything not listed for UART options results in I2C
    AnythingElse = ["i2c", "I2C", "blah"]

    for i2c in AnythingElse:
        with patch.dict('os.environ', {"PORT_TYPE": i2c}):
            c = config.GetConfig()
            assert c.PortType == "i2c"
Esempio n. 3
0
def main():

    # Log the startup
    jarlog.logit('INFO', "Starting jarflyd")

    # Get the config
    confobj = config.GetConfig()

    # Set up the identity type
    pyrax.set_setting("identity_type", "rackspace")

    # Set up the credentials file
    cred_file = confobj.get("global", "credentials_file")
    jarlog.logit('INFO', "Authenticating using cred file: %s" % cred_file)
    pyrax.set_credential_file(cred_file)

    # Set up the default region
    globalRegion = confobj.get("global", "region")
    jarlog.logit('INFO', "Setting global region to: %s" % globalRegion)
    pyrax.connect_to_services(region=globalRegion)

    # Start reading in the jar sections
    sections = confobj.sections()
    for section in sections:
        if section.startswith("jar-"):
            processJar(confobj, section)
    def _Email(self, experiment):
        # Only email by default if a new run was completed.
        send_mail = False
        for benchmark_run in experiment.benchmark_runs:
            if not benchmark_run.cache_hit:
                send_mail = True
                break
        if (not send_mail and not experiment.email_to
                or config.GetConfig('no_email')):
            return

        label_names = []
        for label in experiment.labels:
            label_names.append(label.name)
        subject = '%s: %s' % (experiment.name, ' vs. '.join(label_names))

        text_report = TextResultsReport.FromExperiment(experiment,
                                                       True).GetReport()
        text_report += ('\nResults are stored in %s.\n' %
                        experiment.results_directory)
        text_report = "<pre style='font-size: 13px'>%s</pre>" % text_report
        html_report = HTMLResultsReport.FromExperiment(experiment).GetReport()
        attachment = EmailSender.Attachment('report.html', html_report)
        email_to = experiment.email_to or []
        email_to.append(getpass.getuser())
        EmailSender().SendEmail(email_to,
                                subject,
                                text_report,
                                attachments=[attachment],
                                msg_type='html')
Esempio n. 5
0
def test_GetConfig_Defaults():
    c = config.GetConfig()

    assert c.ProductUID == 'com.my.product.uid'
    assert c.HubHost == "a.notefile.net"
    assert c.PortType == "i2c"
    assert c.PortName == "/dev/i2c-1"
    assert c.BaudRate == 9600
    assert not c.EnableDebug
Esempio n. 6
0
def test_GetConfig_setAllEnvironmentVars():
    e = {
        "PRODUCT_UID": 'dummy_product_uid',
        "PORT_TYPE": 'uart',
        "PORT_NAME": "COM6",
        "BAUD_RATE": "115200",
        "HUB_HOST": "a.b.c",
        "DEBUG": "true"
    }

    with patch.dict('os.environ', e, clear=True):
        c = config.GetConfig()
        assert c.ProductUID == 'dummy_product_uid'
        assert c.HubHost == "a.b.c"
        assert c.PortType == "uart"
        assert c.PortName == "COM6"
        assert c.BaudRate == 115200
        assert c.EnableDebug
Esempio n. 7
0
def GetHtml(url):
    config = my_config.GetConfig()
    cookie = config['remote_server']['cookie']
    html = ""
    request = urllib2.Request(
        url,
        headers={
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'
        })
    request.add_header("Cookie", cookie)
    while (True):
        try:
            response = urllib2.urlopen(request, timeout=60)
            html = response.read()
            break
        except urllib2.HTTPError, e:
            traceback.print_stack()
            logger.info(e.code)
            logger.error(e.reason)
            logger.error(traceback)
Esempio n. 8
0
def SendEMail(files2mail):
    config = my_config.GetConfig()
    # 第三方 SMTP 服务
    mail_host = "smtp.qq.com"  # 设置服务器
    sender = config['email']['sender']
    mail_user = config['email']['mail_user']  # 用户名
    mail_pass = config['email']['mail_pass']  # 口令

    receivers = []
    for recv in config['email']['receivers']:
        receivers.append(recv['qq'])

    msg = MIMEMultipart()
    msg['From'] = formataddr([u'Chant', sender])
    msg['To'] = formataddr([u'Nancy', receivers])
    msg['Subject'] = Header(config['email']['topic'], 'utf-8').encode()
    msg.attach(MIMEText(config['email']['text'], 'plain', 'utf-8'))

    for file in files2mail:
        # 添加附件
        att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        att1.add_header('Content-Disposition',
                        'attachment',
                        filename=Header(file, 'utf-8').encode())  # 防止中文附件名称乱码
        msg.attach(att1)

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.set_debuglevel(1)
        smtpObj.sendmail(sender, receivers, msg.as_string())
        smtpObj.quit()
        logger.info("Send EMail OK")
    except smtplib.SMTPException as e:
        logger.error("Send EMail Error: " + e)
Esempio n. 9
0

GPIO.setmode(GPIO.BCM)

# Configure RPi GPIO pin that is wired to the Notecard ATTN pin to detect rising edges
GPIO.setup(gpioAttnPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)


def signal_handler(sig, frame):
    GPIO.cleanup()
    sys.exit(0)


if __name__ == '__main__':

    config = config.GetConfig()

    if config.EnableDebug:
        log.setLevel(logging.DEBUG)
        ch.setLevel(logging.DEBUG)

    log.info(f"Running: {__file__}")

    message = f"\nProduct: {config.ProductUID}\nHost: {config.HubHost}\nDebug: {config.EnableDebug}\nConnection Port Type:{config.PortType}\nPort name: {config.PortName}\n"
    log.info(message)

    log.debug(f"Connecting to Notecard using {config.PortType} port type")
    card = connectNotecard(config)

    log.debug("Configuring Notecard Hub connection")
    configureNotecard(card, productUID=config.ProductUID, host=config.HubHost)
Esempio n. 10
0
 def setUp(self):
   super(ConfigTest, self).setUp()
   self.config = config.GetConfig()
Esempio n. 11
0
def test_GetConfig_EnableDebug():
    validEnableOpts = ["TRUE", "true", "T", "t", "1", "on", "ON"]
    for opt in validEnableOpts:
        with patch.dict('os.environ', {"DEBUG": opt}):
            c = config.GetConfig()
            assert c.EnableDebug
Esempio n. 12
0
def GetHostUrl():
    config = my_config.GetConfig()
    return config['remote_server']['host_url']