def test_config_defaults(self): """ Test the 'CWD' config file using the _test_general() function. """ #PULL IN CONFIG conf = config.loadconfig(filename=self._file) #RUN TESTS self.assertTrue(self._test_general(conf))
def test_config_fullpath(self): """ Test the 'defined path' config file using the _test_general() function. """ #PULL IN CONFIG conf = config.loadconfig(filename=os.path.join(self._path, self._file)) #RUN TESTS self.assertTrue(self._test_general(conf))
def test_dict2obj(self): """Test the loadconfig() return_as_obj parameter.""" # READ CONFIG cfg = config.loadconfig(filename=os.path.join(self._path, self._file), return_as_obj=True) # TEST DATA TYPE self.assertTrue(isinstance(cfg, utils3.dict2obj.Dict2Obj)) # TEST CONTENTS self.assertTrue(cfg.path == self._path) self.assertTrue(cfg.file == self._file)
def _dbconn_fields(dbtype, fields, filename): """Extract database credentials from a JSON file, prompt for missing values. Args: dbtype (str): Type of the database being connected. fields (list): List of credentials to test. For example:: ['server', 'user', 'password', 'port'] filename (str): Full file path to the credentials JSON file. :Design: Using the passed file, the config key/value pairs are loaded into a dictionary where a test is made to determine if the expected fields (as defined by the ``fields`` argument) is present. If an expected field is missing, the user is prompted for the value. Note: This function handles the **credential file parsing** and **credential prompting** for the following classes: * :class:`~database.MySQL` * :class:`~database.Oracle` * :class:`~database.SQLServer` Returns: A completed credential dictionary. """ try: # INITIALISE creds = dict() # LOAD CONNECTION DETAILS FROM CONFIG FILE conf = config.loadconfig(filename=filename) # LOOP THROUGH EXPECTED KEYS for key in fields: # TEST KEY EXISTS IN CONFIG FILE if key in conf: # ADD EXISTING VALUE TO CREDENTIAL DICT (USED FOR CONNECTION) creds[key] = conf[key] else: # PROMPT FOR VALUE >> ADD TO CREDENTIAL DICT creds[key] = six.moves.input('Please enter the %s %s: ' % (dbtype, key)) # RETURN DICTIONARY OF CREDENTIALS return creds except Exception as err: # USER NOTIFICATION _UI.print_alert('\nAn error occurred while checking the database credentials in the ' 'config file.\nFilename used: %s' % filename) _UI.print_error(err) return None
def __init__(self): r"""Class initialiser. :Purpose: This constructor initialises ``colorama`` - which enables the user to print coloured text to the Windows CLI - and loads the config file, which is used throughout the class. :Background win_unicode_console: ``win_unicode_console`` is used here to fix a problem between the Python :func:`~input` function and the Windows CLI. The problem causes ANSI characters to be **displayed** to the console, rather than **setting** colours. Note: It **may** be possible to remove use of ``win_unicode_console`` when/if we move to Python 3.6. :Background colorama: Colorama is initialised here to "strip ANSI characters from stdout and convert them into the equivalent win32 calls"; per Jonathan Hartley, creator of Colorama. The Win32 console (excluding *some* versions of Win10) does not support ANSI escape sequences, and therefore (unlike \*nix) simply printing the escape sequence to the native Win CLI with the text does not work. So we use Colorama for the low-level win32 work. Thanks Jonathan!! """ # RUN ONLY IF WINDOWS if 'win' in platform.system().lower(): # INSTALL FIX FOR PYTHON 3 WINDOWS CLI ISSUE self._enable_win_unicode_console() # COLORAMA INITIALISATION colourinit() # SET LOCATION OF THE UI CONFIG FILE EXPLICITLY (SHOULD WORK FOR WIN AND LINUX) ui_config_file = os.path.join( os.path.realpath(os.path.dirname(__file__)), 'user_interface_config.json') # LOAD CONFIG FILE self._cfg = config.loadconfig(filename=ui_config_file) # BUILD REFERENCE DICTS OF COLORAMA FORE / BACK / STYLE self._fore = self._build_color_dict(class_=Fore) self._back = self._build_color_dict(class_=Back) self._style = self._build_color_dict(class_=Style)
def __init__(self, name=None, version=None, desc=None, info=None, chars=72, ribbon='-', fore='white', back='black', style='bright'): """Display a configurable information banner to the CLI. :Design: In short, if the ``info`` parameter is left as ``None``, a default banner is generated using the values passed into the ``name``, ``version`` and ``desc`` parameters. The string templates used for the banner layout may be configured in the ``user_interface_config.json`` config file. Additional configuration is available through the other parameters, which are all defined in the **Parameters** section below. Also, the title of the console window is updated to show the program's name and version, if all of the following criteria are met: * Windows OS * ``name`` parameter is not ``None`` * ``version`` parameter is not ``None`` Args: name (str): Name of your program. version (str): The program's version number. desc (str): Description of what your program is all about. info (list): The info parameter is used to generate a completely customised banner. Basically, whatever key/value pairs you pass in, are what will be printed in the banner. This parameter accepts a **list of dictionaries**. For example, this code:: info = [{'Program':'bob_the_great'}, {'Version':'2.0.3'}, {'':''}, {'Description':'Gives proof why Bob is great.'}, {'Comments':'Some more reasons Bob is so great.'}] ... will print this:: ---------------------------------------------------------------- Program : bob_the_great Version : 2.0.3 Description : Gives proof why Bob is great. Comments : Some more reasons Bob is so great. ---------------------------------------------------------------- chars (int): In the number of characters, the size of the buffer used for the background colour, and the length of the ribbon. ribbon (str): The character(s) to use for the ribbon. If multiple characters are passed into this parameter, these characters will be repeated until the length of the ``chars`` parameter is met. fore (str): Text colour. The eight basic colour names are accepted as strings. back (str): Background colour. The eight basic colour names are accepted as strings. style (str): Brightness of the text/background. Accepted strings: * dim * bright (default) * normal :Example: Use this code:: import utils3.user_interface as ui ui.PrintBanner(name='bob_the_great', version='2.0.3', desc='Gives proof why Bob is so great.', chars=55, ribbon='~-', fore='yellow', back='black', style='bright') ... to print this:: ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- Program : bob_the_great Version : 2.0.3 Description : Gives proof why Bob is so great. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- """ # SET LOCATION OF THE UI CONFIG FILE EXPLICITLY conf_file = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'user_interface_config.json') # INITIALISE self._name = name self._version = version self._desc = desc self._info = info self._chars = chars self._ribbon = ribbon * (chars // len(ribbon)) self._fore = fore self._back = back self._style = style self._to_print = [] self._blank = '' self._spaces = ' ' * 4 self._pad = 15 self._adtl = 4 self._cfg = config.loadconfig(conf_file) self._ui = UserInterface() # PRINT PROGRAM INFO BANNER self._print_prog_banner() # UPDATE CONSOLE WINDOW TITLE self._update_console_title()