How to use test_orientation method in uiautomator

Best Python code snippet using uiautomator

test_integration.py

Source:test_integration.py Github

copy

Full Screen

1import os2from time import sleep3import django4from app_helper.base_test import BaseTestCaseMixin5from cms import __version__ as cms_version6from cms.api import add_plugin7from cms.api import create_page8from django.contrib.staticfiles.testing import StaticLiveServerTestCase9from django.core.servers.basehttp import WSGIServer10from django.test import override_settings11from django.test.testcases import LiveServerThread12from django.test.testcases import QuietWSGIRequestHandler13from selenium.common.exceptions import ElementClickInterceptedException14from selenium.common.exceptions import ElementNotInteractableException15from selenium.common.exceptions import JavascriptException16from selenium.common.exceptions import NoSuchElementException17from selenium.common.exceptions import StaleElementReferenceException18from selenium.common.exceptions import TimeoutException19from selenium.webdriver.common.desired_capabilities import DesiredCapabilities20from selenium.webdriver.support import ui21from .utils.helper_functions import ScreenCreator22from .utils.helper_functions import get_browser_instance23from .utils.helper_functions import get_own_ip24from .utils.helper_functions import get_page_placeholders25from .utils.helper_functions import normalize_screenshot26from .utils.helper_functions import retry_on_browser_exception27INTERACTIVE = False28CMS_VERSION_TUPLE = tuple(map(int, cms_version.split(".")))29PATCHED_CMS_VERSION_TUPLE = (3, 8)30if CMS_VERSION_TUPLE < PATCHED_CMS_VERSION_TUPLE:31 USE_JS_INJECTION = True32else:33 USE_JS_INJECTION = False34class LiveServerSingleThread(LiveServerThread):35 """36 From: https://stackoverflow.com/a/51750516/399061537 Runs a single threaded server rather than multi threaded.38 Reverts https://github.com/django/django/pull/783239 """40 def _create_server(self):41 """42 the keep-alive fixes introduced in Django 2.1.4 (934acf1126995f6e6ccba5947ec8f7561633c27f)43 cause problems when serving the static files in a stream.44 We disable the helper handle method that calls handle_one_request multiple times.45 """46 QuietWSGIRequestHandler.handle = QuietWSGIRequestHandler.handle_one_request47 return WSGIServer(48 (self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False49 )50DJANGO_VERSION_TUPLE = tuple(int(i) for i in django.__version__.split("."))51if DJANGO_VERSION_TUPLE >= (2, 1, 4):52 class StaticServerSingleThreadedTestCase(StaticLiveServerTestCase):53 "A thin sub-class which only sets the single-threaded server as a class"54 server_thread_class = LiveServerSingleThread55else:56 StaticServerSingleThreadedTestCase = StaticLiveServerTestCase57# uncomment the next line if the server throws errors58# @override_settings(DEBUG=True)59@override_settings(ALLOWED_HOSTS=["*"])60class TestIntegrationChrome(BaseTestCaseMixin, StaticServerSingleThreadedTestCase):61 """62 Baseclass for Integration tests with Selenium running in a docker.63 The settings default to chrome (see. docker-compose.yml),64 but can be overwritten in subclasses to match different browsers.65 Original setup from:66 https://stackoverflow.com/a/45324730/399061567 and68 https://docs.djangoproject.com/en/2.2/topics/testing/tools/#liveservertestcase69 """70 host = get_own_ip()71 browser_port = 444472 desire_capabilities = DesiredCapabilities.CHROME73 desire_capabilities["unexpectedAlertBehaviour"] = "accept"74 browser_name = "Chrome"75 _pages_data = (76 {77 "en": {78 "title": "testpage",79 "template": "page.html",80 "publish": True,81 "menu_title": "test_page",82 "in_navigation": True,83 }84 },85 )86 languages = ["en"]87 @classmethod88 def setUpClass(cls):89 super().setUpClass()90 cls.browser = get_browser_instance(91 cls.browser_port,92 cls.desire_capabilities,93 interactive=INTERACTIVE,94 browser_name=cls.browser_name,95 )96 cls.browser.set_window_size(1100, 1200)97 cls.screenshot = ScreenCreator(cls.browser, cls.browser_name)98 cls.wait = ui.WebDriverWait(cls.browser, 20)99 cls.browser.delete_all_cookies()100 @classmethod101 def tearDownClass(cls):102 cls.browser.quit()103 super().tearDownClass()104 def setUp(self):105 # This is needed so the user will be recreated each time,106 # since TransactionTestCase (base class of StaticLiveServerTestCase)107 # drops its db per test108 self.user = self.create_user(109 self._admin_user_username,110 self._admin_user_email,111 self._admin_user_password,112 is_staff=True,113 is_superuser=True,114 )115 testpage = create_page(116 "testpage",117 "page.html",118 "en",119 menu_title="test_page",120 in_navigation=True,121 published=True,122 )123 if CMS_VERSION_TUPLE >= (3, 5):124 testpage.set_as_homepage()125 self.placeholder = get_page_placeholders(testpage, "en").get(slot="content")126 self.logout_user()127 self.screenshot.reset_counter()128 super().setUp()129 @classmethod130 def wait_get_element_css(cls, css_selector):131 cls.wait.until(lambda driver: driver.find_element_by_css_selector(css_selector))132 return cls.browser.find_element_by_css_selector(css_selector)133 @classmethod134 def wait_get_elements_css(cls, css_selector):135 cls.wait.until(lambda driver: driver.find_elements_by_css_selector(css_selector))136 return cls.browser.find_elements_by_css_selector(css_selector)137 @classmethod138 def wait_get_element_link_text(cls, link_text):139 cls.wait.until(lambda driver: driver.find_element_by_link_text(link_text))140 return cls.browser.find_element_by_link_text(link_text)141 def element_is_displayed_css(self, css_selector):142 if self.element_exists(css_selector):143 try:144 return self.browser.find_element_by_css_selector(css_selector).is_displayed()145 except (146 ElementNotInteractableException,147 StaleElementReferenceException,148 NoSuchElementException,149 ):150 return False151 else:152 return False153 @retry_on_browser_exception(154 max_retry=1,155 exceptions=(156 StaleElementReferenceException,157 NoSuchElementException,158 TimeoutException,159 ),160 raise_exception=False,161 )162 def wait_for_element_to_disappear(self, css_selector):163 try:164 self.browser.find_element_by_css_selector(css_selector)165 except (StaleElementReferenceException, NoSuchElementException):166 pass167 else:168 if self.browser.find_element_by_css_selector(css_selector).is_displayed():169 self.wait.until_not(170 lambda driver: driver.find_element_by_css_selector(css_selector).is_displayed()171 )172 @retry_on_browser_exception(173 max_retry=1, exceptions=(StaleElementReferenceException, NoSuchElementException)174 )175 def wait_for_element_to_be_visible(self, css_selector):176 try:177 self.browser.find_element_by_css_selector(css_selector)178 except StaleElementReferenceException:179 pass180 else:181 if not self.browser.find_element_by_css_selector(css_selector).is_displayed():182 self.wait.until(183 lambda driver: driver.find_element_by_css_selector(css_selector).is_displayed()184 )185 def set_text_input_value(self, input, value):186 if input.get_attribute("value") == "":187 input.send_keys(value)188 def sleep(self, time=60, allways_sleep=False):189 if (INTERACTIVE and "GITHUB_WORKSPACE" not in os.environ) or allways_sleep:190 sleep(time)191 def element_exists(self, css_selector):192 try:193 self.browser.find_element_by_css_selector(css_selector)194 return True195 except NoSuchElementException:196 return False197 def login_user(self, take_screen_shot=False):198 if not self.element_exists(".cms-btn-switch-save"):199 self.browser.get(self.live_server_url + "/?edit")200 try:201 username = self.wait_get_element_css("#id_username")202 username.send_keys(self._admin_user_username) # admin203 password = self.wait_get_element_css("#id_password")204 password.send_keys(self._admin_user_password) # admin205 self.screenshot.take(206 "added_credentials.png",207 "test_login_user",208 take_screen_shot=take_screen_shot,209 )210 login_form = self.wait_get_element_css("form.cms-form-login")211 login_form.submit()212 self.screenshot.take(213 "form_submitted.png",214 "test_login_user",215 take_screen_shot=take_screen_shot,216 )217 except TimeoutException as e:218 print("Didn't find `form.cms-form-login`.")219 self.screenshot.take("login_fail.png", "login_fail")220 raise TimeoutException(e.msg)221 # make sure that the css for proper screenshots is applied222 normalize_screenshot(browser=self.browser)223 def logout_user(self):224 # visiting the logout link is a fallback since FireFox225 # sometimes doesn't logout properly by just deleting the cookies226 self.browser.get(self.live_server_url + "/admin/logout/")227 # self.browser.delete_all_cookies()228 @retry_on_browser_exception(229 exceptions=(ElementNotInteractableException, StaleElementReferenceException)230 )231 def open_structure_board(232 self,233 self_test=False,234 test_name="test_create_standalone_equation",235 execution_count=0,236 ):237 if execution_count >= 2:238 self.browser.refresh()239 if CMS_VERSION_TUPLE < (3, 5):240 if not self.element_is_displayed_css(".cms-toolbar"):241 # cms_toolbar_btn only exists in django-cms 3.4242 self.click_element_css(".cms-toolbar-trigger a")243 if self.element_is_displayed_css("a.cms-btn-switch-edit"):244 self.click_element_css("a.cms-btn-switch-edit")245 if not self.element_is_displayed_css(".cms-structure"):246 # sidebar_toggle_btn247 self.click_element_css(".cms-toolbar-item-cms-mode-switcher a")248 # This is needed so structure_board won't be stale249 if not self.element_is_displayed_css(".cms-structure"):250 if self.element_is_displayed_css("a.cms-btn-switch-edit"):251 self.click_element_css("a.cms-btn-switch-edit")252 self.open_structure_board(253 self_test=self_test,254 test_name=test_name,255 execution_count=execution_count + 1,256 )257 def change_form_orientation(self, test_name="test_equation_orientation", current_frames=None):258 orientation_changer = self.wait_get_element_css(".orientation_selector")259 orientation_changer.click()260 self.screenshot.take(261 "horizontal_orientation.png",262 test_name,263 take_screen_shot=True,264 current_frames=current_frames,265 )266 orientation_changer.click()267 self.screenshot.take(268 "vertical_orientation.png",269 test_name,270 take_screen_shot=True,271 current_frames=current_frames,272 )273 orientation_changer.click()274 self.screenshot.take(275 "default_orientation_auto_again.png",276 test_name,277 take_screen_shot=True,278 current_frames=current_frames,279 )280 @retry_on_browser_exception(exceptions=(TimeoutException, ElementNotInteractableException))281 def enter_equation(282 self,283 self_test=False,284 tex_code=r"\int^{a}_{b} f(x) \mathrm{d}x",285 font_size_value=1,286 font_size_unit="rem",287 is_inline=False,288 test_name="test_create_standalone_equation",289 not_js_injection_hack=True,290 test_orientation=False,291 current_frames=None,292 ):293 # this is to prevent random errors, when294 # chrome does not manage to click #id_tex_code295 if current_frames is not None:296 self.browser.switch_to.default_content()297 for current_frame in current_frames:298 self.browser.switch_to.frame(current_frame)299 # the click is needed for firefox to select the frame again300 latex_input = self.click_element_css("#id_tex_code")301 if font_size_value != 1 or font_size_unit != "rem" or is_inline is True:302 try:303 self.browser.find_element_by_css_selector(".collapse.advanced.collapsed")304 except NoSuchElementException:305 pass306 else:307 # advanced_setting_toggle308 self.click_element_css(".collapse-toggle")309 if font_size_value != 1:310 font_size_value_input = self.wait_get_element_css(311 "#djangocms_equation_font_size_value"312 )313 font_size_value_input.clear()314 font_size_value_input.send_keys(str(font_size_value))315 if font_size_unit != "rem":316 # font_size_unit_input317 self.click_element_css("#djangocms_equation_font_size_unit")318 # unit_option319 self.click_element_css(320 "#djangocms_equation_font_size_unit option[value={}]".format(font_size_unit)321 )322 if is_inline is True:323 # is_inline_input324 self.click_element_css("#id_is_inline")325 # the click is needed for firefox to select the element326 latex_input = self.click_element_css("#id_tex_code")327 # the input of the equation is done here so the browsers328 # have more time to render the settings, since this appears329 # to be a problem on travis330 self.set_text_input_value(latex_input, tex_code)331 self.screenshot.take(332 "equation_entered.png",333 test_name,334 take_screen_shot=not_js_injection_hack,335 current_frames=current_frames,336 )337 if test_orientation:338 self.change_form_orientation(test_name=test_name, current_frames=current_frames)339 @retry_on_browser_exception(exceptions=(StaleElementReferenceException, TimeoutException))340 def open_stand_alone_add_modal(341 self,342 self_test=False,343 test_name="test_create_standalone_equation",344 plugin_to_add="equation",345 ):346 # add_plugin_btn347 self.click_element_css(".cms-submenu-btn.cms-submenu-add.cms-btn")348 # #### Firefox Hack, since it fails sometimes to open the modal349 self.wait_for_element_to_be_visible(".cms-modal")350 # prevent scroll errors351 # quick_search352 self.click_element_css(".cms-quicksearch input")353 if plugin_to_add == "equation":354 plugin_option = self.wait_get_element_css('.cms-submenu-item a[href="EquationPlugin"]')355 elif plugin_to_add == "text":356 plugin_option = self.wait_get_element_css('.cms-submenu-item a[href="TextPlugin"]')357 self.screenshot.take("plugin_add_modal.png", test_name, take_screen_shot=self_test)358 plugin_option.click()359 @retry_on_browser_exception(max_retry=1)360 def hide_structure_mode_cms_34(self):361 if CMS_VERSION_TUPLE < (3, 5):362 # content_link363 self.click_element_css('.cms-toolbar-item-cms-mode-switcher a[href="?edit"]')364 @retry_on_browser_exception(365 max_retry=2,366 exceptions=(367 StaleElementReferenceException,368 TimeoutException,369 NoSuchElementException,370 ElementNotInteractableException,371 ElementClickInterceptedException,372 ),373 )374 def click_element_css(self, css_selector):375 element = self.wait_get_element_css(css_selector)376 element.click()377 return element378 @retry_on_browser_exception(379 max_retry=1, exceptions=(ElementNotInteractableException, TimeoutException)380 )381 def publish_and_take_screen_shot(self, not_js_injection_hack, test_name):382 if not_js_injection_hack:383 if self.element_exists(".cms-btn-publish-active"):384 self.click_element_css(".cms-btn-publish-active")385 # making sure the page got updated386 self.wait_get_element_css("a.cms-btn-switch-edit")387 if not self.element_exists(".cms-btn-publish-active"):388 self.logout_user()389 self.wait_get_element_css(".djangocms-admin-style")390 self.browser.get(self.live_server_url)391 self.wait_get_element_css("span.katex-html")392 self.screenshot.take(393 "equation_rendered_no_edit_mode.png",394 test_name,395 take_screen_shot=True,396 )397 else:398 self.browser.refresh()399 raise ElementNotInteractableException("Couldn't publish page")400 def create_standalone_equation(401 self,402 self_test=False,403 tex_code=r"\int^{a}_{b} f(x) \mathrm{d}x",404 font_size_value=1,405 font_size_unit="rem",406 is_inline=False,407 test_name="test_create_standalone_equation",408 not_js_injection_hack=True,409 test_orientation=False,410 ):411 self.login_user()412 self.open_structure_board(self_test=self_test, test_name=test_name)413 self.screenshot.take("sidebar_open.png", test_name, take_screen_shot=self_test)414 self.open_stand_alone_add_modal(415 self_test=self_test, test_name=test_name, plugin_to_add="equation"416 )417 equation_edit_iframe = self.wait_get_element_css("iframe")418 self.screenshot.take("equation_edit_iframe.png", test_name, take_screen_shot=self_test)419 self.browser.switch_to.frame(equation_edit_iframe)420 self.enter_equation(421 self_test=self_test,422 tex_code=tex_code,423 font_size_value=font_size_value,424 font_size_unit=font_size_unit,425 is_inline=is_inline,426 test_name=test_name,427 not_js_injection_hack=not_js_injection_hack,428 test_orientation=test_orientation,429 current_frames=(equation_edit_iframe,),430 )431 self.browser.switch_to.default_content()432 # save_btn433 self.click_element_css(".cms-btn.cms-btn-action.default")434 if self.element_is_displayed_css(".cms-modal"):435 self.wait_for_element_to_disappear(".cms-modal")436 self.hide_structure_mode_cms_34()437 # self.wait_get_element_css("span.katex")438 if not test_orientation:439 self.screenshot.take(440 "equation_rendered.png",441 test_name,442 take_screen_shot=not_js_injection_hack,443 )444 self.publish_and_take_screen_shot(not_js_injection_hack, test_name)445 def create_text_equation(446 self,447 self_test=False,448 tex_code=r"\int^{a}_{b} f(x) \mathrm{d}x",449 font_size_value=1,450 font_size_unit="rem",451 is_inline=False,452 test_name="test_create_text_equation",453 test_orientation=False,454 ):455 def switch_to_text_edit_frame():456 self.browser.switch_to.default_content()457 text_edit_iframe = self.wait_get_element_css("iframe")458 self.browser.switch_to.frame(text_edit_iframe)459 return text_edit_iframe460 def switch_to_cke_wysiwyg_frame():461 switch_to_text_edit_frame()462 cke_wysiwyg_frame = self.wait_get_element_css("iframe.cke_wysiwyg_frame")463 self.browser.switch_to.frame(cke_wysiwyg_frame)464 return cke_wysiwyg_frame465 @retry_on_browser_exception(exceptions=(TimeoutException), test_name=test_name)466 def add_equation_text_plugin():467 text_edit_frame = switch_to_text_edit_frame()468 plugin_select = self.wait_get_element_css(".cke_button__cmsplugins")469 self.screenshot.take(470 "text_edit_iframe.png",471 test_name,472 take_screen_shot=self_test,473 current_frames=(text_edit_frame,),474 )475 plugin_select.click()476 text_edit_pannel_iframe = self.wait_get_element_css("iframe.cke_panel_frame")477 self.browser.switch_to.frame(text_edit_pannel_iframe)478 # equation_options479 self.click_element_css('.cke_panel_listItem a[rel="EquationPlugin"]')480 text_edit_frame = switch_to_text_edit_frame()481 equation_edit_iframe = self.wait_get_element_css("iframe.cke_dialog_ui_html")482 self.browser.switch_to.frame(equation_edit_iframe)483 return (text_edit_frame, equation_edit_iframe)484 @retry_on_browser_exception(485 exceptions=(TimeoutException, JavascriptException), test_name=test_name486 )487 def add_text(text=" Some text for testing:", counter=0):488 switch_to_cke_wysiwyg_frame()489 self.wait_get_element_css("body p")490 script_code = 'document.querySelector("body p").innerText=" {} "'.format(text)491 self.browser.execute_script(script_code)492 @retry_on_browser_exception(exceptions=(TimeoutException), test_name=test_name)493 def save_equation_text_plugin():494 switch_to_text_edit_frame()495 # OK_btn496 self.click_element_css(".cke_dialog_ui_button_ok")497 # making sure that equation properly propagated, to the text editor498 switch_to_cke_wysiwyg_frame()499 self.wait_get_element_css("span.katex")500 text_edit_frame = switch_to_text_edit_frame()501 if not test_orientation:502 self.screenshot.take(503 "equation_in_text_editor.png",504 test_name,505 take_screen_shot=True,506 current_frames=(text_edit_frame,),507 )508 self.browser.switch_to.default_content()509 # save_btn510 self.click_element_css(".cms-btn.cms-btn-action.default")511 self.login_user()512 self.open_structure_board(self_test=self_test, test_name=test_name)513 self.open_stand_alone_add_modal(514 self_test=self_test, test_name=test_name, plugin_to_add="text"515 )516 add_text()517 current_frames = add_equation_text_plugin()518 self.enter_equation(519 self_test=self_test,520 tex_code=tex_code,521 font_size_value=font_size_value,522 font_size_unit=font_size_unit,523 is_inline=is_inline,524 test_name=test_name,525 not_js_injection_hack=True,526 test_orientation=test_orientation,527 current_frames=current_frames,528 )529 save_equation_text_plugin()530 self.browser.switch_to.default_content()531 self.wait_for_element_to_disappear(".cms-modal")532 self.hide_structure_mode_cms_34()533 try:534 self.wait_for_element_to_be_visible("span.katex-html")535 except (TimeoutException, NoSuchElementException):536 pass537 if not test_orientation:538 self.screenshot.take("equation_rendered.png", test_name, take_screen_shot=True)539 self.publish_and_take_screen_shot(True, test_name)540 def delete_plugin(self, delete_all=True):541 self.open_structure_board()542 delete_links = self.wait_get_elements_css("a[data-rel=delete]")543 if not delete_all:544 delete_links = [delete_links[0]]545 for _ in delete_links:546 # since the delete links aren't visible the click is triggered547 # with javascript548 self.browser.execute_script('document.querySelector("a[data-rel=delete]").click()')549 # delete_confirm550 self.click_element_css(".deletelink")551 def js_injection_hack(self):552 if USE_JS_INJECTION:553 with self.login_user_context(self.user):554 add_plugin(555 self.placeholder,556 "EquationPlugin",557 language="en",558 tex_code="js~injection~hack~for~cms<{}.{}".format(*PATCHED_CMS_VERSION_TUPLE),559 is_inline=False,560 font_size_value=1,561 font_size_unit="rem",562 )563 self.browser.refresh()564 # ACTUAL TESTS565 def test_page_exists(self):566 self.browser.get(self.live_server_url)567 body = self.browser.find_element_by_css_selector("body")568 self.screenshot.take("created_page.png", "test_page_exists")569 self.assertIn("test_page", body.text)570 def test_login_user(self):571 self.login_user(take_screen_shot=True)572 self.browser.get(self.live_server_url + "/?edit")573 self.screenshot.take("start_page_user_logged_in.png", "test_login_user")574 cms_navigation = self.wait_get_element_css(".cms-toolbar-item-navigation span")575 self.assertEqual(576 cms_navigation.text,577 "example.com",578 cms_navigation.get_attribute("innerHTML"),579 )580 def test_logout_user(self):581 self.login_user()582 self.logout_user()583 self.browser.get(self.live_server_url)584 self.screenshot.take("start_page_user_logged_out.png", "test_logout_user")585 self.assertRaises(586 NoSuchElementException,587 self.browser.find_element_by_css_selector,588 "#cms-top",589 )590 def test_create_standalone_equation(self):591 self.js_injection_hack()592 self.create_standalone_equation(self_test=True)593 def test_create_standalone_equation_2rem(self):594 self.js_injection_hack()595 self.create_standalone_equation(596 font_size_value=2, test_name="test_create_standalone_equation_2rem"597 )598 def test_create_standalone_equation_1_cm(self):599 self.js_injection_hack()600 self.create_standalone_equation(601 font_size_unit="cm", test_name="test_create_standalone_equation_1_cm"602 )603 def test_create_standalone_equation_inline_True(self):604 self.js_injection_hack()605 self.create_standalone_equation(606 is_inline=True, test_name="test_create_standalone_equation_inline_True"607 )608 def test_create_standalone_mhchem_equation(self):609 self.js_injection_hack()610 self.create_standalone_equation(611 tex_code=r"\ce{A <=>>[\Delta] B3^2-_{(aq)}}",612 test_name="test_create_standalone_mhchem_equation",613 )614 def test_orientation_swap_standalone_equation(self):615 self.js_injection_hack()616 self.create_standalone_equation(617 test_orientation=True, test_name="test_orientation_swap_standalone_equation"618 )619 def test_create_text_equation(self):620 self.js_injection_hack()621 self.create_text_equation(self_test=True)622 def test_create_text_equation_2rem(self):623 self.js_injection_hack()624 self.create_text_equation(font_size_value=2, test_name="test_create_text_equation_2rem")625 def test_create_text_equation_1_cm(self):626 self.js_injection_hack()627 self.create_text_equation(font_size_unit="cm", test_name="test_create_text_equation_1_cm")628 def test_create_text_equation_inline_True(self):629 self.js_injection_hack()630 self.create_text_equation(631 is_inline=True, test_name="test_create_text_equation_inline_True"632 )633 def test_create_text_mhchem_equation(self):634 self.js_injection_hack()635 self.create_standalone_equation(636 tex_code=r"\ce{A <=>>[\Delta] B3^2-_{(aq)}}",637 test_name="test_create_text_mhchem_equation",638 )639 def test_orientation_swap_text_equation(self):640 self.js_injection_hack()641 self.create_text_equation(642 test_orientation=True, test_name="test_orientation_swap_text_equation"643 )644class TestIntegrationFirefox(TestIntegrationChrome):645 browser_port = 4445646 desire_capabilities = DesiredCapabilities.FIREFOX...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

1import numpy as np2import pandas as pd3import Pipeline as pline4import cleantext as cl56''' train '''7#load train8train_=np.load('../Data/train/train.npy')9info_train=pd.read_csv('../Data/train/Train.csv')1011# preprocess, face detection and standardise train set12prep_train= pline.face_recognition(train_)1314# predict pic orientation (+ create confusion matrix)15train_prediction, confusion_matrix_train = pline.classify_pose(prep_train, info_train, C=0.9,gamma=0.005)1617# results of pose prediction 18train_orientation = pd.DataFrame({'Number':info_train.Number,'Angle': train_prediction})19train_orientation['Angle'] = train_orientation['Angle'].map({0:'Half Left', 1:'Half Right', 2: 'Left', 3:'Right', 4:'Straight'})20train_orientation.to_csv('../Results/Train/train_results.csv', index=False)2122# group pics by pose and save Y true23train_pose, y_pose = pline.pose_category(prep_train, info_train)2425# compute LDA + SVM of train set26train_svm_straight, train_pred_straight,train_lda_straight = pline.classify_emotion(dataset=train_pose["Straight"],y=y_pose["Straight"], n_comp=4,C=0.05, gamma=0.15)27train_svm_hl, train_pred_hl,train_lda_hl = pline.classify_emotion(dataset=train_pose["Half Left"], y=y_pose["Half Left"], n_comp=4,C=0.9, gamma=0.01)28train_svm_hr, train_pred_hr,train_lda_hr = pline.classify_emotion(dataset=train_pose["Half Right"], y=y_pose["Half Right"], n_comp=4,C=1.13, gamma=0.145)29train_svm_left, train_pred_left,train_lda_left = pline.classify_emotion(dataset=train_pose["Left"], y=y_pose["Left"], n_comp=4,C=0.2, gamma=0.35)30train_svm_right, train_pred_right,train_lda_right = pline.classify_emotion(dataset=train_pose["Right"],y= y_pose["Right"], n_comp=4,C=0.22, gamma=0.027)3132# results of emotion detection33final_result={"Straight":train_pred_straight,"Half Left":train_pred_hl,"Half Right":train_pred_hr,"Left":train_pred_left,"Right":train_pred_right}34cl.csv_result(y_pose,final_result,train_orientation,'../Results/Train/train_results.csv')353637''' test '''38#load test39test=np.load('../Data/test/test.npy')40info_test=pd.read_csv('../Data/test/Test.csv')4142# preprocess, face detection and standardise test set43prep_test= pline.face_recognition(test)4445# predict pic orientation (+ create confusion matrix)46test_prediction, confusion_matrix_test = pline.classify_pose(prep_test, info_test, C=0.6, gamma=0.4)4748# results of pose prediction 49test_orientation = pd.DataFrame({'Number':info_test.Number,'Angle': test_prediction})50test_orientation['Angle'] = test_orientation['Angle'].map({0:'Half Left', 1:'Half Right', 2: 'Left', 3:'Right', 4:'Straight'})51test_orientation.to_csv('../Results/Test/test_results.csv', index=False)52test_orientation['Encoding_expression'] = info_test.Encoding_expression5354# group pics by pose and save Y true55test_pose, y_pose_test = pline.pose_category(prep_test, test_orientation)5657# compute PCA + SVM of test set58test_pred_straight = pline.classify_emotion(test_pose["Straight"], y_pose_test["Straight"], svm_=train_svm_straight,lda_=train_lda_straight)59test_pred_hl = pline.classify_emotion(test_pose["Half Left"], y_pose_test["Half Left"], svm_=train_svm_hl,lda_=train_lda_hl)60test_pred_hr = pline.classify_emotion(test_pose["Half Right"], y_pose_test["Half Right"], svm_=train_svm_hr,lda_=train_lda_hr)61test_pred_left = pline.classify_emotion(test_pose["Left"], y_pose_test["Left"], svm_=train_svm_left,lda_=train_lda_left)62test_pred_right = pline.classify_emotion(test_pose["Right"], y_pose_test["Right"],svm_=train_svm_right,lda_=train_lda_right)6364# results of emotion detection65final_result={"Straight":test_pred_straight,"Half Left":test_pred_hl,"Half Right":test_pred_hr,"Left":test_pred_left,"Right":test_pred_right} ...

Full Screen

Full Screen

2CollisionDetection.py

Source:2CollisionDetection.py Github

copy

Full Screen

1import RobotUtil2def origin_orientation_dims(xyz, rpy, dxdydz):3 return RobotUtil.BlockDesc2Points(RobotUtil.rpyxyz2H((rpy[0], rpy[1], rpy[2]), (xyz[0], xyz[1], xyz[2])),4 (dxdydz[0], dxdydz[1], dxdydz[2]))5ref_cuboid_corners, ref_cuboid_axes = origin_orientation_dims((0, 0, 0), (0, 0, 0), (3, 1, 2))6# print(ref_cuboid_corners)7test_origin = [(0, 1, 0), (1.5, -1.5, 0), (0, 0, -1), (3, 0, 0), (-1, 0, -2), (1.8, 0.5, 1.5), (0, -1.2, 0.4),8 (-0.8, 0, -0.5)]9test_orientation = [(0, 0, 0), (1, 0, 1.5), (0, 0, 0), (0, 0, 0), (0.5, 0, 0.4), (-0.2, 0.5, 0), (0, 0.785, 0.785),10 (0, 0, 0.2)]11test_dims = [(0.8, 0.8, 0.8), (1, 3, 3), (2, 3, 1), (3, 1, 1), (2, 0.7, 2), (1, 3, 1), (1, 1, 1), (1, 0.5, 0.5)]12assert len(test_origin) == len(test_orientation) and len(test_orientation) == len(test_dims)13for i in range(len(test_origin)):14 corners_to_test, axes_to_test = origin_orientation_dims(test_origin[i], test_orientation[i], test_dims[i])15 print(RobotUtil.CheckBoxBoxCollision(ref_cuboid_corners, ref_cuboid_axes, corners_to_test, axes_to_test))16'''17False18True19True20True21True22False23True24True...

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