Пример #1
0
def get_config(config_file):
    # FIXME gross hack, ditch or fork this module, and numpy why?
    # class fakemodule(object):
    #     pass
    #sys.modules["PyQt5.QtWebKit"] = fakemodule
    #sys.modules["PyQt5.QtWebKitWidgets"] = fakemodule
    # os.environ['QT_API'] = '0'
    # sys.modules["numpy"] = fakemodule
    # from pyqtconfig.qt import QObject, PYSIDE, QT_API_ENV
    # print('----', QObject, PYSIDE, QT_API_ENV)
    #from pyqtconfig import ConfigManager # isort:skip

    cfg = ConfigManager()
    cfg.set_defaults({
        'run_at_startup': False,
        'watch_dir': '.',
        'api_token': '',
        'account_id': '',
        'always_running': False,
    })
    try:
        with open(config_file, 'r') as f:
            raw_config = json.loads(f.read())
            raw_config['account_id'] = str(raw_config['account_id'])
            cfg.set_defaults(raw_config)
    except FileNotFoundError:
        logging.info('Found no config file, using defaults')
    except JSONDecodeError:
        logging.error('Invalid config file, noit valid json')
    return cfg
Пример #2
0
    def testGetProjectNameInvalidUserInput_minus_one(self):
        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/transfiles.ini'
        else:
            configFilePathName = 'D:\\Development\\Python\\trans_file_cloud\\test\\transfiles.ini'

        configManager = ConfigManager(configFilePathName)
        rq = Requester(configManager)

        # simulating user input
        stdin = sys.stdin

        # invalid user input of -1
        sys.stdin = StringIO('-1\nQ')

        stdout = sys.stdout
        outputCapturingString = StringIO()
        sys.stdout = outputCapturingString
        rq.getProjectName(
            None
        )  # will eat up what has been filled in stdin using StringIO above

        sys.stdin = stdin
        sys.stdout = stdout

        self.assertEqual(
            'Select project (Enter to loop or quit):\n\n1 transFileCloudTestProject\n2 transFileCloudProject\n3 transFileCloudFilePathNameProject\n4 cartesianAxesProject\n5 transFileCloudInvalidProject\n\nInvalid selection. Select project (Enter to loop or quit):\n\n1 transFileCloudTestProject\n2 transFileCloudProject\n3 transFileCloudFilePathNameProject\n4 cartesianAxesProject\n5 transFileCloudInvalidProject\n\n',
            outputCapturingString.getvalue())
Пример #3
0
    def __init__(self):
        self.principal = get_principal()

        self.config = ConfigManager(self)
        self.db = Database(self)

        self.zgram_queue = queue.Queue()
        self.error_queue = queue.Queue()

        def zgram_handler(zp, zgram):
            self.zgram_queue.put(zgram)
            # we send a SIGWINCH signal to ourselves,
            # making ncurses think that the window was resized.
            # this is the best way I know of to interrupt ncurses
            # in blocking mode.
            os.kill(os.getpid(), SIGWINCH)

        def error_handler(error):
            self.error_queue.put(error)
            os.kill(os.getpid(), SIGWINCH)

        self.zpipe = zpipe.ZPipe(['./zpipe/zpipe'], zgram_handler,
                                 error_handler)

        self.zpipe.subscribe('message', '*', self.principal)
        for class_, instance, recipient, _ in self.db.get_subscriptions():
            self.zpipe.subscribe(class_, instance, recipient)
Пример #4
0
    def openDB(self):
        try:
            self._config = ConfigManager()
            self.db = self._config.config[self._config.database]["database"]
            create_db = False
            if self.db == self._config.Sqlite:
                folder = self._config.config[self._config.database]["folder"]
                loc = folder + '/icepapcms.db'
                create_db = not os.path.exists(loc)
                if create_db:
                    if not os.path.exists(folder):
                        os.mkdir(folder)
                self._database = create_database("%s:%s" % (self.db, loc))
            else:
                server = self._config.config[self._config.database]["server"]
                user = self._config.config[self._config.database]["user"]
                pwd = self._config.config[self._config.database]["password"]
                self._database = create_database("%s://%s:%s@%s/icepapcms" %
                                                 (self.db, user, pwd, server))

            self._store = Store(self._database)
            if create_db:
                self.dbOK = self.createSqliteDB()
            else:
                self.dbOK = True
        except:
            print "Unexpected error:", sys.exc_info()
            self.dbOK = False
