import json from playwright.sync_api import Browser from src import config from allure import step from src.helpers.logger import Logger log = Logger() class App: def __init__(self, browser: Browser, api, base_url: str, **kwargs): self.browser = browser self.context = self.browser.new_context(**kwargs) self.page = self.context.new_page() self.base_url = base_url self.api = api @step("Go to {endpoint} page") def go_to(self, endpoint: str): log.info(f'Proceeding to {self.base_url + endpoint}') self.page.goto(self.base_url + endpoint) self.page.wait_for_load_state('load') self.page.wait_for_load_state('domcontentloaded') try: self.page.wait_for_load_state('networkidle') except: pass @step("Abort request {request_url}") def abort_request(self, request_url): self.page.route(request_url, lambda route: route.abort()) @step("Fulfill response {response_url} with body={data}") def fulfill_response(self, response_url, data): self.page.route(response_url, lambda route: route.fulfill( status=200, content_type="application/json; charset=utf-8", body=data)) def save_context_state(self): log.info('Saving Context from browser') refresh_token = None for cookie in self.context.cookies(): if cookie['name'] == 'dna_refresh_token_uat': refresh_token = cookie['value'] # self.context.storage_state(path="state.json") # whole context saves values which affect Search tests with open('state.json', 'r') as state_json: state = json.load(state_json) for cookie in state['cookies']: if cookie['name'] == 'dna_refresh_token_uat' and refresh_token is not None: cookie['value'] = refresh_token with open('state.json', 'w') as state_json: json.dump(state, state_json, indent=4) def close(self): if 'uat' in config.ENV_BASE_URL: self.save_context_state() self.page.close() self.context.close() def start_tracing(self): self.context.tracing.start(screenshots=True, snapshots=True, sources=True) def stop_tracing(self): self.context.tracing.stop(path="trace.zip") def check_http_response(self): # https://playwright.dev/python/docs/network#network-events pass # NOTE: BUG for Chromium https://github.com/microsoft/playwright/issues/6479 def read_network_requests(self): self.page.on("request", lambda request: print(">>", request.method, request.url, request.post_data))