Best Python code snippet using pytractor_python
test_mixins.py
Source:test_mixins.py
1# Copyright 2014 Konrad Podloucky2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14import unittest15from mock import MagicMock, patch, PropertyMock, DEFAULT16from selenium.common.exceptions import NoSuchElementException17from pytractor.exceptions import AngularNotFoundException18from pytractor.mixins import (WebDriverMixin, angular_wait_required,19 CLIENT_SCRIPTS_DIR)20try: # FIXME: find another way21 import __builtin__22 super_str = '__builtin__.super'23except ImportError:24 super_str = 'builtins.super'25class AngularWaitRequiredDecoratorTest(unittest.TestCase):26 @angular_wait_required27 def wrapped_function(self, *args, **kwargs):28 return self.check_function(*args, **kwargs)29 def check_function(self, *args, **kwargs):30 pass31 def test_angular_wait_required(self):32 with patch.multiple(self, wait_for_angular=DEFAULT,33 check_function=DEFAULT, create=True) as patched:34 mock_wait_for_angular = patched['wait_for_angular']35 mock_check_function = patched['check_function']36 mock_arg = MagicMock()37 mock_kwarg = MagicMock()38 result = self.wrapped_function(mock_arg, kwarg=mock_kwarg)39 # result should be the result of the wrapped function40 self.assertIs(result, mock_check_function.return_value)41 # wait_for_angular() should have been called42 mock_wait_for_angular.assert_called_once_with()43 # the check function should have been called44 mock_check_function.assert_called_once_with(mock_arg,45 kwarg=mock_kwarg)46class WebDriverMixinConstructorTest(unittest.TestCase):47 class ConstructorTester(object):48 """Class for checking calls to __init__"""49 def __init__(self, *args, **kwargs):50 self.constructor_called(*args, **kwargs)51 def constructor_called(self, *args, **kwargs):52 """53 This function will be called by __init__. We can hook onto this54 to check for __init__ calls.55 """56 pass57 class TestDriver(WebDriverMixin, ConstructorTester):58 pass59 def test_constructor(self):60 base_url = 'BASEURL'61 root_element = 'ROOTEL'62 test_timeout = 'TESTTIMEOUT'63 script_timeout = 'SCRIPTTIMEOUT'64 with patch.object(65 self.ConstructorTester, 'constructor_called'66 ) as mock_constructor_called, patch.object(67 self.TestDriver, 'set_script_timeout', create=True68 ) as mock_set_script_timeout:69 instance = self.TestDriver(base_url, root_element,70 test_timeout=test_timeout,71 script_timeout=script_timeout)72 # verify that properties have been set73 self.assertIs(instance._base_url, base_url)74 self.assertIs(instance._root_element, root_element)75 self.assertIs(instance._test_timeout, test_timeout)76 # verify that the super class' constructor has been called77 mock_constructor_called.assert_called_once_with()78 # verify that set_script_timeout has been called79 mock_set_script_timeout.assert_called_once_with(script_timeout)80class WebDriverMixinTest(unittest.TestCase):81 def setUp(self):82 set_script_timeout_patcher = patch.object(83 WebDriverMixin, 'set_script_timeout', create=True84 )85 self.mock_set_script_timeout = set_script_timeout_patcher.start()86 self.addCleanup(set_script_timeout_patcher.stop)87 self.mock_root_element = MagicMock()88 self.instance = WebDriverMixin('http://localhost',89 self.mock_root_element)90 @patch('pytractor.mixins.resource_string')91 def verify__execute_client_script_call(self, async, mock_resource_string):92 with patch.multiple(93 self.instance,94 execute_async_script=DEFAULT, execute_script=DEFAULT,95 create=True96 ) as mock_execute:97 (mock_execute_script,98 mock_execute_async_script) = [mock_execute.get(func_name)99 for func_name in100 ('execute_script',101 'execute_async_script')]102 mock_arg = MagicMock()103 result = self.instance._execute_client_script('SCRIPT', mock_arg,104 async=async)105 # the script was read correctly with resource_string()106 mock_resource_string.assert_called_once_with(107 'pytractor.mixins',108 '{}/{}.js'.format(CLIENT_SCRIPTS_DIR, 'SCRIPT')109 )110 # execute_async_script or execute_script were called (but not both)111 script_content = mock_resource_string.return_value.decode()112 if async:113 mock_execute_async_script.assert_called_once_with(script_content,114 mock_arg)115 self.assertEqual(len(mock_execute_script.mock_calls), 0)116 # the result is the one from execute_async_script()117 self.assertIs(result, mock_execute_async_script.return_value)118 else:119 mock_execute_script.assert_called_once_with(script_content,120 mock_arg)121 self.assertEqual(len(mock_execute_async_script.mock_calls), 0)122 # the result is the one from execute_script()123 self.assertIs(result, mock_execute_script.return_value)124 def test__execute_client_script_async(self):125 self.verify__execute_client_script_call(True)126 def test__execute_client_script_sync(self):127 self.verify__execute_client_script_call(False)128 def verify_function_executes_script_with(self, func_to_call,129 script_name, *script_args,130 **script_kwargs):131 with patch.object(132 self.instance, '_execute_client_script'133 ) as mock_execute_client_script:134 result = func_to_call()135 mock_execute_client_script.assert_called_once_with(136 script_name,137 *script_args, **script_kwargs138 )139 self.assertIs(result, mock_execute_client_script.return_value)140 def test_wait_for_angular(self):141 self.verify_function_executes_script_with(142 self.instance.wait_for_angular,143 'waitForAngular', self.mock_root_element, async=True144 )145 def test_wait_for_angular_does_not_call_script_if_ignore_synchronization(146 self147 ):148 """wait_for_angular() must not call the waitForAngular script, if149 ignore_synchronization is set to True."""150 self.instance.ignore_synchronization = True151 with patch.object(152 self.instance, '_execute_client_script'153 ) as mock_execute_client_script:154 self.instance.wait_for_angular()155 self.assertEqual(mock_execute_client_script.call_count, 0)156 def test__test_for_angular(self):157 self.instance._test_timeout = 5000158 self.verify_function_executes_script_with(159 self.instance._test_for_angular,160 'testForAngular', self.instance._test_timeout / 1000161 )162 def test__location_equals(self):163 with patch.object(164 self.instance, 'execute_script', create=True165 ) as mock_execute_script:166 mock_location = MagicMock()167 mock_execute_script.return_value = MagicMock(__eq__=MagicMock())168 result = self.instance._location_equals(mock_location)169 mock_execute_script.assert_called_once_with(170 'return window.location.href'171 )172 script_result = mock_execute_script.return_value173 script_result.__eq__.assert_called_once_with(mock_location)174 self.assertIs(result, script_result.__eq__.return_value)175 # The following tests test some properties that use the wait_for_angular176 # decorator and fetch the property from the super class.177 def verify_super_property_called_with_wait(self, prop_name):178 """179 Verifies that accessing the given property calls the equally180 named property on the super class.181 """182 with patch(183 super_str184 ) as mock_super, patch.object(185 self.instance, 'wait_for_angular'186 ) as mock_wait_for_angular:187 # setup the mocked property188 mock_prop = PropertyMock(name='super.{}'.format(prop_name))189 setattr(type(mock_super.return_value), prop_name, mock_prop)190 result = getattr(self.instance, prop_name)191 mock_wait_for_angular.assert_called_once_with()192 mock_super.assert_called_once_with(WebDriverMixin, self.instance)193 mock_prop.assert_called_once_with()194 self.assertIs(result, mock_prop.return_value)195 def test_current_url(self):196 self.verify_super_property_called_with_wait('current_url')197 def test_page_source(self):198 self.verify_super_property_called_with_wait('page_source')199 def test_title(self):200 self.verify_super_property_called_with_wait('title')201 # Tests for methods that delegate to the super method202 def verify_super_method_called_with_wait(self, method_name):203 """204 Verifies that calling the given method calls the equally205 named method on the super class.206 """207 mock_args = [MagicMock(), MagicMock()]208 with patch(209 super_str210 ) as mock_super, patch.object(211 self.instance, 'wait_for_angular'212 ) as mock_wait_for_angular:213 mock_super_method = getattr(mock_super.return_value, method_name)214 method = getattr(self.instance, method_name)215 result = method(*mock_args)216 mock_wait_for_angular.assert_called_once_with()217 mock_super.assert_called_once_with(WebDriverMixin, self.instance)218 mock_super_method.assert_called_once_with(*mock_args)219 self.assertIs(result, mock_super_method.return_value)220 def test_find_element(self):221 self.verify_super_method_called_with_wait('find_element')222 def test_find_elements(self):223 self.verify_super_method_called_with_wait('find_elements')224 # tests for other methods225 def test_find_elements_by_binding(self):226 mock_descriptor = MagicMock()227 mock_using = MagicMock()228 with patch.multiple(229 self.instance, wait_for_angular=DEFAULT,230 _execute_client_script=DEFAULT231 ) as mock_methods:232 result = self.instance.find_elements_by_binding(mock_descriptor,233 mock_using)234 mock_methods['wait_for_angular'].assert_called_once_with()235 mock_methods['_execute_client_script'].assert_called_once_with(236 'findBindings', mock_descriptor, False, mock_using, async=False237 )238 self.assertIs(result,239 mock_methods['_execute_client_script'].return_value)240 def test_find_element_by_binding_no_element(self):241 mock_descriptor = MagicMock()242 mock_using = MagicMock()243 with patch.object(244 self.instance, 'find_elements_by_binding'245 ) as mock_find_elements_by_binding:246 mock_find_elements_by_binding.return_value = []247 with self.assertRaises(NoSuchElementException):248 self.instance.find_element_by_binding(mock_descriptor,249 mock_using)250 mock_find_elements_by_binding.assert_called_once_with(251 mock_descriptor, using=mock_using252 )253 def test_find_element_by_binding_with_element(self):254 mock_descriptor = MagicMock()255 mock_using = MagicMock()256 mock_element = MagicMock()257 with patch.object(258 self.instance, 'find_elements_by_binding'259 ) as mock_find_elements_by_binding:260 mock_find_elements_by_binding.return_value = [mock_element]261 result = self.instance.find_element_by_binding(mock_descriptor,262 mock_using)263 mock_find_elements_by_binding.assert_called_once_with(264 mock_descriptor, using=mock_using265 )266 self.assertIs(result, mock_element)267 def test_get_with_angular(self):268 mock_url = MagicMock()269 with patch(270 super_str271 ) as mock_super, patch(272 'pytractor.mixins.WebDriverWait'273 ) as mock_webdriverwait_class, patch.multiple(274 self.instance, _test_for_angular=DEFAULT, execute_script=DEFAULT,275 create=True # needed for execute_script276 ) as mock_methods:277 mock_test_for_angular = mock_methods['_test_for_angular']278 # return a truthy value to indicate that angular was found279 mock_test_for_angular.return_value = (True,)280 mock_execute_script = mock_methods['execute_script']281 self.instance.get(mock_url)282 mock_super.assert_called_once_with(WebDriverMixin, self.instance)283 mock_super.return_value.get.assert_called_once_with('about:blank')284 self.assertEqual(len(mock_execute_script.mock_calls), 2)285 mock_webdriverwait_class.assert_called_once_with(self.instance,286 10)287 mock_webdriverwait_instance = mock_webdriverwait_class.return_value288 mock_webdriverwait_instance.until_not.assert_called_once_with(289 self.instance._location_equals, 'about:blank'290 )291 mock_test_for_angular.assert_called_once_with()292 def test_get_without_angular(self):293 mock_url = MagicMock()294 with patch(295 super_str296 ) as mock_super, patch(297 'pytractor.mixins.WebDriverWait'298 ) as mock_webdriverwait_class, patch.multiple(299 self.instance, _test_for_angular=DEFAULT, execute_script=DEFAULT,300 create=True # needed for execute_script301 ) as mock_methods:302 mock_test_for_angular = mock_methods['_test_for_angular']303 # return a falsy value to indicate that angular was not found304 mock_test_for_angular.return_value = (False, 'ERROR')305 mock_execute_script = mock_methods['execute_script']306 with self.assertRaises(AngularNotFoundException):307 self.instance.get(mock_url)308 mock_super.assert_called_once_with(WebDriverMixin, self.instance)309 mock_super.return_value.get.assert_called_once_with('about:blank')310 self.assertEqual(len(mock_execute_script.mock_calls), 1)311 mock_webdriverwait_class.assert_called_once_with(self.instance,312 10)313 mock_webdriverwait_instance = mock_webdriverwait_class.return_value314 mock_webdriverwait_instance.until_not.assert_called_once_with(315 self.instance._location_equals, 'about:blank'316 )317 mock_test_for_angular.assert_called_once_with()318 def test_get_does_not_test_for_angular_if_ignore_synchronization_is_true(319 self320 ):321 """Verify that get() does not call _test_for_angular if322 ignore_synchronization is set to True."""323 mock_url = MagicMock()324 with patch(325 super_str326 ) as mock_super, patch(327 'pytractor.mixins.WebDriverWait'328 ) as mock_webdriverwait_class, patch.multiple(329 self.instance, _test_for_angular=DEFAULT, execute_script=DEFAULT,330 create=True # needed for execute_script331 ) as mock_methods:332 mock_test_for_angular = mock_methods['_test_for_angular']333 self.instance.ignore_synchronization = True334 self.instance.get(mock_url)335 self.assertEqual(mock_test_for_angular.call_count, 0)336 def test_refresh(self):337 with patch.multiple(338 self.instance, get=DEFAULT, execute_script=DEFAULT,339 create=True # needed for execute_script()340 ) as mock_methods:341 self.instance.refresh()342 mock_execute_script, mock_get = (mock_methods['execute_script'],343 mock_methods['get'])344 self.assertEqual(mock_execute_script.call_count, 1)345 mock_get.assert_called_once_with(mock_execute_script.return_value)346 def test_find_element_by_exact_binding_calls_find_elements(self):347 mock_descriptor = MagicMock()348 mock_using = MagicMock()349 mock_element = MagicMock()350 with patch.object(351 self.instance, 'find_elements_by_exact_binding',352 return_value=[mock_element]353 ) as mock_find_elements_by_exact_binding:354 result = self.instance.find_element_by_exact_binding(355 mock_descriptor, mock_using356 )357 mock_find_elements_by_exact_binding.assert_called_once_with(358 mock_descriptor, using=mock_using359 )360 self.assertIs(result, mock_element)361 def test_find_element_by_exact_binding_raises_error_if_nothing_found(self):362 mock_descriptor = MagicMock()363 mock_using = MagicMock()364 with patch.object(365 self.instance, 'find_elements_by_exact_binding', return_value=[]366 ) as mock_find_elements_by_exact_binding:367 with self.assertRaises(NoSuchElementException):368 self.instance.find_element_by_exact_binding(369 mock_descriptor, mock_using370 )371 mock_find_elements_by_exact_binding.assert_called_once_with(372 mock_descriptor, using=mock_using373 )374 def test_find_elements_by_exact_binding_calls_protractor_script(self):375 mock_descriptor = MagicMock()376 mock_using = MagicMock()377 with patch.multiple(378 self.instance, wait_for_angular=DEFAULT,379 _execute_client_script=DEFAULT380 ) as mock_methods:381 result = self.instance.find_elements_by_exact_binding(382 mock_descriptor, mock_using383 )384 mock_methods['wait_for_angular'].assert_called_once_with()385 mock_methods['_execute_client_script'].assert_called_once_with(386 'findBindings', mock_descriptor, True, mock_using, async=False387 )388 self.assertIs(result,389 mock_methods['_execute_client_script'].return_value)390 def test_find_element_by_model_calls_find_elements(self):391 mock_descriptor = MagicMock()392 mock_using = MagicMock()393 with patch.object(394 self.instance, 'find_elements_by_model', return_value=[]395 ) as mock_find_elements_by_model:396 with self.assertRaises(NoSuchElementException):397 self.instance.find_element_by_model(398 mock_descriptor, mock_using399 )400 mock_find_elements_by_model.assert_called_once_with(401 mock_descriptor, using=mock_using402 )403 def test_find_element_by_model_raises_error_if_nothing_found(self):404 mock_descriptor = MagicMock()405 mock_using = MagicMock()406 with patch.object(407 self.instance, 'find_elements_by_model', return_value=[]408 ) as mock_find_elements_by_model:409 with self.assertRaises(NoSuchElementException):410 self.instance.find_element_by_model(411 mock_descriptor, mock_using412 )413 mock_find_elements_by_model.assert_called_once_with(414 mock_descriptor, using=mock_using415 )416 def test_find_elements_by_model_calls_protractor_script(self):417 mock_descriptor = MagicMock()418 mock_using = MagicMock()419 with patch.multiple(420 self.instance, wait_for_angular=DEFAULT,421 _execute_client_script=DEFAULT422 ) as mock_methods:423 result = self.instance.find_elements_by_model(424 mock_descriptor, mock_using425 )426 mock_methods['wait_for_angular'].assert_called_once_with()427 mock_methods['_execute_client_script'].assert_called_once_with(428 'findByModel', mock_descriptor, mock_using, async=False429 )430 self.assertIs(result,431 mock_methods['_execute_client_script'].return_value)432 def test_find_elements_by_model_returns_empty_list_if_script_returns_none(433 self434 ):435 """Verify that find_elements_by_model() returns an empty list if436 the protractor script returns None.437 This is a test for issue #10438 """439 with patch.object(self.instance, '_execute_client_script',440 return_value=None):441 result = self.instance.find_elements_by_model('does-not-exist')442 self.assertIsInstance(result, list)443 self.assertEqual(len(result), 0)444 def test_location_abs_url_calls_protractor_script(self):445 with patch.multiple(446 self.instance, wait_for_angular=DEFAULT,447 _execute_client_script=DEFAULT448 ) as mock_methods:449 result = self.instance.location_abs_url450 mock_methods['wait_for_angular'].assert_called_once_with()451 mock_methods['_execute_client_script'].assert_called_once_with(452 'getLocationAbsUrl', self.instance._root_element, async=False453 )454 self.assertIs(result,455 mock_methods['_execute_client_script'].return_value)456 def test_set_location_calls_protractor_script(self):457 url = 'http://a.new.locat.ion/'458 with patch.multiple(459 self.instance, wait_for_angular=DEFAULT,460 _execute_client_script=DEFAULT461 ) as mock_methods:462 result = self.instance.set_location(url)463 mock_methods['wait_for_angular'].assert_called_once_with()464 mock_methods['_execute_client_script'].assert_called_once_with(465 'setLocation', self.instance._root_element, url, async=False466 )467 self.assertIs(result,...
mixins.py
Source:mixins.py
...108 def title(self):109 return super(WebDriverMixin, self).title110 @property111 @angular_wait_required112 def location_abs_url(self):113 return self._execute_client_script('getLocationAbsUrl',114 self._root_element, async=False)115 @angular_wait_required116 def find_elements_by_repeater(self, descriptor, using=None):117 return self._execute_client_script('findAllRepeaterRows',118 descriptor, False, using,119 async=False)120 @angular_wait_required121 def find_element(self, *args, **kwargs):122 return super(WebDriverMixin, self).find_element(*args, **kwargs)123 @angular_wait_required124 def find_elements(self, *args, **kwargs):125 return super(WebDriverMixin, self).find_elements(*args, **kwargs)126 @angular_wait_required...
test_helpers.py
Source:test_helpers.py
1# Copyright 2014 Konrad Podloucky2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""15Contains tests that wait for angular's processing to finish.16"""17from unittest import TestCase18from .testdriver import TestDriver19from .testserver import SimpleWebServerProcess20class HelperFunctionTestCase(TestCase):21 """Tests for helper functions."""22 @classmethod23 def setUpClass(cls):24 cls.driver = TestDriver(25 'http://localhost:{}/'.format(SimpleWebServerProcess.PORT),26 'body'27 )28 @classmethod29 def tearDownClass(cls):30 cls.driver.quit()31 def setUp(self):32 self.driver.get('index.html')33 def test_location_abs_url_returns_absolute_url(self):34 url = self.driver.location_abs_url35 self.assertIn('/form', url)36 repeater_button = self.driver.find_element_by_link_text('repeater')37 repeater_button.click()38 url = self.driver.location_abs_url39 self.assertIn('/repeater', url)40 def test_set_location_navigates_to_another_url(self):41 self.driver.set_location('/repeater')42 url = self.driver.location_abs_url...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!