How to use is_context_modifier method in pyresttest

Best Python code snippet using pyresttest_python

test_tests.py

Source:test_tests.py Github

copy

Full Screen

...110 {"expected_status": ["200", 204, "202"]}]111 test = Test.parse_test('', myinput)112 self.assertEqual(test.name, "cheese")113 self.assertEqual(test.expected_status, [200, 204, 202])114 self.assertFalse(test.is_context_modifier())115 def test_parse_nonstandard_http_method(self):116 myinput = {"url": "/ping", "method": "PATCH", "NAME": "foo", "group": "bar",117 "body": "<xml>input</xml>", "headers": {"Accept": "Application/json"}}118 test = Test.parse_test('', myinput)119 self.assertEqual("PATCH", test.method)120 try:121 myinput['method'] = 1122 test.parse_test('', myinput)123 fail("Should fail to pass a nonstring HTTP method")124 except TypeError:125 pass126 try:127 myinput['method'] = ''128 test.parse_test('', myinput)129 fail("Should fail to pass a nonstring HTTP method")130 except (TypeError, AssertionError):131 pass132 def test_parse_custom_curl(self):133 # Basic case134 myinput = {'url': '/ping', 'name': 'basic',135 'curl_option_followLocatION': True}136 test = Test.parse_test('', myinput)137 options = test.curl_options138 self.assertEqual(1, len(options))139 self.assertEqual(True, options['FOLLOWLOCATION'])140 # Test parsing with two options141 myinput['curl_option_maxredirs'] = 99142 test = Test.parse_test('', myinput)143 options = test.curl_options144 self.assertEqual(2, len(options))145 self.assertEqual(True, options['FOLLOWLOCATION'])146 self.assertEqual(99, options['MAXREDIRS'])147 # Invalid curl option148 myinput['curl_option_BOGUSOPTION'] = 'i_fail'149 try:150 test.parse_test('', myinput)151 fail("Should throw an exception when invalid curl option used, but didn't!")152 except ValueError:153 pass154 # We can't use version specific skipIf decorator b/c python 2.6 unittest lacks it155 def test_use_custom_curl(self):156 """ Test that test method really does configure correctly """157 if PYTHON_MAJOR_VERSION > 2:158 # In python 3, use of mocks for the curl setopt version (or via setattr)159 # Will not modify the actual curl object... so test fails160 print("Skipping test of CURL configuration for redirects because the mocks fail")161 raise unittest.SkipTest("Skipping test of CURL configuration for redirects because the mocks fail")162 test = Test()163 test.curl_options = {'FOLLOWLOCATION': True, 'MAXREDIRS': 5}164 mock_handle = pycurl.Curl()165 mock_handle.setopt = mock.MagicMock(return_value=True)166 test.configure_curl(curl_handle=mock_handle)167 # print mock_handle.setopt.call_args_list # Debugging168 mock_handle.setopt.assert_any_call(mock_handle.FOLLOWLOCATION, True)169 mock_handle.setopt.assert_any_call(mock_handle.MAXREDIRS, 5)170 mock_handle.close()171 def test_basic_auth(self):172 """ Test that basic auth configures correctly """173 if PYTHON_MAJOR_VERSION > 2:174 # In python 3, use of mocks for the curl setopt version (or via setattr)175 # Will not modify the actual curl object... so test fails176 print("Skipping test of CURL configuration for basic auth because the mocks fail in Py3")177 return178 test = Test()179 test.auth_username = u'bobbyg'180 test.auth_password = 'password'181 mock_handle = pycurl.Curl()182 mock_handle.setopt = mock.MagicMock(return_value=True)183 test.configure_curl(curl_handle=mock_handle)184 # print mock_handle.setopt.call_args_list # Debugging185 mock_handle.setopt.assert_any_call(mock_handle.USERPWD, b'bobbyg:password')186 mock_handle.close()187 def test_parse_test_templated_headers(self):188 """ Test parsing with templated headers """189 heads = {"Accept": "Application/json", "$AuthHeader": "$AuthString"}190 templated_heads = {"Accept": "Application/json",191 "apikey": "magic_passWord"}192 context = Context()193 context.bind_variables(194 {'AuthHeader': 'apikey', 'AuthString': 'magic_passWord'})195 # If this doesn't throw errors we have silent failures196 input_invalid = {"url": "/ping", "method": "DELETE", "NAME": "foo",197 "group": "bar", "body": "<xml>input</xml>", "headers": 'goat'}198 try:199 test = Test.parse_test('', input_invalid)200 test.fail("Expected error not thrown")201 except TypeError:202 pass203 def assert_dict_eq(dict1, dict2):204 """ Test dicts are equal """205 self.assertEqual(2, len(set(dict1.items()) & set(dict2.items())))206 # Before templating is used207 input = {"url": "/ping", "method": "DELETE", "NAME": "foo",208 "group": "bar", "body": "<xml>input</xml>", "headers": heads}209 test = Test.parse_test('', input)210 assert_dict_eq(heads, test.headers)211 assert_dict_eq(heads, test.get_headers(context=context))212 # After templating applied213 input_templated = {"url": "/ping", "method": "DELETE", "NAME": "foo",214 "group": "bar", "body": "<xml>input</xml>", "headers": {'tEmplate': heads}}215 test2 = Test.parse_test('', input_templated)216 assert_dict_eq(heads, test2.get_headers())217 assert_dict_eq(templated_heads, test2.get_headers(context=context))218 def test_parse_test_validators(self):219 """ Test that for a test it can parse the validators section correctly """220 input = {"url": '/test', 'validators': [221 {'comparator': {222 'jsonpath_mini': 'key.val',223 'comparator': 'eq',224 'expected': 3225 }},226 {'extract_test': {'jsonpath_mini': 'key.val', 'test': 'exists'}}227 ]}228 test = Test.parse_test('', input)229 self.assertTrue(test.validators)230 self.assertEqual(2, len(test.validators))231 self.assertTrue(isinstance(232 test.validators[0], validators.ComparatorValidator))233 self.assertTrue(isinstance(234 test.validators[1], validators.ExtractTestValidator))235 # Check the validators really work236 self.assertTrue(test.validators[0].validate(237 '{"id": 3, "key": {"val": 3}}'))238 def test_parse_validators_fail(self):239 """ Test an invalid validator syntax throws exception """240 input = {"url": '/test', 'validators': ['comparator']}241 try:242 test = Test.parse_test('', input)243 self.fail(244 "Should throw exception if not giving a dictionary-type comparator")245 except TypeError:246 pass247 def test_parse_extractor_bind(self):248 """ Test parsing of extractors """249 test_config = {250 "url": '/api',251 'extract_binds': {252 'id': {'jsonpath_mini': 'idfield'},253 'name': {'jsonpath_mini': 'firstname'}254 }255 }256 test = Test.parse_test('', test_config)257 self.assertTrue(test.extract_binds)258 self.assertEqual(2, len(test.extract_binds))259 self.assertTrue('id' in test.extract_binds)260 self.assertTrue('name' in test.extract_binds)261 # Test extractors config'd correctly for extraction262 myjson = '{"idfield": 3, "firstname": "bob"}'263 extracted = test.extract_binds['id'].extract(myjson)264 self.assertEqual(3, extracted)265 extracted = test.extract_binds['name'].extract(myjson)266 self.assertEqual('bob', extracted)267 def test_parse_extractor_errors(self):268 """ Test that expected errors are thrown on parsing """269 test_config = {270 "url": '/api',271 'extract_binds': {'id': {}}272 }273 try:274 test = Test.parse_test('', test_config)275 self.fail("Should throw an error when doing empty mapping")276 except TypeError:277 pass278 test_config['extract_binds']['id'] = {279 'jsonpath_mini': 'query',280 'test': 'anotherquery'281 }282 try:283 test = Test.parse_test('', test_config)284 self.fail("Should throw an error when given multiple extractors")285 except ValueError as te:286 pass287 def test_parse_validator_comparator(self):288 """ Test parsing a comparator validator """289 test_config = {290 'name': 'Default',291 'url': '/api',292 'validators': [293 {'comparator': {'jsonpath_mini': 'id',294 'comparator': 'eq',295 'expected': {'template': '$id'}}}296 ]297 }298 test = Test.parse_test('', test_config)299 self.assertTrue(test.validators)300 self.assertEqual(1, len(test.validators))301 context = Context()302 context.bind_variable('id', 3)303 myjson = '{"id": "3"}'304 failure = test.validators[0].validate(myjson, context=context)305 self.assertTrue(test.validators[0].validate(myjson, context=context))306 self.assertFalse(test.validators[0].validate(myjson))307 def test_parse_validator_extract_test(self):308 """ Tests parsing extract-test validator """309 test_config = {310 'name': 'Default',311 'url': '/api',312 'validators': [313 {'extract_test': {'jsonpath_mini': 'login',314 'test': 'exists'}}315 ]316 }317 test = Test.parse_test('', test_config)318 self.assertTrue(test.validators)319 self.assertEqual(1, len(test.validators))320 myjson = '{"login": "testval"}'321 self.assertTrue(test.validators[0].validate(myjson))322 def test_variable_binding(self):323 """ Test that tests successfully bind variables """324 element = 3325 input = [{"url": "/ping"}, {"name": "cheese"},326 {"expected_status": ["200", 204, "202"]}]327 input.append({"variable_binds": {'var': 'value'}})328 test = Test.parse_test('', input)329 binds = test.variable_binds330 self.assertEqual(1, len(binds))331 self.assertEqual('value', binds['var'])332 # Test that updates context correctly333 context = Context()334 test.update_context_before(context)335 self.assertEqual('value', context.get_value('var'))336 self.assertTrue(test.is_context_modifier())337 def test_test_url_templating(self):338 test = Test()339 test.set_url('$cheese', isTemplate=True)340 self.assertTrue(test.is_dynamic())341 self.assertEqual('$cheese', test.get_url())342 self.assertTrue(test.templates['url'])343 context = Context()344 context.bind_variable('cheese', 'stilton')345 self.assertEqual('stilton', test.get_url(context=context))346 realized = test.realize(context)347 self.assertEqual('stilton', realized.url)348 def test_test_content_templating(self):349 test = Test()350 handler = ContentHandler()...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

