How to use test_contains_value method in assertpy

Best Python code snippet using assertpy_python Github


Full Screen

1from __future__ import print_function, unicode_literals2import inspect3from django.core.exceptions import ImproperlyConfigured4from django.core.urlresolvers import Resolver404, resolve5from django.template.response import SimpleTemplateResponse6from six.moves.urllib_parse import urlsplit, urlunsplit7class BaseValidator(object):8 """9 Base validator which should be sub-classed to create10 custom validators.11 :var tuple BaseValidator.expected_attrs: Required attributes for the12 validator. :py:meth:`_check_improper_configuration`13 will verify that all of these attributes are defined.14 .. note:: Each validator should only define required15 attributes for itself. :py:meth:`_get_expected_attrs`16 will automatically return required attributes17 from all current validator and base classes.18 :param test_step: :py:class:`subui.step.TestStep`19 instance which will be used to make assertions on.20 .. note:: This parameter is not really required in the21 ``__init__`` because the same step will be passed22 in :py:meth:`test` however is useful in ``__init__``23 in case subclass validator needs to apply custom24 login according to values from the ``step``.25 """26 expected_attrs = None27 def __init__(self, test_step=None, **kwargs):28 self.step = test_step29 self.__dict__.update(**kwargs)30 def _get_expected_attrs(self):31 """32 Get all required/expected attributes as defined by33 :py:attr:`expected_attrs` from all current and base34 classes.35 For example::36 class Validator1(BaseValidator):37 expected_attr = ('foo', 'bar')38 class Validator2(Validator1):39 expected_attr = ('hello', 'world')40 > validator = Validator2()41 > validator._get_expected_attrs()42 ['foo', 'bar', 'hello', 'world']43 :rtype: list44 """45 bases = inspect.getmro(self.__class__)46 attrs = set()47 for base in bases:48 attrs |= set(getattr(base, 'expected_attrs', None) or set())49 return list(sorted(attrs))50 def _check_improper_configuration(self):51 """52 Check that the validator is configured correctly53 by verifying that all attributes as returned by54 :py:meth:`_get_expected_attrs` are defined.55 :raises ImproperlyConfigured: If any of the required56 attributes are not defined.57 """58 for attr in self._get_expected_attrs():59 if not getattr(self, attr, None):60 msg = '{} requires to define {}'61 raise ImproperlyConfigured(62 msg.format(self.__class__.__name__, attr)63 )64 def _get_base_error_message(self):65 """66 Get base error message which will be used in assertions67 """68 msg = 'Response for {{{key}:{step}}} requesting "{url}"'69 msg = msg.format(70 key=self.step.step_key,71 step=self.step.__class__.__name__,72 url=self.step.get_url(),73 )74 return msg75 def test(self, test_step):76 """77 Test the step's server response by making78 all the necessary assertions. This method79 by default saves the ``test_step`` parameter80 into :py:attr:`step` and validates the validator81 by using :py:meth:`_check_improper_configuration`.82 All subclass validators should actually implement83 assertions in this method.84 :param test_step: Test step85 """86 self.step = test_step87 self._check_improper_configuration()88class HeaderValidator(BaseValidator):89 """90 Validator which can check that a particular header91 is returned and that it is of particular value.92 :var str HeaderValidator.header_name: Name of the header which93 must be returned94 :var str expected_header: Expected header value95 to be returned96 :var bool HeaderValidator.test_header_value: Whether to test the97 header value or simply check its existence98 :var test_contains_value: Whether to test if the99 header value contains another value, or simply100 check equality to that value101 """102 expected_attrs = ('header_name', 'expected_header',)103 header_name = None104 expected_header = None105 test_header_value = True106 test_contains_value = False107 def _get_expected_attrs(self):108 """109 Get all expected attributes except remove "expected_header"110 if :py:attr:`test_header_value` is ``False``.111 """112 attrs = super(HeaderValidator, self)._get_expected_attrs()113 if not self.test_header_value:114 attrs.remove('expected_header')115 return attrs116 def test(self, test_step):117 """118 Test the response returned with119 :py:attr:header_name header and that its value120 is equal to :py:attr:expected_header if121 :py:attr:test_header_value is True.122 If :py:attr:test_contains_value is True,123 header value will be tested to contain expected value.124 """125 super(HeaderValidator, self).test(test_step)126 if self.test_contains_value:127 self.test_header_value = False128 self.step.test.assertIn(129 self.header_name,130 self.step.response,131 '{} must contain {} header'132 ''.format(self._get_base_error_message(),133 self.header_name)134 )135 if self.test_header_value:136 self.test_contains_value = False137 self.step.test.assertEqual(138 self.step.response[self.header_name],139 self.expected_header,140 '{} returned header {} with value {} != {}'141 ''.format(self._get_base_error_message(),142 self.header_name,143 self.step.response[self.header_name],144 self.expected_header)145 )146 if self.test_contains_value:147 self.step.test.assertIn(148 self.expected_header,149 self.step.response[self.header_name],150 '{} returned header {} with value {} which doesnt contain {}'151 ''.format(self._get_base_error_message(),152 self.header_name,153 self.step.response[self.header_name],154 self.expected_header)155 )156class HeaderContentTypeValidator(HeaderValidator):157 """158 Validator to check that the expected159 "Content-Type" header is returned.160 """161 header_name = 'Content-Type'162class HeaderLocationValidator(HeaderValidator):163 """164 Validator to check that the redirect165 "Location" header is returned166 """167 header_name = 'Location'168class StatusCodeValidator(BaseValidator):169 """170 Validator which allows to verify the returned171 server status code such as "OK-200" or "Redirect-302", etc.172 :var int StatusCodeValidator.expected_status_code: Expected status code to be173 returned by the server174 """175 expected_attrs = ('expected_status_code',)176 expected_status_code = None177 def test(self, test_step):178 """179 Test that the response status code180 matched expected status code.181 """182 super(StatusCodeValidator, self).test(test_step)183 self.step.test.assertEqual(184 self.step.response.status_code,185 self.expected_status_code,186 '{} returned with status code {} != {}'187 ''.format(self._get_base_error_message(),188 self.step.response.status_code,189 self.expected_status_code)190 )191class StatusCodeCreatedValidator(StatusCodeValidator):192 """193 Validator to check that the returned status194 code is created - 201195 """196 expected_status_code = 201197class StatusCodeOkValidator(StatusCodeValidator):198 """199 Validator to check that the returned status200 code is OK - 200201 """202 expected_status_code = 200203class StatusCodeRedirectValidator(HeaderLocationValidator, StatusCodeValidator):204 """205 Validator to check that the server returns a redirect206 with the "Location" header defined.207 """208 expected_status_code = 302209 test_header_value = False210class RedirectToRouteValidator(StatusCodeRedirectValidator):211 """212 Validator which also checks that the server returns213 a redirect to an expected Django route.214 :var str expected_route_name: Route name to which215 the server should redirect to216 """217 expected_attrs = ('expected_route_name',)218 expected_route_name = None219 def test(self, test_step):220 """221 Test the response by additionally testing222 that the response redirects to an expected223 route as defined by :py:attr:`expected_route_name`.224 """225 super(RedirectToRouteValidator, self).test(test_step)226 location = self.step.response['Location']227 # remove schema, query string and host from URL. Since query string need to be removed to properly resolve that url228 location = urlunsplit(('', '', urlsplit(location).path, '', ''))229 try:230 redirected_to_route = resolve(location).view_name231 except Resolver404:232 msg = '{} returned a redirect to "{}" which cannot be resolved'233,234 location))235 self.step.test.assertEqual(236 redirected_to_route,237 self.expected_route_name,238 '{} returned redirect to route {} != {}'239 ''.format(self._get_base_error_message(),240 redirected_to_route,241 self.expected_route_name)242 )243class ResponseContentContainsValidator(StatusCodeOkValidator):244 """245 Validator which also checks that returned response246 content contains expect string.247 :var str expected_content: Expected string in the248 server response249 """250 expected_attrs = ('expected_content',)251 expected_content = None252 def test(self, test_step):253 """254 Test the response by additionally testing255 that the response context contains expected256 string as defined by :py:attr:`expected_content`.257 """258 super(ResponseContentContainsValidator, self).test(test_step)259 self.step.test.assertIn(260 self.expected_content,261 # need to decode since content is binary262 self.step.response.content.decode('utf-8'),263 '{} does not contain {!r} in its content'264 ''.format(self._get_base_error_message(),265 self.expected_content)266 )267class ResponseContentNotContainsValidator(StatusCodeOkValidator):268 """269 Validator checks that returned response270 content does not contain unexpected string.271 :var str unexpected_content: Unexpected string in the272 server response273 """274 expected_attrs = ('unexpected_content',)275 unexpected_content = None276 def test(self, test_step):277 """278 Test the response by additionally testing279 that the response context does not contain the unexpected280 string as defined by :py:attr:`unexpected_content`.281 """282 super(ResponseContentNotContainsValidator, self).test(test_step)283 self.step.test.assertNotIn(284 self.unexpected_content,285 # need to decode since content is binary286 self.step.response.content.decode('utf-8'),287 'UnexpectedContentFound: {} contains {!r} in its content. '288 ''.format(self._get_base_error_message(),289 self.unexpected_content)290 )291class SessionDataValidator(BaseValidator):292 """293 Validator which allows to verify the data in the session based on294 session key.295 :var str expected_session_key: Expected session key to be present in session296 :var list expected_session_secondary_keys: List of Expected session key to be present in session297 """298 expected_attrs = ('expected_session_key',)299 expected_session_key = None300 expected_session_secondary_keys = []301 def test(self, test_step):302 """303 Test that expected session key is present. If expected session data provided,304 ensure the expected session key data matches what is there currently.305 """306 super(SessionDataValidator, self).test(test_step)307 self.step.test.assertIn(308 self.expected_session_key,309 self.step.response.wsgi_request.session.keys(),310 '{} does not contain session[{!r}].'311 ''.format(self._get_base_error_message(),312 self.expected_session_key)313 )314 if self.expected_session_secondary_keys:315 self.step.test.assertIsInstance(316 self.step.response.wsgi_request.session[self.expected_session_key],317 dict,318 '{} session[{!r}] is not a dictionary hence cannot contain secondary keys.'319 ''.format(self._get_base_error_message(), self.expected_session_key)320 )321 # Make sure secondary keys are not empty.322 for secondary_key in self.expected_session_secondary_keys:323 self.step.test.assertIn(324 secondary_key,325 self.step.response.wsgi_request.session[self.expected_session_key].keys(),326 '{} does not contain session[{!r}][{!r}].'327 ''.format(self._get_base_error_message(), self.expected_session_key, secondary_key)328 )329 self.step.test.assertIsNotNone(330 self.step.response.wsgi_request.session[self.expected_session_key][secondary_key],331 '{} contains session[{!r}][{!r}] but is empty.'332 ''.format(self._get_base_error_message(), self.expected_session_key, secondary_key)333 )334class FormInitialDataValidator(BaseValidator):335 """336 Validator checks that form in response has expected data in initial data.337 :var str initial_data_key: Expected initial data key to be present in form initial data338 :var expected_initial_data_value: Expected value initial value should be set to339 :var str context_data_form_name: Template context data key for form data340 :var bool test_initial_value: Test if the initial value matched expected value341 :var bool test_initial_value_present: Test if the initial value key is present in initial data342 :var bool test_initial_value_not_none: Test if the initial value is not ``None``343 """344 expected_attrs = ('initial_data_key',)345 initial_data_key = None346 expected_initial_data_value = None347 context_data_form_name = 'form'348 test_initial_value = False349 test_initial_value_present = True350 test_initial_value_not_none = True351 def test(self, test_step):352 super(FormInitialDataValidator, self).test(test_step)353 self.step.test.assertIsInstance(354 self.step.response,355 SimpleTemplateResponse,356 '{} did not return SimpleTemplateResponse '357 'and as such response.context_data is not accessible. '358 'It returned {!r}'359 ''.format(self._get_base_error_message(),360 type(self.step.response))361 )362 self.step.test.assertIn(363 self.context_data_form_name,364 self.step.response.context_data,365 '{} did not render with {!r} in its context_data'366 ''.format(self._get_base_error_message(),367 self.context_data_form_name)368 )369 self.step.test.assertIsInstance(370 self.step.response.context_data[self.context_data_form_name].initial,371 dict,372 '{} did not render with the context_data[{!r}].initial being a dictionary'373 ''.format(self._get_base_error_message(),374 self.context_data_form_name)375 )376 if self.test_initial_value_present:377 self.step.test.assertIn(378 self.initial_data_key,379 self.step.response.context_data[self.context_data_form_name].initial.keys(),380 '{} did not render with {!r} in the context_data[{!r}].initial. '381 'Provided keys - {!r}'382 ''.format(self._get_base_error_message(),383 self.initial_data_key,384 self.context_data_form_name,385 self.step.response.context_data[self.context_data_form_name].initial.keys())386 )387 if self.test_initial_value_not_none:388 self.step.test.assertIsNotNone(389 self.step.response.context_data['form'].initial[self.initial_data_key],390 '{} rendered with {!r} for context_data[{!r}].initial[{!r}]'391 ''.format(self._get_base_error_message(),392 None,393 self.context_data_form_name,394 self.initial_data_key)395 )396 if self.test_initial_value:397 self.step.test.assertEqual(398 self.step.response.context_data['form'].initial[self.initial_data_key],399 self.expected_initial_data_value,400 '{} rendered with context_data[{!r}].initial[{!r}] = {} != {}'401 ''.format(self._get_base_error_message(),402 self.context_data_form_name,403 self.initial_data_key,404 self.step.response.context_data['form'].initial[self.initial_data_key],405 self.expected_initial_data_value)...

