How to use jq_format method in SeleniumBase

Best Python code snippet using SeleniumBase

http.py

Source:http.py Github

copy

Full Screen

1import ast2import json3from behave import *4from django.template import Template, Context5from jq import jq6from .utils import extract_field_value, pretty_print_table7@step('hago las peticiones desde la url "([^"]+)"')8def set_url(context, url):9 try:10 context.http_headers['HTTP_REFERER'] = url11 except AttributeError:12 context.http_headers = {'HTTP_REFERER': url}13@step('hago un "([^"]+)" a la url "([^"]+)"(?: con los argumentos "([^"]+)")?(?: (?:y|con) los parametros "([^"]+)")?(?: (?:y|con) body)?')14def step_impl(context, method_name, url, url_args, url_params):15 """16 Hago un "get" a la url "factura"17 Hago un "get" a la url "factura" con los argumentos "id=1"18 Hago un "get" a la url "factura" con los parametros "ordering=nombre,nombre=mario"19 Hago un "get" a la url "factura" con body:20 Hago un "get" a la url "factura" con los argumentos "id=1" y body:21 | name |22 | mario |23 | luigi |24 Hago un "get" a la url "factura" con los argumentos "id=1" y body:25 | key | value |26 | mario | rossi |27 | luigi | verdi |28 Hago un "get" a la url "factura" con los argumentos "id=1" y body:29 '''30 { raw json }31 '''32 # Use triple double-quotes33 """34 headers = {'content_type': 'application/json'}35 try:36 headers = dict(headers, **context.http_headers)37 except AttributeError:38 pass39 data = None40 if context.text:41 data = context.text42 elif context.table:43 fields = context.table.headings44 # This is used to send a single dict as the payload45 if len(fields) == 2 and 'key' in fields and 'value' in fields:46 data = {item['key']: item['value'] for item in context.table.headings}47 else:48 data = list(context.table.headings)49 if not url.startswith('/'):50 # Hack!!51 # Could not find an easier way to parse the named url WITH parameters52 url = Template(f"{{% url '{url}' {url_args or ''} %}}").render(Context())53 if url_params:54 url = f'{url}?{"&".join([param.strip().replace(";", ",") for param in url_params.split(", ")])}'55 method = getattr(context.test.client, method_name.lower())56 context.response = method(url, data=data, **headers)57@step('configuro los headers( usando literales|)')58def add_request_headers(context, use_literals):59 # The way django settings is made, it allows for settings and headers to be passed in as one60 context.http_headers = {}61 cast = ast.literal_eval if bool(use_literals) else lambda x: x62 for item in context.table.rows:63 context.http_headers[item['name']] = cast(item['value'])64@step('el codigo de retorno es "([0-9]{3})"')65def step_impl(context, status_code):66 assert context.response.status_code == int(status_code), (context.response.status_code, context.response.content)67@step('hay "([0-9]+)" elementos en la response')68def step_impl(context, count):69 assert len(context.response.json()['results']) == int(count)70@step('(?:utilizando el formato jq "(.*)")? la response es')71def check_request_response(context, jq_format):72 """73 More details about the jq can be found at their docs: https://stedolan.github.io/jq/manual/#Basicfilters74 List within list75 [76 {"nk": "coursenk1", "prereqs_met": ["coursenkX", "coursenkY"], "prereqs_missed": ["courseidW", "courseidZ"]},77 {"nk": "coursenk2", "prereqs_met": ["coursenkA", "coursenkB"], "prereqs_missed": ["courseidC", "courseidD"]},78 ]79 # And using jq format check the expected values for prereqs_met80 And using jq format "[.[].prereqs_met[] | {value: .}]" the response is:81 | value |82 | coursenkX |83 | coursenkY |84 | coursenkA |85 | coursenkB |86 # And using jq format check the expected values for prereqs_missed87 And using jq format "[.[].prereqs_missed[] | {value: .}]" the response is:88 | value |89 | courseidW |90 | courseidZ |91 | courseidC |92 | courseidD |93 List within list within dict94 {95 "courses":96 [97 {"nk": "coursenk1", "prereqs_met": ["coursenkX", "coursenkY"],98 "prereqs_missed": ["courseidW", "courseidZ"]},99 {"nk": "coursenk2", "prereqs_met": ["coursenkA", "coursenkB"],100 "prereqs_missed": ["courseidC", "courseidD"]},101 ],102 "units": 16103 }104 # And using jq format check the expected values for prereqs_met105 And using jq format "[.courses[].prereqs_met[] | {value: .}]" the response is:106 | value |107 | coursenkX |108 | coursenkY |109 | coursenkA |110 | coursenkB |111 # And using jq format check the expected values for prereqs_missed112 And using jq format "[.courses[].prereqs_missed[] | {value: .}]" the response is:113 | value |114 | courseidW |115 | courseidZ |116 | courseidC |117 | courseidD |118 Dict within dict119 {120 "courses":121 {122 "MATH101": {"nk": "MATH101", "title": "Algebra"},123 "MATH202": {"nk": "MATH202", "title": "Linear Algebra"},124 },125 "hobbies":126 {127 "Swimming": {"nk": "Swimming", "area": "Outdoors"},128 "Ping Pong": {"nk": "Ping Pong", "area": "Indoors"},129 },130 }131 # And using jq format check the expected values for hobby nk & course nk132 And using jq format "[.[][].nk | {value: .}]" the response is:133 | value |134 | MATH101 |135 | MATH202 |136 | Swimming |137 | Ping Pong |138 # And using jq format check the expected values for course nk139 And using jq format "[.courses[].nk | {value: .}]" the response is:140 | value |141 | Swimming |142 | Ping Pong |143 """144 is_json = context.response.get('Content-Type') == 'application/json'145 if is_json:146 actual = context.response.json()147 if jq_format:148 # Before trying to debug the lines below, why not test it at this website: https://jqplay.org/149 # It's simpler than adding breakpoints and print statements everywhere...150 # Also, the docs are here: https://stedolan.github.io/jq/manual/#Basicfilters151 try:152 actual = jq(jq_format).transform(actual)153 except StopIteration:154 # jq returns this if nothing was returned155 actual = None156 else:157 actual = context.response.content.decode()158 if context.table:159 fields = context.table.headings160 if isinstance(actual, dict):161 actual = [actual]162 cleaned_data = [{field: str(extract_field_value(item, field)) for field in fields} for item in actual]163 expected_data = [{field: item[field] for field in fields} for item in context.table.rows]164 context.test.assertEquals(cleaned_data, expected_data, pretty_print_table(fields, cleaned_data))165 elif context.text is not None:166 if is_json:167 expected = json.loads(context.text)168 else:169 # Remove all leading whitespace and new line chars from multiline before comparing.170 # Remove whitespace between dict key & value.171 lines = context.text.split('\n')172 lines_without_leading_whitespace = [line.lstrip() for line in lines]173 one_str_of_all_lines = ''.join(lines_without_leading_whitespace)174 without_space_after_colon = one_str_of_all_lines.replace(': ', ':')175 expected = without_space_after_colon176 actual = actual.replace(': ', ':')177 context.test.assertEquals.__self__.maxDiff = None178 context.test.assertEquals(actual, expected)179 else:180 raise Exception('Nothing to compare')181@step('la respuesta contiene los siguientes headers')182def check_headers(context):183 for row in context.table.rows:184 assert row['key'] in context.response.headers, (f'key {row["key"]} not found', context.response.headers.keys())...

Full Screen

Full Screen

page_utils.py

Source:page_utils.py Github

copy

Full Screen

1"""2This module contains useful utility methods.3"""4import requests5def jq_format(code):6 """7 Use before throwing raw code such as 'div[tab="advanced"]' into jQuery.8 Selectors with quotes inside of quotes would otherwise break jQuery.9 This is similar to "json.dumps(value)", but with one less layer of quotes.10 """11 code = code.replace('\\', '\\\\').replace('\t', '\\t').replace('\n', '\\n')12 code = code.replace('\"', '\\\"').replace('\'', '\\\'')13 code = code.replace('\v', '\\v').replace('\a', '\\a').replace('\f', '\\f')14 code = code.replace('\b', '\\b').replace('\u', '\\u').replace('\r', '\\r')15 return code16def get_domain_url(url):17 """18 Use this to convert a url like this:19 https://blog.xkcd.com/2014/07/22/what-if-book-tour/...

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