...150 for key, value in self.extract_binds.items():151 result = value.extract(152 body=response_body, headers=headers, context=context)153 context.bind_variable(key, result)154 def is_context_modifier(self):155 """ Returns true if context can be modified by this test156 (disallows caching of templated test bodies) """157 return self.variable_binds or self.generator_binds or self.extract_binds158 def is_dynamic(self):159 """ Returns true if this test does templating """160 if self.templates:161 return True162 elif isinstance(self._body, ContentHandler) and self._body.is_dynamic():163 return True164 return False165 def realize(self, context=None):166 """ Return a fully-templated test object167 Warning: this is a SHALLOW copy, mutation of fields will cause problems!168 Can accept a None context """169 if not self.is_dynamic() or context is None:170 return self171 else:172 selfcopy = self.ninja_copy()173 selfcopy.templates = None174 if isinstance(self._body, ContentHandler):175 selfcopy._body = self._body.get_content(context)176 selfcopy._url = self.get_url(context=context)177 selfcopy._headers = self.get_headers(context=context)178 return selfcopy179 def realize_partial(self, context=None):180 """ Attempt to template out what is static if possible, and load files.181 Used for performance optimization, in cases where a test is re-run repeatedly182 WITH THE SAME Context.183 """184 if self.is_context_modifier():185 # Don't template what is changing186 return self187 elif self.is_dynamic(): # Dynamic but doesn't modify context, template everything188 return self.realize(context=context)189 # See if body can be replaced190 bod = self._body191 newbod = None192 if bod and isinstance(bod, ContentHandler) and bod.is_file and not bod.is_template_path:193 # File can be UN-lazy loaded194 newbod = bod.create_noread_version()195 output = self196 if newbod: # Read body197 output = copy.copy(self)198 output._body = newbod...

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 pyresttest 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