Best Python code snippet using tempest_python
misp_common.py
Source:misp_common.py  
1# coding=utf-82import json3import os4from splunk.clilib import cli_common as cli5import splunklib6from io import open7__license__ = "LGPLv3"8__version__ = "4.0.0"9__maintainer__ = "Remi Seguy"10__email__ = "remg427@gmail.com"11# set up logger suitable for splunkd consumption12def logging_level(app_name):13    """14    This function sets logger to the defined level in15    misp42splunk app and writes logs to a dedicated file16    """17    # retrieve log level18    _SPLUNK_PATH = os.environ['SPLUNK_HOME']19    settings_file = os.path.join(20        _SPLUNK_PATH, 'etc', 'apps', app_name,21        'local', app_name + '_settings.conf'22    )23    run_level = 'ERROR'24    if os.path.exists(settings_file):25        app_settings = cli.readConfFile(settings_file)26        for name, content in list(app_settings.items()):27            if 'logging' in name:28                if 'loglevel' in content:29                    set_level = content['loglevel']30                    if set_level in ['DEBUG', 'INFO', 'WARNING',31                                     'ERROR', 'CRITICAL']:32                        run_level = set_level33    return run_level34def prepare_config(helper, app_name, misp_instance, storage_passwords, session_key=None):35    config_args = dict()36    # get settings for MISP instance37    if session_key is None:38        response = helper.service.get('misp42splunk_instances')39    else:40        service = splunklib.client.connect(token=session_key)41        response = service.get('misp42splunk_instances')42    helper.log_debug("[MC-PC-D01] response.status={}".format(response.status))43    if response.status == 200:44        data_body = splunklib.data.load(response.body.read())45    else:46        helper.log_error("[MC-PC-E01] Unexpected status received {}".format(response.status))47        raise Exception("[MC-PC-E01] Unexpected status received %s", str(response.status))48        return None49    foundStanza = False50    instance_count = int(data_body['feed']['totalResults'])51    helper.log_debug("[MC-PC-D02] instance_count={}".format(instance_count))52    if instance_count == 0:  # No misp instance configured53        helper.log_error("[MC-PC-E02] no misp instance configured")54        raise Exception("[MC-PC-E02] no misp instance configured. Please configure an entry for %s", str(misp_instance))55        return None56    elif instance_count == 1:  # Single misp instance configured57        instance = data_body['feed']['entry']58        helper.log_debug("[MC-PC-D03] single instance={}".format(instance))59        if misp_instance == str(instance['title']):60            app_config = instance['content']61            foundStanza = True62    else:  # Multiple misp instances configured63        misp_instances = data_body['feed']['entry']64        for instance in list(misp_instances):65            helper.log_debug("[MC-PC-D04] instance item={}".format(instance))66            if misp_instance == str(instance['title']):67                app_config = instance['content']68                foundStanza = True69    if not foundStanza:70        raise Exception("[MC-PC-E03] no misp_instance with specified name found: %s ", str(misp_instance))71        return None72    # save MISP settings stored in app_config into config_arg73    misp_url = str(app_config.get('misp_url', '')).rstrip('/')74    if misp_url.startswith('https://'):75        config_args['misp_url'] = misp_url76    else:77        raise Exception("[MC-PC-E04] misp_url must start with https://. Please set a valid misp_url")78        return None79    if int(app_config.get('misp_verifycert', '0')) == 1:80        misp_ca_full_path = app_config.get('misp_ca_full_path', '')81        if misp_ca_full_path != '':82            config_args['misp_verifycert'] = misp_ca_full_path83        else:84            config_args['misp_verifycert'] = True85    else:86        config_args['misp_verifycert'] = False87    # get client cert parameters88    if int(app_config.get('client_use_cert', '0')) == 1:89        config_args['client_cert_full_path'] = app_config.get('client_cert_full_path', 'no_path')90    else:91        config_args['client_cert_full_path'] = None92    # test if client certificate file is readable93    if config_args['client_cert_full_path'] is not None:94        try:95            # open client_cert_full_path if exists and log.96            with open(config_args['client_cert_full_path'], 'rb'):97                helper.log_info(98                    "client_cert_full_path file at {} was successfully opened".format(config_args['client_cert_full_path']))99        except IOError:  # file misp_instances.csv not readable100            helper.log_error(101                "[MC-PC-E05] client_cert_full_path file at {} not readable".format(config_args['client_cert_full_path'])102            )103            raise Exception(104                "[MC-PC-E05] client_cert_full_path file at {} not readable".format(config_args['client_cert_full_path'])105            )106            return None107    # get clear version of misp_key and proxy password108    config_args['misp_key'] = None109    proxy_clear_password = None110    # avoid picking wrong key if stanza is a substring of another stanza111    misp_instance_index = misp_instance + "``splunk_cred_sep``"112    for credential in storage_passwords:113        cred_app_name = credential.access.get('app')114        if (app_name in cred_app_name) and (cred_app_name is not None):115            username = credential.content.get('username')116            if misp_instance_index in username:117                clear_credentials = credential.content.get('clear_password')118                if 'misp_key' in clear_credentials:119                    misp_instance_key = json.loads(clear_credentials)120                    config_args['misp_key'] = str(misp_instance_key['misp_key'])121            elif 'proxy' in username:122                clear_credentials = credential.content.get('clear_password')123                if 'proxy_password' in clear_credentials:124                    proxy_creds = json.loads(clear_credentials)125                    proxy_clear_password = str(proxy_creds['proxy_password'])126    if config_args['misp_key'] is None:127        raise Exception("[MC205] misp_key NOT found for instance {}".format(misp_instance))128        return None129    # get proxy parameters if any130    config_args['proxies'] = dict()131    if int(app_config.get('misp_use_proxy', '0')) == 1:132        proxy = None133        settings_file = os.path.join(134            os.environ['SPLUNK_HOME'], 'etc', 'apps', app_name,135            'local', app_name + '_settings.conf'136        )137        if os.path.exists(settings_file):138            app_settings = cli.readConfFile(settings_file)139            for name, content in list(app_settings.items()):140                if 'proxy' in name:141                    proxy = content142        if proxy:143            proxy_url = '://'144            if 'proxy_username' in proxy \145               and proxy_clear_password is not None:146                if proxy['proxy_username'] not in ['', None]:147                    proxy_url = proxy_url + \148                        proxy['proxy_username'] + ':' \149                        + proxy_clear_password + '@'150            proxy_url = proxy_url + proxy['proxy_hostname'] + \151                ':' + proxy['proxy_port'] + '/'152            config_args['proxies'] = {153                "http": "http" + proxy_url,154                "https": "https" + proxy_url155            }...test_tpclient.py
Source:test_tpclient.py  
...36        return self.assertEquals(scheme, *args)37    def test_adjust_scheme(self):38        c = typepad.tpclient.TypePadClient()39        c.endpoint = 'http://api.typepad.com'40        c.clear_credentials()41        self.assertScheme(c.endpoint, 'http')42        c.clear_credentials()43        c.add_credentials('a', 'b')44        self.assertScheme(c.endpoint, 'http')45        c.clear_credentials()46        c.add_credentials('a', 'b', domain='api.typepad.com')47        self.assertScheme(c.endpoint, 'http')48        c.clear_credentials()49        c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'))50        self.assertScheme(c.endpoint, 'https')51        c.clear_credentials()52        c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='api.example.com')53        self.assertScheme(c.endpoint, 'http')54        c.clear_credentials()55        c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='typepad.com')56        self.assertScheme(c.endpoint, 'http')57        # This time for sure!!58        c.clear_credentials()59        c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='api.typepad.com')60        self.assertScheme(c.endpoint, 'https')61        # Try it again.62        c.clear_credentials()63        c.add_credentials(OAuthConsumer('a', 'b'), OAuthToken('c', 'd'), domain='api.typepad.com')64        self.assertScheme(c.endpoint, 'https')65        # Check that clearing works.66        c.clear_credentials()67        self.assertScheme(c.endpoint, 'http')68    def test_consumer_property(self):69        c = typepad.tpclient.TypePadClient()70        c.endpoint = 'http://api.typepad.com'71        # make sure initial credentials are clear72        self.assert_(len(c.authorizations) == 0)73        self.assert_(len(c.credentials.credentials) == 0)74        # we can specify consumer and token as OAuth objects75        c.consumer = OAuthConsumer('x', 'y')76        c.token = OAuthToken('z', 'q')77        self.assert_(len(c.credentials.credentials) == 1)78        self.assertScheme(c.endpoint, 'https')79        # we can specify consumer and token as tuples of key/secrets80        c.consumer = ('a', 'b')81        c.token = ('a', 'b')82        self.assert_(len(c.credentials.credentials) == 1)83        self.assertScheme(c.endpoint, 'https')84        # assigning "None" to either token or consumer will85        # effectively clear credentials also86        c.token = None87        self.assert_(len(c.credentials.credentials) == 0)88        self.assertScheme(c.endpoint, 'http')89        c.clear_credentials()...config.py
Source:config.py  
...49				return d.decode('utf-8')50			except:51				if route == 'PASSWORD':52					dialog.ok(addon_id, translation(30507))53					self.clear_credentials()54				return ""55		elif not its_base64 and self.force_encrypt is False:56			debug_MS("(config.vers_decrypt) XXX '{0}' IS NORMAL - NOT BASE64-ENCODED XXX".format(route))57			return data58		else:59			if route == 'PASSWORD':60				dialog.ok(addon_id, translation(30507))61				self.clear_credentials()62			return ""6364	def has_credentials(self):65		debug_MS("(config.has_credentials) ### START has_credentials ###")66		if self.username is not None and self.password is not None:67			if len(self.username) > 0 and len(self.password) >= 6:68				return True69		else:70			xbmc.sleep(3000)71			if self.username is not None and self.password is not None:72				if len(self.username) > 0 and len(self.password) >= 6:73					return True74		return False7576	def get_credentials(self):77		debug_MS("(config.get_credentials) ### START get_credentials ###")78		return (self.vers_decrypt(self.username, 'USERNAME'), self.vers_decrypt(self.password, 'PASSWORD'))7980	def save_credentials(self):81		debug_MS("(config.save_credentials) ### START save_credentials ###")82		USER = dialog.input(translation(30671), type=xbmcgui.INPUT_ALPHANUM)83		PASSWORD = dialog.input(translation(30672), type=xbmcgui.INPUT_ALPHANUM)84		if self.force_encrypt is True:85			_user = self.vers_encrypt(USER) if USER != '' else USER86			_code = self.vers_encrypt(PASSWORD) if PASSWORD != '' else PASSWORD87			debug_MS("(config.save_credentials) XXX encrypt-USER : {0} || encrypt-PASSWORD : {1} XXX".format(_user, _code))88		else:89			_user = USER90			_code = PASSWORD91			debug_MS("(config.save_credentials) XXX standard-USER : {0} || standard-PASSWORD : {1} XXX".format(_user, _code))92		addon.setSetting('username', _user)93		addon.setSetting('password', _code)94		return (USER, PASSWORD)9596	def clear_credentials(self):97		debug_MS("(config.clear_credentials) ### START clear_credentials ###")98		addon.setSetting('username', '')99		addon.setSetting('password', '')100		addon.setSetting('select_start', '0')101		if self.session_file is not None and os.path.isfile(self.session_file):102			if xbmcvfs.exists(self.tempSESS_folder) and os.path.isdir(self.tempSESS_folder):
...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
