How to use _is_method_shortcut method in gabbi

Best Python code snippet using gabbi_python

driver.py

Source:driver.py Github

copy

Full Screen

...117 If there is no upper case key then 'url' must be present.118 """119 method_key = None120 for key, val in six.iteritems(test):121 if _is_method_shortcut(key):122 if method_key:123 raise GabbiFormatError(124 'duplicate method/URL directive in "%s"' %125 test_name)126 test['method'] = key127 test['url'] = val128 method_key = key129 if method_key:130 del test[method_key]131 if not test['url']:132 raise GabbiFormatError('Test url missing in test %s.'133 % test_name)134 def _validate_keys(self, test, test_name):135 """Check for invalid keys.136 If there are any, raise a GabbiFormatError.137 """138 test_keys = set(test.keys())139 if test_keys != self.default_keys:140 raise GabbiFormatError(141 'Invalid test keys used in test %s: %s'142 % (test_name,143 ', '.join(list(test_keys - self.default_keys))))144class TestBuilder(type):145 """Metaclass to munge a dynamically created test."""146 required_attributes = {'has_run': False}147 def __new__(mcs, name, bases, attributes):148 attributes.update(mcs.required_attributes)149 return type.__new__(mcs, name, bases, attributes)150def build_tests(path, loader, host=None, port=8001, intercept=None,151 test_loader_name=None, fixture_module=None,152 response_handlers=None, prefix=''):153 """Read YAML files from a directory to create tests.154 Each YAML file represents an ordered sequence of HTTP requests.155 :param path: The directory where yaml files are located.156 :param loader: The TestLoader.157 :param host: The host to test against. Do not use with ``intercept``.158 :param port: The port to test against. Used with ``host``.159 :param intercept: WSGI app factory for wsgi-intercept.160 :param test_loader_name: Base name for test classes. Rarely used.161 :param fixture_module: Python module containing fixture classes.162 :param response_handers: ResponseHandler classes.163 :type response_handlers: List of ResponseHandler classes.164 :param prefix: A URL prefix for all URLs that are not fully qualified.165 :rtype: TestSuite containing multiple TestSuites (one for each YAML file).166 """167 # Exit immediately if we have no host to access, either via a real host168 # or an intercept.169 if not (bool(host) ^ bool(intercept)):170 raise AssertionError('must specify exactly one of host or intercept')171 if test_loader_name is None:172 test_loader_name = inspect.stack()[1]173 test_loader_name = os.path.splitext(os.path.basename(174 test_loader_name[1]))[0]175 # Initialize response handlers.176 response_handlers = response_handlers or []177 for handler in RESPONSE_HANDLERS + response_handlers:178 handler(case.HTTPTestCase)179 top_suite = suite.TestSuite()180 for test_file in glob.iglob('%s/*.yaml' % path):181 if intercept:182 host = str(uuid.uuid4())183 suite_dict = load_yaml(test_file)184 test_base_name = '%s_%s' % (185 test_loader_name, os.path.splitext(os.path.basename(test_file))[0])186 file_suite = test_suite_from_dict(loader, test_base_name, suite_dict,187 path, host, port, fixture_module,188 intercept, prefix)189 top_suite.addTest(file_suite)190 return top_suite191def load_yaml(yaml_file):192 """Read and parse any YAML file. Let exceptions flow where they may."""193 with open(yaml_file) as source:194 return yaml.safe_load(source.read())195def test_update(orig_dict, new_dict):196 """Modify test in place to update with new data."""197 for key, val in six.iteritems(new_dict):198 if key == 'data':199 orig_dict[key] = val200 elif isinstance(val, dict):201 orig_dict[key].update(val)202 elif isinstance(val, list):203 orig_dict[key] = orig_dict.get(key, []) + val204 else:205 orig_dict[key] = val206def test_suite_from_dict(loader, test_base_name, suite_dict, test_directory,207 host, port, fixture_module, intercept, prefix=''):208 """Generate a TestSuite from YAML-sourced data."""209 try:210 test_data = suite_dict['tests']211 except KeyError:212 raise GabbiFormatError('malformed test file, "tests" key required')213 except TypeError:214 # `suite_dict` appears not to be a dictionary; we cannot infer215 # any details or suggestions on how to fix it, thus discarding216 # the original exception in favor of a generic error217 raise GabbiFormatError('malformed test file, invalid format')218 # Merge global with per-suite defaults219 default_test_dict = copy.deepcopy(case.HTTPTestCase.base_test)220 local_defaults = _validate_defaults(suite_dict.get('defaults', {}))221 test_update(default_test_dict, local_defaults)222 # Establish any fixture classes used in this file.223 fixtures = suite_dict.get('fixtures', None)224 fixture_classes = []225 if fixtures and fixture_module:226 for fixture_class in fixtures:227 fixture_classes.append(getattr(fixture_module, fixture_class))228 test_maker = TestMaker(test_base_name, default_test_dict, test_directory,229 fixture_classes, loader, host, port, intercept,230 prefix)231 file_suite = gabbi_suite.GabbiSuite()232 prior_test = None233 for test_dict in test_data:234 this_test = test_maker.make_one_test(test_dict, prior_test)235 file_suite.addTest(this_test)236 prior_test = this_test237 return file_suite238def test_suite_from_yaml(loader, test_base_name, test_yaml, test_directory,239 host, port, fixture_module, intercept, prefix=''):240 """Legacy wrapper retained for backwards compatibility."""241 import warnings242 with warnings.catch_warnings(): # ensures warnings filter is restored243 warnings.simplefilter('default', DeprecationWarning)244 warnings.warn('test_suite_from_yaml has been renamed to '245 'test_suite_from_dict', DeprecationWarning, stacklevel=2)246 return test_suite_from_dict(loader, test_base_name, test_yaml,247 test_directory, host, port, fixture_module,248 intercept, prefix)249def _validate_defaults(defaults):250 """Ensure default test settings are acceptable.251 Raises GabbiFormatError for invalid settings.252 """253 if any(_is_method_shortcut(key) for key in defaults):254 raise GabbiFormatError('"METHOD: url" pairs not allowed in defaults')255 return defaults256def _is_method_shortcut(key):257 """Is this test key indicating a request method.258 It is a request method if it is all upper case.259 """...

Full Screen

Full Screen

suitemaker.py

Source:suitemaker.py Github

copy

Full Screen

...135 If there is no upper case key then 'url' must be present.136 """137 method_key = None138 for key, val in test.items():139 if _is_method_shortcut(key):140 if method_key:141 raise GabbiFormatError(142 'duplicate method/URL directive in "%s"' %143 test_name)144 test['method'] = key145 test['url'] = val146 method_key = key147 if method_key:148 del test[method_key]149 if not test['url']:150 raise GabbiFormatError('Test url missing in test %s.'151 % test_name)152 def _validate_keys(self, test, test_name):153 """Check for invalid keys.154 If there are any, raise a GabbiFormatError.155 """156 test_keys = set(test.keys())157 if test_keys != self.default_keys:158 raise GabbiFormatError(159 'Invalid test keys used in test %s: %s'160 % (test_name,161 ', '.join(list(test_keys - self.default_keys))))162class TestBuilder(type):163 """Metaclass to munge a dynamically created test."""164 required_attributes = {'has_run': False}165 def __new__(mcs, name, bases, attributes):166 attributes.update(mcs.required_attributes)167 return type.__new__(mcs, name, bases, attributes)168def test_suite_from_dict(loader, test_base_name, suite_dict, test_directory,169 host, port, fixture_module, intercept, prefix='',170 handlers=None, test_loader_name=None,171 inner_fixtures=None):172 """Generate a GabbiSuite from a dict represent a list of tests.173 The dict takes the form:174 :param fixtures: An optional list of fixture classes that this suite175 can use.176 :param defaults: An optional dictionary of default values to be used177 in each test.178 :param tests: A list of individual tests, themselves each being a179 dictionary. See :data:`gabbi.case.BASE_TEST`.180 """181 try:182 test_data = suite_dict['tests']183 except KeyError:184 raise GabbiFormatError('malformed test file, "tests" key required')185 except TypeError:186 # `suite_dict` appears not to be a dictionary; we cannot infer187 # any details or suggestions on how to fix it, thus discarding188 # the original exception in favor of a generic error189 raise GabbiFormatError('malformed test file, invalid format')190 handlers = handlers or []191 response_handlers = []192 content_handlers = []193 # Merge global with per-suite defaults194 default_test_dict = copy.deepcopy(case.HTTPTestCase.base_test)195 seen_keys = set()196 for handler in handlers:197 default_test_dict.update(copy.deepcopy(handler.test_base))198 if handler.response_handler:199 if handler.test_key_suffix not in seen_keys:200 response_handlers.append(handler.response_handler)201 seen_keys.add(handler.test_key_suffix)202 if handler.content_handler:203 content_handlers.append(handler.content_handler)204 local_defaults = _validate_defaults(suite_dict.get('defaults', {}))205 test_update(default_test_dict, local_defaults)206 # Establish any fixture classes used in this file.207 fixtures = suite_dict.get('fixtures', None)208 fixture_classes = []209 if fixtures and fixture_module:210 for fixture_class in fixtures:211 fixture_classes.append(getattr(fixture_module, fixture_class))212 test_maker = TestMaker(test_base_name, default_test_dict, test_directory,213 fixture_classes, loader, host, port, intercept,214 prefix, response_handlers, content_handlers,215 test_loader_name=test_loader_name,216 inner_fixtures=inner_fixtures)217 file_suite = suite.GabbiSuite()218 prior_test = None219 for test_dict in test_data:220 this_test = test_maker.make_one_test(test_dict, prior_test)221 file_suite.addTest(this_test)222 prior_test = this_test223 return file_suite224def test_update(orig_dict, new_dict):225 """Modify test in place to update with new data."""226 for key, val in new_dict.items():227 if key == 'data':228 orig_dict[key] = val229 elif isinstance(val, dict):230 orig_dict[key].update(val)231 elif isinstance(val, list):232 orig_dict[key] = orig_dict.get(key, []) + val233 else:234 orig_dict[key] = val235def _is_method_shortcut(key):236 """Is this test key indicating a request method.237 It is a request method if it is all upper case.238 """239 return key.isupper()240def _validate_defaults(defaults):241 """Ensure default test settings are acceptable.242 Raises GabbiFormatError for invalid settings.243 """244 if any(_is_method_shortcut(key) for key in defaults):245 raise GabbiFormatError('"METHOD: url" pairs not allowed in defaults')...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run gabbi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful