def test_change_config_command(self): # Given config = { 'db_path': 'db.json', 'language': 'en', 'logger_path': 'logger.json' } with open(self.config_file_name, "w") as f: json.dump(config, f) config_manager = ConfigManager() app_info_logger = AppInfoLogger() db = DBConnector(DbFileConnector(config_manager)) logger = LoggerConnector(LoggerFileConnector(config_manager)) config_manager.db_path = self.database_file_name config_manager.logger_path = self.logger_file_name config = { 'db_path': 'db.json', 'language': 'en', 'logger_path': 'logger.json' } with open(self.config_file_name, "w") as f: json.dump(config, f) INVOKER = Invoker(db, logger, config_manager, app_info_logger) expected = "CONFIGURATION_CHANGE" + "\n" \ + "1: \"language\"" + "\n" \ + "2: \"db_path\"" + "\n" \ + "3: \"logger_path\"" + "\n" \ + "INFO: NO_SUCH_ATTRIBUTE\n" # When with mock.patch('builtins.input', return_value="db_path"): with mock.patch('builtins.input', return_value="0"): with patch('sys.stdout', new=StringIO()) as result: INVOKER.execute('11') # Then self.assertEqual(expected, result.getvalue())
def test_search_for_an_article_by_id_command(self): # Given config_manager = ConfigManager() app_info_logger = AppInfoLogger() db = DBConnector(DbFileConnector(config_manager)) logger = LoggerConnector(LoggerFileConnector(config_manager)) config_manager.db_path = self.database_file_name config_manager.logger_path = self.logger_file_name articles = [{ "id": "1", "name": ["mlotek", "hammer"], "total_quantity": 2, "quantity": 2, "is_available": True }, { "id": "2", "name": ["wiertarka", "driller"], "total_quantity": 2, "quantity": 2, "is_available": False }] with open(self.database_file_name, "w") as f: json.dump(articles, f) INVOKER = Invoker(db, logger, config_manager, app_info_logger) expected = "+----+---------+------------------+----------------+----------+--------------+" + "\n" \ + "| ID | NAME | NAME_SECOND_LANG | TOTAL_QUANTITY | QUANTITY | AVAILABILITY |" + "\n" \ + "+----+---------+------------------+----------------+----------+--------------+" + "\n" \ + "| 2 | driller | wiertarka | 2 | 2 | NO |" + "\n" \ + "+----+---------+------------------+----------------+----------+--------------+" # When with mock.patch('builtins.input', return_value="2"): with patch('sys.stdout', new=StringIO()) as result: INVOKER.execute('8') # Then self.assertEqual(expected, result.getvalue())
def setup_logging(self): """Setup logging configuration """ path = os.getenv(self.env_key, None) or self.cfg_path try: config = ConfigManager( config_file_path=path, defaults=self.default_conf, required=['version']) if self.cfg_path else self.default_conf dictConfig(config) logger = logging.getLogger(self.name) except (ValueError, IOError, FileFormatError): logging.basicConfig(level=self.default_level) logger = logging.getLogger(self.name) logger.setLevel(self.default_level) if self.extra: logger = logging.LoggerAdapter(logger, self.extra) return logger
def test_add_log_2(self): # Given logs = [{'id': '1', 'logs': [{"data": "08-05-2020", "text": "Added"}]}] with open(self.config_file_name, "w") as f: json.dump(logs, f) config_manager = ConfigManager() config_manager.logger_path = self.config_file_name logger = LoggerConnector(LoggerFileConnector(config_manager)) expected = [ ArticleLogs('1', [Log("08-05-2020", "Added")]), ArticleLogs('99', [Log("20-05-2020", "Added")]) ] # When logger.add_log('99', Log("20-05-2020", "Added")) # Then self.assertListEqual(expected, logger.get_all_logs())
def test_borrow_article_command2(self): # Given config_manager = ConfigManager() app_info_logger = AppInfoLogger() db = DBConnector(DbFileConnector(config_manager)) logger = LoggerConnector(LoggerFileConnector(config_manager)) config_manager.db_path = self.database_file_name config_manager.logger_path = self.logger_file_name articles = [{ "id": "1", "name": ["mlotek", "hammer"], "total_quantity": 4, "quantity": 1, "is_available": True }, { "id": "2", "name": ["wiertarka", "driller"], "total_quantity": 2, "quantity": 2, "is_available": False }] with open(self.database_file_name, "w") as f: json.dump(articles, f) with open(self.logger_file_name, "w") as f: json.dump([], f) INVOKER = Invoker(db, logger, config_manager, app_info_logger) # When with mock.patch('builtins.input', side_effect=["1", "2", "\n"]): with patch('sys.stdout', new=StringIO()): INVOKER.execute('13') # Then expected = [Article('1', ["mlotek", "hammer"], 4, 1, True)] self.assertEqual(str(expected[0]), str(db.get_articles_by_name('mlotek')[0]))
def test_get_articles_by_availability(self): # Given articles = [{ "id": "1", "name": ["mlotek", "hammer"], "total_quantity": 2, "quantity": 2, "is_available": True }, { "id": "2", "name": ["wiertarka", "driller"], "total_quantity": 2, "quantity": 3, "is_available": False }, { "id": "3", "name": ["wiertarka2", "driller2"], "total_quantity": 40, "quantity": 0, "is_available": False }] with open(self.config_file_name, "w") as f: json.dump(articles, f) config_manager = ConfigManager() config_manager.db_path = self.config_file_name db = DBConnector(DbFileConnector(config_manager)) available = False expected = [ Article('2', ["wiertarka", "driller"], 2, 3, False), Article('3', ["wiertarka2", "driller2"], 40, 0, False) ] # When articles = db.get_articles_by_availability(available) # Then self.assertListEqual(expected, articles)
def __init__(self, config_path, mode, label='Survived'): self.label = label self.config_path = config_path # 学習時の設定ファイル self.dataset = {'X': None, 'y': None} if mode not in ['train', 'pred']: raise ValueError('modeに"train", "pred"を指定してない.') self.mode = mode cm = ConfigManager() if mode == 'pred': expected_keys = ['transformers_path'] self.config = cm.load_config(config_path, expected_keys) self.transformers = self._load_transformers(self.config) else: expected_keys = [] self.config = cm.load_config(config_path, expected_keys) self.transformers = { 'fillna_vals': {}, 'onehot_encoders': {}, 'count_corresp_tables': {}, 'minmax_scaler': None }
def test_delete_article_command(self): # Given config_manager = ConfigManager() app_info_logger = AppInfoLogger() db = DBConnector(DbFileConnector(config_manager)) logger = LoggerConnector(LoggerFileConnector(config_manager)) config_manager.db_path = self.database_file_name config_manager.logger_path = self.logger_file_name articles = [{ "id": "1", "name": ["mlotek", "hammer"], "total_quantity": 2, "quantity": 2, "is_available": True }, { "id": "2", "name": ["wiertarka", "driller"], "total_quantity": 2, "quantity": 2, "is_available": False }] with open(self.database_file_name, "w") as f: json.dump(articles, f) with open(self.logger_file_name, "w") as f: # rozroznienie na pliki db i loggera json.dump([], f) INVOKER = Invoker(db, logger, config_manager, app_info_logger) # When with mock.patch('builtins.input', return_value="1"): with patch('sys.stdout', new=StringIO()): INVOKER.execute('6') # Then self.assertEqual(db.get_article_by_id("1"), False)
def main(): try: # input_param=sys.argv # print(input_param[1]) # print(input_param[2]) #for test only p1 = datetime.strftime(datetime(2018, 9, 19, 1, 1, 1), '%Y-%m-%d-%H-%M-%S') p2 = datetime.strftime(datetime(2018, 9, 20, 1, 1, 1), '%Y-%m-%d-%H-%M-%S') input_param = [p1, p2] print("loading config file...") config_obj = ConfigManager() print('creating AutoTrainer object ...') localDB_filler_obj = LocalDBFiller(config_obj, input_param) localDB_filler_obj.grabber_cleaner( ) # TODO: decide what todo with output time.sleep(5) schedul_kill() except Exception: PrintException()
def test_remove_article_by_id_2(self): # Given articles = [{ "id": "1", "name": ["mlotek", "hammer"], "total_quantity": 2, "quantity": 2, "is_available": True }, { "id": "2", "name": ["wiertarka", "driller"], "total_quantity": 2, "quantity": 3, "is_available": False }, { "id": "3", "name": ["wiertarka2", "driller2"], "total_quantity": 40, "quantity": 0, "is_available": False }] with open(self.config_file_name, "w") as f: json.dump(articles, f) config_manager = ConfigManager() config_manager.db_path = self.config_file_name db = DBConnector(DbFileConnector(config_manager)) article_id = '2' expected = [ Article('1', ["mlotek", "hammer"], 2, 2, True), Article('3', ["wiertarka2", "driller2"], 40, 0, False) ] # When db.remove_article_by_id(article_id) actual = db.get_all_articles() self.assertListEqual(expected, actual)
def test_add_article_2(self): # Given articles = [] with open(self.config_file_name, "w") as f: json.dump(articles, f) config_manager = ConfigManager() config_manager.db_path = self.config_file_name db = DBConnector(DbFileConnector(config_manager)) article = Article('1', ["mlotek", "hammer"], 2, 2, False) article2 = Article('1', ["mlotek2", "hammer2"], 2, 2, False) expected = [Article('1', ["mlotek", "hammer"], 2, 2, False)] # When db.add_article(article) db.add_article(article) db.add_article(article2) # Then self.assertListEqual(expected, db.get_all_articles())
def test_display_config_command(self): # Given config_manager = ConfigManager() app_info_logger = AppInfoLogger() db = DBConnector(DbFileConnector(config_manager)) logger = LoggerConnector(LoggerFileConnector(config_manager)) config_manager.db_path = self.database_file_name config_manager.logger_path = self.logger_file_name INVOKER = Invoker(db, logger, config_manager, app_info_logger) expected = "CURRENT_CONFIGURATION" + "\n" \ + "language: \"en\"" + "\n" \ + "db_path: \"test_interface_database.json\"" + "\n" \ + "logger_path: \"test_interface_logger.json\"" + "\n" # When with mock.patch('builtins.input', return_value="1"): with patch('sys.stdout', new=StringIO()) as result: INVOKER.execute('10') # Then self.assertEqual(expected, result.getvalue())
def reload_yaml(self): config = ConfigManager() config.reload_yaml() db_handle = self.client['esp8266_workshop'] # update all groups mac address and degrees groups_collection = db_handle['groups'] for group in range(1, self._number_of_groups + 1): group_query = {'number': group} groups = [] for g in groups_collection.find(group_query, {'_id': 0}): groups.append(g) if len(groups) > 0: new_values = { '$set': { 'mac': config.get_group_mac_address(group), 'degrees': config.get_group_degrees(group) } } groups_collection.update_one(group_query, new_values) db_handle.drop_collection('config') config_collection = db_handle['config'] for config_item in self._config: new_config = { 'name': config_item, 'value': config.get_item(config_item) } config_collection.insert_one(new_config) db_handle.drop_collection('devices_ip') devices_ip_collection = db_handle['devices_ip'] devices_ip_list = [] for group in range(1, self._number_of_groups + 1): devices_ip_list.append({ 'mac': config.get_group_mac_address(group), 'ip': '' }) devices_ip_collection.insert_many(devices_ip_list)
def setUpClass(cls) -> None: cls.input_board = ' ' \ ' ' \ 'ppppppp ' \ ' ' \ ' ' \ ' ' \ ' p ' \ ' ' \ ' ' \ ' P ' \ ' ' \ ' ' \ ' ' \ 'PPPPPPP ' \ ' ' \ ' ' cls.opponent = 'test_opponent' cls.board_id = 'abcde12345' cls.color = 'white' ConfigManager({}) ConfigManager.set('username', 'test_player') cls.server = MockServerAdapter() cls.strategy = MockAIStrategy()
def i_show_articles(step): config_manager = ConfigManager() config_manager.db_path = world.path_db db_file_connector = DbFileConnector(config_manager) db = DBConnector(db_file_connector) world.articles = db.get_all_articles()
def __init__(self, *args, **kwargs): super(SavedConfigs, self).__init__(*args, **kwargs) # new ConfigManager for read saved configs self.config_manager = ConfigManager()
if os.path.exists(file): fp = open(file, "r") content = fp.read() fp.close() return content def writeFile(file, content): fp = open(file, "w") fp.write(content) fp.close() config_manager = ConfigManager() config = config_manager.get() #Run all languages to group all the words try: for language in config['languages']: words = [] try: if not (config['wake_word'] in words): words.append(config['wake_word']) except KeyError: print('Wake word required') sys.exit(1) pass
def __init__(self, config_path): self.config = ConfigManager(config_path) self.enviroment = ConfigManager(self.config.enviroment_location) self.package_path = self.config.temp_dir + "/src" self.package_zip = self.config.temp_dir + "/package"
import sys import json import os import validators as val from config_manager import ConfigManager # Find the proper config file current_dir = os.path.dirname(os.path.abspath(__file__)) parent_dir = os.path.dirname(current_dir) cfg_dir = os.path.join(parent_dir, 'cfg') config_file = os.path.join(cfg_dir, 'config.json') dft_cfg_file = os.path.join(cfg_dir, 'default_config.json') # Used to manage configuration files - read, write and changes cfg = ConfigManager(config_file, dft_cfg_file) # Dicts of menu options - to avoid using strings in the whole program mm_choices = { 'current_sett': 'Show current settings from file', 'edit_sett': 'Edit settings', 'preview_ch': 'Preview changes', 'save_ch': 'Save changes to file', 'back': 'Back to main menu without saving' } main_cfg_choices = { 'elemental': 'Elemental server - IP and credentials', 'stream': 'Stream-GPI pairs - number of streams and GPI mapping', 'avail': 'Minimum avail duration - Enable/Disable, Duration', 'back': 'Back to main configuration menu'
return dictionary if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(\ description='Run a simulation using a specified scenario.', epilog='Any extra argument passed through the CLI will be used to overwrite scenario parameters. Do not enter spaces in the values or add quotes! Ex: --start [20,10] --goal "[21, 11]"') parser.add_argument('--version', action='store_true', \ help='Displays the current version of the simulator.') parser.add_argument('--scenario', metavar='S', nargs='?',\ help='Path to the configuration JSON in which the scenario is defined.') parser.add_argument('--controller', metavar='C', nargs='?',\ help='Path to the controller that you want to use. This will override the scenario one if there was any.') args, unknown = parser.parse_known_args() unknown_args = args_list_to_dict(unknown) if args.version: print('R2P2 v.' + __version__) exit() if args.scenario: config_mgr = ConfigManager(scenario_config=args.scenario, controller_config=args.controller, params=unknown_args) else: config_mgr = ConfigManager(controller_config=args.controller, params=unknown_args) start_simulation(config_mgr)
from config_manager import ConfigManager if __name__ == '__main__': # Connecting to ConfigManager cf = ConfigManager('192.168.0.3', '8080') # getting access to the health monitor proxy health_monitor_proxy = cf.get_proxy('/health_monitor') print('Testing connection with health monitor:') print(health_monitor_proxy.test_connection(), '\n') functions = health_monitor_proxy.get_function_list() functions = functions['functions'] print('The available functions are') for function in functions: print(' -', function) print() attributes = health_monitor_proxy.get_attribute_list() attributes = attributes['attributes'] print('The available attributes are') for attribute in attributes: print(' -', attribute) print() # Executing commands on the health monitor print('Executing : administer_insulin')
def init_UI(self): self.sprayTimeVar = tk.StringVar() self.sprayTimeVar.set( str(ConfigManager().get_value("auto_spray_duration_sec"))) self.cycleTimeVar = tk.StringVar() self.cycleTimeVar.set(str(ConfigManager().get_value("auto_cycle_min"))) self.btnHome.place(relx=0.93, rely=0.03) #분사주기 조절 lblCycleTime = tk.Label(self.frame, fg="white", bg=self.COLOR_BUTTON_BACKGROUND, font=tkfont.Font(size=50, weight="bold"), textvariable=self.cycleTimeVar, anchor="e", padx=10) lblCycleTime.place(relx=0.45, rely=0.36, relwidth=0.18, relheight=0.18) btnCycleTimeUp = tk.Button(self.frame, relief="solid", bd=0, highlightthickness=0, command=lambda: self.upCycleTime(), image=self.imgBtnUp, bg=self.COLOR_BUTTON_BACKGROUND) btnCycleTimeUp.place(relx=0.66, rely=0.38) btnCycleTimeDown = tk.Button(self.frame, relief="solid", bd=0, highlightthickness=0, command=lambda: self.downCycleTime(), image=self.imgBtnDown, bg=self.COLOR_BUTTON_BACKGROUND) btnCycleTimeDown.place(relx=0.76, rely=0.38) #분사시간 조절 lblTime = tk.Label(self.frame, fg="white", bg=self.COLOR_BUTTON_BACKGROUND, font=tkfont.Font(size=50, weight="bold"), textvariable=self.sprayTimeVar, anchor="e", padx=10) lblTime.place(relx=0.45, rely=0.36 + 0.22, relwidth=0.18, relheight=0.18) btnTimeUp = tk.Button(self.frame, image=self.imgBtnUp, relief="solid", bd=0, highlightthickness=0, bg=self.COLOR_BUTTON_BACKGROUND, command=lambda: self.upTime()) btnTimeUp.place(relx=0.66, rely=0.38 + 0.22) btnTimeDown = tk.Button(self.frame, image=self.imgBtnDown, relief="solid", bd=0, highlightthickness=0, bg=self.COLOR_BUTTON_BACKGROUND, command=lambda: self.downTime()) btnTimeDown.place(relx=0.76, rely=0.38 + 0.22)
def __init__(self): self.config = ConfigManager("cfg.ini") connection = self.config.getDatabaseConnectionString() self.db = psycopg2.connect(connection)
def get_value(self, attribute_): return int(ConfigManager().get_value(attribute_))
def set_value(self, attribute_, value_): ConfigManager().set_value(attribute_, value_)
'%(asctime)s [%(name)s-%(process)d] [%(levelname)s] - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) # Load configs config_path = '.artifactory_replicator/config.json' config_manager = None logger.info('Loading configuration ' + config_path) try: defaults = {} required = ['source_username'] config_manager = ConfigManager(config_file_path=config_path, defaults=defaults, required=required) logger.info('Configuration loaded') except (OSError, IOError) as exception: logger.warn('Abondoning config load') else: # Repository instances representative of the source and destination repositories. source_repository = Repository( username=config_manager['source_username'], password=config_manager['source_password'], repository_name=config_manager['source_repository_name'], base_url=config_manager['source_base_url'], delete_temp_directory=config_manager['delete_temp_directory'], max_concurrent_threads=config_manager['max_concurrent_threads'],
def load_configuration(self): settings = ConfigManager('general_config.json').settings extensions = settings['extension'] return extensions
def i_show_available_articles(step): config_manager = ConfigManager() config_manager.db_path = world.path_db db_file_connector = DbFileConnector(config_manager) db = DBConnector(db_file_connector) world.articles = db.get_articles_by_availability(True)
def i_get_article_by_name(step, name): config_manager = ConfigManager() config_manager.db_path = world.path_db db_file_connector = DbFileConnector(config_manager) db = DBConnector(db_file_connector) world.articles = db.get_articles_by_name(name)
def i_have_no_configuration_file(step): world.path_config = 'test_config.json' world.config = ConfigManager()