Пример #5
0
    def testGetUserConfirmation_downloadFiles(self):
        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/transfiles.ini'
        else:
            configFilePathName = 'D:\\Development\\Python\\trans_file_cloud\\test\\transfiles.ini'

        configManager = ConfigManager(configFilePathName)
        rq = Requester(configManager)

        # simulating user input
        stdin = sys.stdin
        sys.stdin = StringIO('y')

        stdout = sys.stdout
        outputCapturingString = StringIO()
        sys.stdout = outputCapturingString

        cloudFileLst = [
            'constants_2.py', 'filelister_2.py', 'testfilelister_2.py'
        ]
        questionStr = 'vvv {} files will be transferred from the cloud and then moved to the correct dir and sub-dir of {}.\nIf you want to upload new modified files instead, type N'.format(
            len(cloudFileLst), 'ru.iiec.pydroid3/files/trans_file_cloud')
        doDownload, lastSynchTimeChoice = rq.getUserConfirmation(
            questionStr, cloudFileLst)

        sys.stdin = stdin
        sys.stdout = stdout

        self.assertEqual(
            '\nconstants_2.py\nfilelister_2.py\ntestfilelister_2.py\n\nvvv 3 files will be transferred from the cloud and then moved to the correct dir and sub-dir of ru.iiec.pydroid3/files/trans_file_cloud.\nIf you want to upload new modified files instead, type N.\n\nContinue (Y/YK/N/Enter) ',
            outputCapturingString.getvalue())
        self.assertTrue(doDownload)
        self.assertEqual('', lastSynchTimeChoice)
