How to use make_one_test method in gabbi

Best Python code snippet using gabbi_python

driver.py

Source:driver.py Github

copy

Full Screen

...58 self.port = port59 self.loader = loader60 self.intercept = intercept61 self.prefix = prefix62 def make_one_test(self, test_dict, prior_test):63 """Create one single HTTPTestCase.64 The returned HTTPTestCase is added to the TestSuite currently65 being built (one per YAML file).66 """67 test = copy.deepcopy(self.test_defaults)68 try:69 test_update(test, test_dict)70 except KeyError as exc:71 raise GabbiFormatError('invalid key in test: %s' % exc)72 except AttributeError as exc:73 if not isinstance(test_dict, dict):74 raise GabbiFormatError(75 'test chunk is not a dict at "%s"' % test_dict)76 else:77 # NOTE(cdent): Not clear this can happen but just in case.78 raise GabbiFormatError(79 'malformed test chunk "%s": %s' % (test_dict, exc))80 test_name = self._set_test_name(test)81 self._set_test_method_and_url(test, test_name)82 self._validate_keys(test, test_name)83 http_class = httpclient.get_http(verbose=test['verbose'],84 caption=test['name'])85 # Use metaclasses to build a class of the necessary type86 # and name with relevant arguments.87 klass = TestBuilder(test_name, (case.HTTPTestCase,),88 {'test_data': test,89 'test_directory': self.test_directory,90 'fixtures': self.fixture_classes,91 'http': http_class,92 'host': self.host,93 'intercept': self.intercept,94 'port': self.port,95 'prefix': self.prefix,96 'prior': prior_test})97 tests = self.loader.loadTestsFromTestCase(klass)98 # Return the first (and only) test in the klass.99 return tests._tests[0]100 def _set_test_name(self, test):101 """Set the name of the test102 The original name is lowercased and spaces are replaces with '_'.103 The result is appended to the test_base_name, which is based on the104 name of the input data file.105 """106 if not test['name']:107 raise GabbiFormatError('Test name missing in a test in %s.'108 % self.test_base_name)109 return '%s_%s' % (self.test_base_name,110 test['name'].lower().replace(' ', '_'))111 @staticmethod112 def _set_test_method_and_url(test, test_name):113 """Extract the base URL and method for this test.114 If there is an upper case key in the test, that is used as the115 method and the value is used as the URL. If there is more than116 one uppercase that is a GabbiFormatError.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)...

Full Screen

Full Screen

suitemaker.py

Source:suitemaker.py Github

copy

Full Screen

...47 self.test_loader_name = test_loader_name48 self.inner_fixtures = inner_fixtures or []49 self.content_handlers = content_handlers50 self.response_handlers = response_handlers51 def make_one_test(self, test_dict, prior_test):52 """Create one single HTTPTestCase.53 The returned HTTPTestCase is added to the TestSuite currently54 being built (one per YAML file).55 """56 test = copy.deepcopy(self.test_defaults)57 try:58 test_update(test, test_dict)59 except KeyError as exc:60 raise GabbiFormatError('invalid key in test: %s' % exc)61 except AttributeError as exc:62 if not isinstance(test_dict, dict):63 raise GabbiFormatError(64 'test chunk is not a dict at "%s"' % test_dict)65 else:66 # NOTE(cdent): Not clear this can happen but just in case.67 raise GabbiFormatError(68 'malformed test chunk "%s": %s' % (test_dict, exc))69 test_name = self._set_test_name(test)70 self._set_test_method_and_url(test, test_name)71 self._validate_keys(test, test_name)72 # Set server hostname in http request if host header is set.73 if 'request_headers' in test and 'host' in test['request_headers']:74 hostname = test['request_headers']['host']75 else:76 hostname = None77 http_class = httpclient.get_http(verbose=test['verbose'],78 caption=test['name'],79 cert_validate=test['cert_validate'],80 hostname=hostname)81 if prior_test:82 history = prior_test.history83 else:84 history = {}85 test_method_name = 'test_request'86 test_method = getattr(case.HTTPTestCase, test_method_name)87 @unittest.skipIf(self.host == '', 'No host configured')88 @functools.wraps(test_method)89 def do_test(*args, **kwargs):90 return test_method(*args, **kwargs)91 # Use metaclasses to build a class of the necessary type92 # and name with relevant arguments.93 klass = TestBuilder(test_name, (case.HTTPTestCase,),94 {'test_data': test,95 'test_directory': self.test_directory,96 'fixtures': self.fixture_classes,97 'inner_fixtures': self.inner_fixtures,98 'http': http_class,99 'host': self.host,100 'intercept': self.intercept,101 'content_handlers': self.content_handlers,102 'response_handlers': self.response_handlers,103 'port': self.port,104 'prefix': self.prefix,105 'prior': prior_test,106 'history': history,107 'test_base_name': self.test_base_name,108 test_method_name: do_test,109 })110 # We've been asked to, make this test class think it comes111 # from a different module.112 if self.test_loader_name:113 klass.__module__ = self.test_loader_name114 tests = self.loader.loadTestsFromTestCase(klass)115 history[test['name']] = tests._tests[0]116 # Return the first (and only) test in the klass.117 return tests._tests[0]118 def _set_test_name(self, test):119 """Set the name of the test120 The original name is lowercased and spaces are replaces with '_'.121 The result is appended to the test_base_name, which is based on the122 name of the input data file.123 """124 if not test['name']:125 raise GabbiFormatError('Test name missing in a test in %s.'126 % self.test_base_name)127 return '%s_%s' % (self.test_base_name,128 test['name'].lower().replace(' ', '_'))129 @staticmethod130 def _set_test_method_and_url(test, test_name):131 """Extract the base URL and method for this test.132 If there is an upper case key in the test, that is used as the133 method and the value is used as the URL. If there is more than134 one uppercase that is a GabbiFormatError.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] = val...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

...16m = 617t = 1618set_rs_code(m, t)19def test():20 ts.make_one_test(n, k, b)21def ntest():22 N = int(input("Enter number test N = "))23 for i in range(N):24 try:25 print("\nTest %d:" % (i+1))26 ts.make_one_test(n, k, b)27 except:28 pass29test()30ntest()31'''32### For test code33# t0 = (d-1)/234def getFER_t0():35 arr = []36 for m in range(4, 10):37 fer = ts.getFER(m, 2**(m-2), 0)38 arr.append(fer)39 return arr40# t1 = (d-1)/2+1...

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