Full Screen

Full Screen Github


Full Screen

...22 )))23 def test_wrong_length_tuple(self):24 with self.assertRaises(ValueError):25 Choices(('a',))26 def test_contains_value(self):27 self.assertTrue('PUBLISHED' in self.STATUS)28 self.assertTrue('DRAFT' in self.STATUS)29 def test_doesnt_contain_value(self):30 self.assertFalse('UNPUBLISHED' in self.STATUS)31 def test_deepcopy(self):32 import copy33 self.assertEqual(list(self.STATUS),34 list(copy.deepcopy(self.STATUS)))35 def test_equality(self):36 self.assertEqual(self.STATUS, Choices('DRAFT', 'PUBLISHED'))37 def test_inequality(self):38 self.assertNotEqual(self.STATUS, ['DRAFT', 'PUBLISHED'])39 self.assertNotEqual(self.STATUS, Choices('DRAFT'))40 def test_composability(self):41 self.assertEqual(Choices('DRAFT') + Choices('PUBLISHED'), self.STATUS)42 self.assertEqual(Choices('DRAFT') + ('PUBLISHED',), self.STATUS)43 self.assertEqual(('DRAFT',) + Choices('PUBLISHED'), self.STATUS)44 def test_option_groups(self):45 c = Choices(('group a', ['one', 'two']), ['group b', ('three',)])46 self.assertEqual(47 list(c),48 [49 ('group a', [('one', 'one'), ('two', 'two')]),50 ('group b', [('three', 'three')]),51 ],52 )53class LabelChoicesTests(ChoicesTests):54 def setUp(self):55 self.STATUS = Choices(56 ('DRAFT', 'is draft'),57 ('PUBLISHED', 'is published'),58 'DELETED',59 )60 def test_iteration(self):61 self.assertEqual(tuple(self.STATUS), (62 ('DRAFT', 'is draft'),63 ('PUBLISHED', 'is published'),64 ('DELETED', 'DELETED'),65 ))66 def test_reversed(self):67 self.assertEqual(tuple(reversed(self.STATUS)), (68 ('DELETED', 'DELETED'),69 ('PUBLISHED', 'is published'),70 ('DRAFT', 'is draft'),71 ))72 def test_indexing(self):73 self.assertEqual(self.STATUS['PUBLISHED'], 'is published')74 def test_default(self):75 self.assertEqual(self.STATUS.DELETED, 'DELETED')76 def test_provided(self):77 self.assertEqual(self.STATUS.DRAFT, 'DRAFT')78 def test_len(self):79 self.assertEqual(len(self.STATUS), 3)80 def test_equality(self):81 self.assertEqual(self.STATUS, Choices(82 ('DRAFT', 'is draft'),83 ('PUBLISHED', 'is published'),84 'DELETED',85 ))86 def test_inequality(self):87 self.assertNotEqual(self.STATUS, [88 ('DRAFT', 'is draft'),89 ('PUBLISHED', 'is published'),90 'DELETED'91 ])92 self.assertNotEqual(self.STATUS, Choices('DRAFT'))93 def test_repr(self):94 self.assertEqual(repr(self.STATUS), "Choices" + repr((95 ('DRAFT', 'DRAFT', 'is draft'),96 ('PUBLISHED', 'PUBLISHED', 'is published'),97 ('DELETED', 'DELETED', 'DELETED'),98 )))99 def test_contains_value(self):100 self.assertTrue('PUBLISHED' in self.STATUS)101 self.assertTrue('DRAFT' in self.STATUS)102 # This should be True, because both the display value103 # and the internal representation are both DELETED.104 self.assertTrue('DELETED' in self.STATUS)105 def test_doesnt_contain_value(self):106 self.assertFalse('UNPUBLISHED' in self.STATUS)107 def test_doesnt_contain_display_value(self):108 self.assertFalse('is draft' in self.STATUS)109 def test_composability(self):110 self.assertEqual(111 Choices(('DRAFT', 'is draft',)) + Choices(('PUBLISHED', 'is published'), 'DELETED'),112 self.STATUS113 )114 self.assertEqual(115 (('DRAFT', 'is draft',),) + Choices(('PUBLISHED', 'is published'), 'DELETED'),116 self.STATUS117 )118 self.assertEqual(119 Choices(('DRAFT', 'is draft',)) + (('PUBLISHED', 'is published'), 'DELETED'),120 self.STATUS121 )122 def test_option_groups(self):123 c = Choices(124 ('group a', [(1, 'one'), (2, 'two')]),125 ['group b', ((3, 'three'),)]126 )127 self.assertEqual(128 list(c),129 [130 ('group a', [(1, 'one'), (2, 'two')]),131 ('group b', [(3, 'three')]),132 ],133 )134class IdentifierChoicesTests(ChoicesTests):135 def setUp(self):136 self.STATUS = Choices(137 (0, 'DRAFT', 'is draft'),138 (1, 'PUBLISHED', 'is published'),139 (2, 'DELETED', 'is deleted'))140 def test_iteration(self):141 self.assertEqual(tuple(self.STATUS), (142 (0, 'is draft'),143 (1, 'is published'),144 (2, 'is deleted'),145 ))146 def test_reversed(self):147 self.assertEqual(tuple(reversed(self.STATUS)), (148 (2, 'is deleted'),149 (1, 'is published'),150 (0, 'is draft'),151 ))152 def test_indexing(self):153 self.assertEqual(self.STATUS[1], 'is published')154 def test_getattr(self):155 self.assertEqual(self.STATUS.DRAFT, 0)156 def test_len(self):157 self.assertEqual(len(self.STATUS), 3)158 def test_repr(self):159 self.assertEqual(repr(self.STATUS), "Choices" + repr((160 (0, 'DRAFT', 'is draft'),161 (1, 'PUBLISHED', 'is published'),162 (2, 'DELETED', 'is deleted'),163 )))164 def test_contains_value(self):165 self.assertTrue(0 in self.STATUS)166 self.assertTrue(1 in self.STATUS)167 self.assertTrue(2 in self.STATUS)168 def test_doesnt_contain_value(self):169 self.assertFalse(3 in self.STATUS)170 def test_doesnt_contain_display_value(self):171 self.assertFalse('is draft' in self.STATUS)172 def test_doesnt_contain_python_attr(self):173 self.assertFalse('PUBLISHED' in self.STATUS)174 def test_equality(self):175 self.assertEqual(self.STATUS, Choices(176 (0, 'DRAFT', 'is draft'),177 (1, 'PUBLISHED', 'is published'),178 (2, 'DELETED', 'is deleted')...

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:


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

Run assertpy 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?