Пример #6
0
def config_by_search():
    """Create a RDF Graph configuration file by searching for Orcid user."""
    orcid_profile = orcid_search(sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
Пример #7
0
 def __init__(self, config=None):
     self.config = config or ConfigManager().get_specific_configuration(
         "alerts_processor")
     super().__init__(self.config["amqp_url"])
     self.exchange = self.config["exchange"]
     self.exchange_type = self.config["exchange_type"]
     self.queue = self.config["queue"]
     self.routing_key = self.config["routing_key"]
     self.alerts_enricher = AlertEnricher()
     self.alerts_inserter = AlertsInserter()
Пример #8
0
 def __init__(self, config=None):
     if config is None:
         self.config = ConfigManager().get_specific_configuration(
             "alerts_enricher")
     else:
         self.config = config
     self.db_connection = PostgresClient(host=self.config["host"],
                                         user=self.config["user"],
                                         password=self.config["pass"],
                                         database=self.config["database"])
Пример #9
0
def config_by_id(orcid_id):
    """Create a RDF Graph configuration file by Orcid ID.

    :param orcid_id: string
        Orcid ID used for the configuration file ID and to create the configuration file.
    """
    # Make sure sandbox variable is set correctly in cli.py before testing
    orcid_profile = OrcidManager(orcid_id=orcid_id, sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
Пример #10
0
def init_config(config=None):
    """
    Initialize the server with the endpoints.
    Args:
        config:
    """
    if config is None:
        config = ConfigManager().configuration
    else:
        config = config
    ConfigureLogging(**config["logger"])
    app.config.update(**config)
Пример #11
0
def config_by_email(email):
    """Create a RDF Graph configuration file by Orcid email.

    :param email: string
        Orcid email address used to create a configuration file.
    """
    # Make sure sandbox variable is set correctly in cli.py before testing
    email = 'email:' + email
    orcid_profile = OrcidManager(orcid_email=email, sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
Пример #12
0
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.parent = parent

        self.config(bg=storedsettings.APP_MAIN_COLOR)

        self.ran = False
        self.mgr = ConfigManager()

        self.frame_buttons = tk.Frame(self, bg=storedsettings.APP_MAIN_COLOR)
        self.frame_buttons.grid(row=0, column=0)

        self.draw_menu()
Пример #13
0
 def __init__(self, master, *args):
     QtGui.QWidget.__init__(self, *args)
     self.master = master
     #if hasattr(FreeCAD,"mywidget"):
     #	FreeCAD.mywidget.hide()
     FreeCAD.mywidget = self
     self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
     self.config = master.config
     self.vollabel = QtGui.QLabel('1. Select Packages ...')
     self.vollabel2 = QtGui.QLabel('2. Show Package Info ...')
     self.lab2 = QtGui.QLabel(str(datetime.now()))
     self.vollabel3 = QtGui.QLabel('3. Install/Update ...')
     self.pushButton02 = QtGui.QPushButton()
     self.pushButton02.clicked.connect(self.on_pushButton02_clicked)
     self.pushButton02.setText("Display ")
     self.pushButton03 = QtGui.QPushButton()
     self.pushButton03.clicked.connect(self.on_pushButton03_clicked)
     self.pushButton03.setText("Run")
     self.listWidget = QtGui.QListWidget()
     self.listWidget.setSelectionMode(
         QtGui.QAbstractItemView.MultiSelection)
     kl = self.config.keys()
     say(kl)
     for k in sorted(kl):
         pcm = ConfigManager(k)
         hide = pcm.get('_hide_', False)
         if not self.config[k]['status'] == "ignore" and not hide:
             item = QtGui.QListWidgetItem(k)
             self.listWidget.addItem(item)
     layout = QtGui.QGridLayout()
     self.setStyleSheet(
         "QListWidget,QPushButton {background-color: lightblue;color:brown;} "
     )
     line = 4
     layout.addWidget(self.vollabel, 0, 0)
     line = 3
     layout.addWidget(self.listWidget, line, 0, 1, 4)
     line += 1
     layout.addWidget(self.vollabel2, line, 0)
     line += 1
     layout.addWidget(self.lab2, line, 0)
     line += 1
     layout.addWidget(self.pushButton02, line, 0, 1, 4)
     line += 1
     layout.addWidget(self.vollabel3, line, 0)
     line += 1
     layout.addWidget(self.pushButton03, line, 0, 1, 4)
     line += 1
     line += 1
     self.setLayout(layout)
     self.setWindowTitle("Plugin Loader" + __vers__)
def test_http_sender_queue(properties, deliver, channel, message, url, format):
    # Add message to queue

    message_raw = {"url": url, "message": message, "format": format}

    config = ConfigManager().configuration
    message_handler = MessageHandler()
    consumer = MessageConsumer(message_handler, **config.get("rabbit"))
    message_handler._send_http_post = MagicMock()

    consumer._handle_message(channel, deliver, properties,
                             json.dumps(message_raw).encode("utf8"))

    assert message_handler._send_http_post.called
Пример #15
0
    def checkFirmwareVersions(self, icepap_system):
        config = ConfigManager()
        if config._options.skipversioncheck == True:
            print "Firmware versions are not checked."
            return
        try:
            icepap_name = icepap_system.name
            master_version = self._ctrl_icepap.iPaps[icepap_name].getVersion(
                0, "DRIVER")
            master_version = str(master_version)
            mismatched_drivers = []
            for driver in icepap_system.getDrivers():
                #####################################################################
                driver_version = self._ctrl_icepap.iPaps[
                    icepap_name].getVersion(driver.addr, "DRIVER")
                # If the driver has been temporary removed, the error should
                if driver_version.count("ERROR") > 0:
                    driver_version = master_version
                if master_version != driver_version:
                    mismatched_drivers.append(
                        (driver.addr, str(driver_version)))

            if len(mismatched_drivers) > 0:
                msg = "Some drivers do not have the MASTER's firmware version (%s):\n" % (
                    master_version)
                for driver, version in mismatched_drivers:
                    msg = msg + "driver %d: %s\n" % (driver, version)
                saved_version = self._ctrl_icepap.iPaps[
                    icepap_name].getVersionSaved()
                msg = msg + "Board saved version: %s\n" % (saved_version)
                msg = msg + "Would you like to upgrade these drivers?\n"
                upgrade = MessageDialogs.showYesNoMessage(
                    self._form, "Firmware mismatch", msg)
                if upgrade:
                    progress_dialog = QtGui.QProgressDialog(self._form)
                    progress_dialog.setLabel(
                        QtGui.QLabel(
                            "Icepap: %s\nUpgrading drivers' firmware to %s" %
                            (icepap_name, saved_version)))
                    progress_dialog.setCancelButton(None)
                    progress_dialog.setMaximum(100)
                    upgrading = self._ctrl_icepap.upgradeDrivers(
                        icepap_name, progress_dialog)
                    if not upgrading:
                        progress_dialog.cancel()
                        msg = "Sorry, problems found while upgrading. Please try it manually :-("
                        MessageDialogs.showErrorMessage(
                            None, "Firmware upgrade error", msg)
        except:
            pass
Пример #16
0
def test_sms_sender(properties, deliver, channel, twilio_client, message, to, fixed_to):
    config = ConfigManager().configuration
    handler = MessageHandler(**config.get("sms"))
    handler.client = twilio_client
    consumer = MessageConsumer(handler, **config.get("rabbit"))

    consumer._handle_message(channel, deliver, properties, json.dumps({
        "receiver_phones": to,
        "message": message
    }).encode("utf8"))

    twilio_client.messages.create.assert_called_once_with(body=message,
                                                          from_=config.get("sms").get("sender"),
                                                          to=fixed_to)
Пример #17
0
    def __init__(self):
        self.root = Tk()
        winWidth = int(self.root.winfo_screenwidth() * WIN_WIDTH_RATIO)
        self.root.geometry("{}x{}".format(winWidth, WIN_HEIGHT))
        self.msg = Message(self.root, aspect=winWidth - 10)
        self.msg.grid(row=2, column=0, columnspan=2, padx=2)
        self.msgText = ''

        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/youtube_audio_download/audiodownload.ini'
        else:
            configFilePathName = 'D:\\Development\\Python\\youtube_audio_download\\audiodownload.ini'

        self.configMgr = ConfigManager(configFilePathName)
        self.emailLst = self.configMgr.getEmailLst()
Пример #18
0
    def gentoolbars(self, workbench='init'):
        global pathMacro
        cf = self.pluginloader.config
        say("gentoolbars ...")
        if self.pluginloader.config3["toolbars"].has_key(workbench):
            # say("toolbars for            ----------------------" + workbench)
            for ky in sorted(
                    self.pluginloader.config3["toolbars"][workbench].keys()):
                #say(ky)
                cma = ConfigManager("__toolbars__/" + workbench + "/" + ky)
                funhide = cma.get("_hide_", False)
                if funhide:
                    say("toolbar ignore item " + ky)
                    continue

                try:
                    mw = FreeCAD.Gui.getMainWindow()
                    mw.toolbar = mw.addToolBar(workbench + ': ' + ky)
                    mw.toolbar.setWindowTitle("Personal " + workbench + ': ' +
                                              ky)
                    #exitAction = QtGui.QAction('Exit 2', FreeCAD.Gui.getMainWindow())
                    #exitAction.setShortcut('.')
                    #exitAction.triggered.connect(QtGui.qApp.quit)
                    #mw.toolbar.addAction(exitAction)
                    mw.toolbar.show()
                    toolbarBox = mw.toolbar
                except Exception:
                    sayexc("exception add Tool Bar")
                for tool in sorted(self.pluginloader.config3["toolbars"]
                                   [workbench][ky].keys()):
                    say(tool)
                    yy = self.pluginloader.config3["toolbars"][workbench][ky][
                        tool]
                    myAction2 = QtGui.QAction(QtGui.QIcon(yy['icon']), tool,
                                              mw)
                    myAction2.setToolTip(tool)
                    try:
                        cmd = yy['exec']
                    except:
                        cmd = "say('" + str(yy) + "')"

                    yy = MyAction2(pathMacro(cmd))
                    myAction2.yy = yy
                    myAction2.triggered.connect(yy.run)
                    toolbarBox.addAction(myAction2)
                toolbarBox.show()
                self.toolbars.append(toolbarBox)
                say(ky + " done")
    def testMoveFilesToLocalDirs_dirNotExist(self):
        if os.name == 'posix':
            downloadDir = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/fromdir'
            downloadDirSaved = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/fromdir_saved'
            projectDir = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/projectdir'
        else:
            # Windows
            downloadDir = 'D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\fromdir'
            downloadDirSaved = 'D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\fromdir_saved'
            projectDir = 'D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\projectdir'

        configManager = ConfigManager(CONFIG_FILE_PATH_NAME)

        # deleting downloadDir (dir and content)
        if os.path.exists(downloadDir):
            shutil.rmtree(downloadDir)

        # restoring downloadDir from its saved version
        shutil.copytree(downloadDirSaved, downloadDir)

        projectName = 'transFileCloudTestProject'
        fm = FileMover(configManager, projectName)
        fm.projectDir = projectDir

        # capturing stdout into StringIO to avoid outputing in terminal
        # window while unit testing

        stdout = sys.stdout
        outputCapturingString = StringIO()
        sys.stdout = outputCapturingString

        cloudFileLst = ['constants_1.mp3']

        fm.moveFilesToLocalDirs(cloudFileLst)

        sys.stdout = stdout

        if os.name == 'posix':
            self.assertEqual([
                'Destination dir /storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/projectdir/mp3/not_exist does not exist. Program stopped.'
            ],
                             outputCapturingString.getvalue().split('\n')[:-1])
        else:
            self.assertEqual([
                'Destination dir D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\projectdir\\mp3\\not_exist does not exist. Program stopped.'
            ],
                             outputCapturingString.getvalue().split('\n')[:-1])
Пример #20
0
 def setParams(self):
     ta = FreeCAD.ParamGet('User parameter:Plugins')
     ta.SetString("pluginlist", "")
     pluginlist = []
     for k in self.config.keys():
         if not self.config[k]['status'] == 'ignore':
             t = FreeCAD.ParamGet('User parameter:Plugins/' + k)
             pcm = ConfigManager(k)
             hide = pcm.get('_hide_', False)
             if hide:
                 continue
             pluginlist.append(k)
             #say("--")
             #say(k)
             #say(self.config[k])
             #say(self.config[k]["name"])
             t.SetString("name", self.config[k]["name"])
             if self.config[k].has_key("author"):
                 t.SetString("author", self.config[k]["author"])
             t.SetString("destination", self.config[k]["destdir"])
             t.SetInt('installed', 1)
             itemlist = []
             if self.config[k].has_key('menuitems'):
                 for menu in self.config[k]['menuitems'].keys():
                     #say(menu)
                     itemlist.append(menu)
                     tm = FreeCAD.ParamGet('User parameter:Plugins/' + k +
                                           '/' + menu)
                     tm.SetString("exec",
                                  self.config[k]['menuitems'][menu]['exec'])
             else:
                 #say("keine menuitmes")
                 pass
             if self.config[k].has_key('menu'):
                 menu = self.config[k]['menu']
                 #say(menu)
                 itemlist.append(menu)
                 tm = FreeCAD.ParamGet('User parameter:Plugins/' + k + '/' +
                                       menu)
                 tm.SetString("exec", self.config[k]['exec'])
             ms = ";".join(itemlist)
             if ms <> "":
                 t.SetString("menulist", ms)
     ps = ";".join(pluginlist)
     ta.SetString("pluginlist", ps)
    def __init__(self, audioDownloaderGUI, audioDir, configMgr=None):
        """
		
		:param audioDownloaderGUI: used for unit testing only !
		"""

        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/audiodownloader.ini'
        else:
            configFilePathName = 'c:\\temp\\audiodownloader.ini'

        if configMgr == None:
            self.configMgr = ConfigManager(configFilePathName)
        else:
            self.configMgr = configMgr

        self.requester = Requester(self.configMgr)
        self.audioDownloaderGUI = audioDownloaderGUI
        self.audioDownloader = YoutubeDlAudioDownloader(self, audioDir)
Пример #22
0
 def signDriver(self):
     # AS ESRF SAYS, WHEN SIGNING THE DRIVER CONFIG, THE COMMIT SHOULD BE DONE
     # IN THE DATABASE FIRST, AND IF NO ERRORS, THEN COMMUNICATE THE DRIVER
     # THAT THE VALUES SHOULD BE SIGNED.
     try:
         #signature = socket.gethostname() #+ "_" + str(time.time())
         user = ConfigManager().username
         host = socket.gethostname()
         signature = user+"@"+host+"_"+datetime.now().strftime('%Y/%m/%d_%H:%M:%S')
         IcepapController().signDriverConfiguration(self.icepapsystem_name, self.addr, signature)
         self.mode = unicode(Mode.OPER)
         db = StormManager()
         db.commitTransaction()
         self.current_cfg.name = unicode(time.ctime())
         self.current_cfg.setSignature(signature)        
         self.startup_cfg = self.current_cfg
         self.conflict = Conflict.NO_CONFLICT
     except Exception,e:
         print "some exception while trying to sign the driver",e
Пример #23
0
def simulator_loop():
    conf_manager = ConfigManager()

    frost_config = conf_manager.get_specific_configuration("sensorthings")
    frost_url = frost_config.pop("url")
    frost_port = frost_config.pop("port")
    query_sleep = frost_config.pop("query_sleep")

    simulator_config = conf_manager.get_specific_configuration("simulator")
    mu = simulator_config.pop("mu")
    sigma = simulator_config.pop("sigma")

    frost_base_url = "http://{}:{}/FROST-Server/v1.0/".format(frost_url, frost_port)
    frost_observation_url = frost_base_url + "Observations"

    datastream_id = create_datastream(frost_base_url)

    with open("schemas/tiltmeter_observation_template.json") as f:
        template = f.read()
        template = template.replace("{datastream_id}", datastream_id)

    while True:
        axis_one = random.gauss(mu, sigma)
        axis_two = random.gauss(mu, sigma)
        dt = datetime.datetime.now()

        new_data = template.replace("{axis_one}", str(axis_one))
        new_data = new_data.replace("{axis_two}", str(axis_two))
        new_data = new_data.replace("{datetime}", dt.strftime("%Y-%m-%dT%H:%M:%SZ"))

        # TODO: find the way to prevent from having to write-read the file every iteration
        with open("schemas/tiltmeter_sensorthings.json", "w") as f:
            f.write(new_data)

        with open("schemas/tiltmeter_sensorthings.json", "rb") as f:
            response = requests.post(frost_observation_url,
                                     headers={"content-type": "application/json"},
                                     data=f)

        logging.info(response.request)

        time.sleep(query_sleep)
 def init(self, *args):
     self.iPaps = {}
     pathname = os.path.dirname(sys.argv[0])
     path = os.path.abspath(pathname)
     self.config_template = os.path.join(path, 'templates',
                                         'driverparameters.xml')
     self._parseDriverTemplateFile()
     self._config = ConfigManager()
     self.icepap_cfginfos = {}
     self.programming_ipap = None
     try:
         ipap = self._config.icepap
         debug_set = self._config.config[ipap]["debug_enabled"]
         self.debug = debug_set == str(True)
         self.log_folder = self._config.config[ipap]["log_folder"]
         if not os.path.exists(self.log_folder):
             os.mkdir(self.log_folder)
     except Exception:
         print "icepapcontroller_init():", sys.exc_info()
         pass
 def init(self, *args):
     self.iPaps = {}
     pathname = os.path.dirname(sys.argv[0])
     path = os.path.abspath(pathname)
     self.config_template = path + '/../share/icepapcms/templates/driverparameters.xml'
     self._parseDriverTemplateFile()
     self._config = ConfigManager()
     self.icepap_cfginfos = {}
     self.icepap_cfgorder = {}
     self.programming_ipap = None
     try:
         self.debug = self._config.config[
             self._config.icepap]["debug_enabled"] == str(True)
         self.log_folder = self._config.config[
             self._config.icepap]["log_folder"]
         if not os.path.exists(self.log_folder):
             os.mkdir(self.log_folder)
     except:
         print "icepapcontroller_init():", sys.exc_info()
         pass
def test_email_sender(properties, deliver, channel, server, sender, recipients,
                      subject, message):
    def _build_server():
        return server

    config = ConfigManager().configuration
    handler = MessageHandler(**config.get("smtp"))
    handler._build_server = _build_server
    consumer = MessageConsumer(handler, **config.get("rabbit"))

    consumer._handle_message(
        channel, deliver, properties,
        json.dumps({
            "receiver_emails": recipients,
            "message_html": message,
            "title": subject
        }).encode("utf8"))

    server.sendmail.assert_called_once_with(sender, '*****@*****.**',
                                            ANY)
Пример #27
0
def main(application_name, arguments):
    """
    Main procedure.

    Parameters
    ----------
    application_name : str
        The name of the application (used in console messages).
    arguments : list of str
        The command line arguments passed to the interpreter (beside the name of the script).
    """

    # Parse command line arguments.
    is_config_generation_requested = False
    config_file_path = DEFAULT_CONFIG_PATH

    try:
        opts, _ = getopt.getopt(arguments, 'c:ih', ['config=', 'install'])
    except getopt.GetoptError:
        print_usage_and_exit(application_name, 2)

    for opt, arg in opts:
        if opt in ('-c', '--config'):
            config_file_path = arg
        elif opt in ('-h', '--help'):
            print_usage_and_exit(application_name)
        elif opt in ('-i', '--install'):
            is_config_generation_requested = True

    config_manager = ConfigManager(config_file_path)

    # Create configuration file and exit.
    if is_config_generation_requested:
        config = Config()
        config.create_default()
        config_manager.save(config)
    # Load configuration, then go ahead.
    else:
        config = config_manager.load()
        app = App(config)
        app.execute()
Пример #28
0
    def testGetUserConfirmation_uploadFiles(self):
        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/transfiles.ini'
        else:
            configFilePathName = 'D:\\Development\\Python\\trans_file_cloud\\test\\transfiles.ini'

        configManager = ConfigManager(configFilePathName)
        rq = Requester(configManager)

        # simulating user input
        stdin = sys.stdin
        sys.stdin = StringIO('y')

        stdout = sys.stdout
        outputCapturingString = StringIO()
        sys.stdout = outputCapturingString

        updatedFileNameLst = [
            'constants_2.py', 'filelister_2.py', 'testfilelister_2.py'
        ]
        updatedFilePathNameLst = [
            '/project/constants_2.py', '/project/filelister_2.py',
            '/project/test/testfilelister_2.py'
        ]
        questionStr = '^^^ {} files were modified locally after {}\nand will be uploaded to the cloud.\nChoose P to display the path or U to update the last sync time'.format(
            len(updatedFileNameLst), '2020-07-22 15:30:22')
        doUpload, lastSynchTimeChoice = rq.getUserConfirmation(
            questionStr, updatedFileNameLst, updatedFilePathNameLst)

        sys.stdin = stdin
        sys.stdout = stdout

        self.assertEqual(
            '\nconstants_2.py\nfilelister_2.py\ntestfilelister_2.py\n\n^^^ 3 files were modified locally after 2020-07-22 15:30:22\nand will be uploaded to the cloud.\nChoose P to display the path or U to update the last sync time.\n\nContinue (Y/N/P/U/Enter) ',
            outputCapturingString.getvalue())
        self.assertTrue(doUpload)
        self.assertEqual('', lastSynchTimeChoice)
Пример #29
0
from configmanager import ConfigManager
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker

from utils import construct_db_uri

db_config = ConfigManager().get_specific_configuration("database")
db_uri = construct_db_uri(db_config)
engine = create_engine(db_uri, convert_unicode=True)
session = scoped_session(
    sessionmaker(autocommit=False, autoflush=True, bind=engine))

Base = declarative_base()
Base.query = session.query_property()
metadata = Base.metadata


def init_db():
    import models.models
    Base.metadata.create_all(engine, checkfirst=True)


def insert_response_plan(response_plan):
    from models.models import ResponsePlan
    session.add(response_plan)
    session.flush()
    internal_id = response_plan.internal_id
    session.commit()

    return internal_id
Пример #30
0
from message_handler import MessageHandler

logger = logging.getLogger(__name__)


class EmailNotifier:

    def __init__(self, handler, consumer):
        self.handler = handler
        self.consumer = consumer

    def init(self, ):
        try:
            logger.info("Email Notifier initialization...")
            self.consumer.run()
        except Exception as e:
            logger.exception(e)
        finally:
            logger.info("Email Notifier :: Finish execution")


if __name__ == "__main__":
    config = ConfigManager().configuration
    ConfigureLogging(**config["logger"])
    try:
        handler = MessageHandler(**config.get("smtp"))
        consumer = MessageConsumer(handler, **config.get("rabbit"))
        EmailNotifier(handler, consumer).init()
    except:
        logger.info("Email Notifier :: Finish execution")