Python requests_mock.mock() Examples

The following are 30 code examples of requests_mock.mock(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests_mock , or try the search function .
Example #1
Source File: tests.py    From WazeRouteCalculator with GNU General Public License v3.0 7 votes vote down vote up
def test_calc_route_info_stopatbounds_missing_bounds(self):
        with requests_mock.mock() as m:
            lat = [47.49, 47.612, 47.645]
            lon = [19.04, 18.99, 18.82]
            bounds = [None, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
            length = [400, 5000, 500]
            time = [45, 300, 60]
            address_to_coords_response = [
                '[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":null}]' % (lat[0], lon[0]),
                '[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
            ]
            m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
            route = wrc.WazeRouteCalculator("", "")
        route_mock = mock.Mock(return_value={"results": [
            {"length": length[0], "crossTime": time[0], "path": {"x": lon[0], "y": lat[0]}},
            {"length": length[1], "crossTime": time[1], "path": {"x": lon[1], "y": lat[1]}},
            {"length": length[2], "crossTime": time[2], "path": {"x": lon[2], "y": lat[2]}}
        ]})
        route.get_route = route_mock
        time, dist = route.calc_route_info(stop_at_bounds=True)
        assert route_mock.called
        assert time == 5.75
        assert dist == 5.40 
Example #2
Source File: test_jira.py    From toolium with Apache License 2.0 6 votes vote down vote up
def logger():
    # Configure logger mock
    logger = mock.MagicMock()
    logger_patch = mock.patch('logging.getLogger', mock.MagicMock(return_value=logger))
    logger_patch.start()

    yield logger

    logger_patch.stop()

    # Clear jira module configuration
    jira.enabled = None
    jira.execution_url = None
    jira.summary_prefix = None
    jira.labels = None
    jira.comments = None
    jira.fix_version = None
    jira.build = None
    jira.only_if_changes = None
    jira.jira_tests_status.clear()
    jira.attachments = [] 
Example #3
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_is_remote_video_enabled_disabled(utils):
    # Configure mock
    url = 'http://{}:{}/config'.format('10.20.30.40', 3000)
    config_response_json = {'out': [], 'error': [], 'exit_code': 0,
                            'filename': ['selenium_grid_extras_config.json'],
                            'config_runtime': {'theConfigMap': {
                                'video_recording_options': {'width': '1024', 'videos_to_keep': '5',
                                                            'frames': '30',
                                                            'record_test_videos': 'false'}}}}

    with requests_mock.mock() as req_mock:
        req_mock.get(url, json=config_response_json)

        # Get remote video configuration and check result
        assert utils.is_remote_video_enabled('10.20.30.40') is False
        assert url == req_mock.request_history[0].url 
Example #4
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_is_remote_video_enabled(utils):
    # Configure mock
    url = 'http://{}:{}/config'.format('10.20.30.40', 3000)
    config_response_json = {'out': [], 'error': [], 'exit_code': 0,
                            'filename': ['selenium_grid_extras_config.json'],
                            'config_runtime': {'theConfigMap': {
                                'video_recording_options': {'width': '1024', 'videos_to_keep': '5',
                                                            'frames': '30',
                                                            'record_test_videos': 'true'}}}}

    with requests_mock.mock() as req_mock:
        req_mock.get(url, json=config_response_json)

        # Get remote video configuration and check result
        assert utils.is_remote_video_enabled('10.20.30.40') is True
        assert url == req_mock.request_history[0].url 
Example #5
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_wait_until_first_element_is_found_timeout(driver_wrapper, utils):
    # Configure driver mock
    driver_wrapper.driver.find_element.side_effect = NoSuchElementException('Unknown')
    element_locator = (By.ID, 'element_id')

    start_time = time.time()
    with pytest.raises(TimeoutException) as excinfo:
        utils.wait_until_first_element_is_found([element_locator])
    end_time = time.time()

    assert 'None of the page elements has been found after 10 seconds' in str(excinfo.value)
    # find_element has been called more than one time
    driver_wrapper.driver.find_element.assert_called_with(*element_locator)
    # Execution time must be greater than timeout
    assert end_time - start_time > 10 
Example #6
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_get_remote_video_url(utils):
    # Configure mock
    url = 'http://{}:{}/video'.format('10.20.30.40', 3000)
    video_url = 'http://{}:{}/download_video/f4.mp4'.format('10.20.30.40', 3000)
    video_response_json = {'exit_code': 1, 'out': [],
                           'error': ['Cannot call this endpoint without required parameters: session and action'],
                           'available_videos': {'5af': {'size': 489701,
                                                        'session': '5af',
                                                        'last_modified': 1460041262558,
                                                        'download_url': video_url,
                                                        'absolute_path': 'C:\\f4.mp4'}},
                           'current_videos': []}

    with requests_mock.mock() as req_mock:
        req_mock.get(url, json=video_response_json)

        # Get remote video url and check result
        assert utils._get_remote_video_url('10.20.30.40', '5af') == video_url
        assert url == req_mock.request_history[0].url 
Example #7
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_get_remote_node_non_grid(driver_wrapper, utils):
    # Configure mock
    driver_wrapper.driver.session_id = '5af'
    grid_url = 'http://{}:{}/grid/api/testsession?session={}'.format('localhost', 4444, '5af')
    ggr_url = 'http://{}:{}/host/{}'.format('localhost', 4444, '5af')
    selenoid_url = 'http://{}:{}/status'.format('localhost', 4444)

    with requests_mock.mock() as req_mock:
        req_mock.get(grid_url, text='non_json_response')
        req_mock.get(ggr_url, json={})
        req_mock.get(selenoid_url, json={})

        # Get remote node and check result
        assert utils.get_remote_node() == ('selenium', 'localhost')
        assert grid_url == req_mock.request_history[0].url
        assert ggr_url == req_mock.request_history[1].url
        assert selenoid_url == req_mock.request_history[2].url 
Example #8
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def test_get_remote_node_ggr(driver_wrapper, utils):
    # Configure mock
    driver_wrapper.driver.session_id = '5af'
    grid_url = 'http://{}:{}/grid/api/testsession?session={}'.format('localhost', 4444, '5af')
    ggr_url = 'http://{}:{}/host/{}'.format('localhost', 4444, '5af')
    ggr_response_json = {'Count': 3, 'Username': '', 'Scheme': '', 'VNC': '', 'Name': 'host_name', 'Password': '',
                         'Port': 4500}

    with requests_mock.mock() as req_mock:
        req_mock.get(grid_url, text='non_json_response')
        req_mock.get(ggr_url, json=ggr_response_json)

        # Get remote node and check result
        assert utils.get_remote_node() == ('ggr', 'host_name')
        assert grid_url == req_mock.request_history[0].url
        assert ggr_url == req_mock.request_history[1].url 
Example #9
Source File: test_virtual_switch.py    From python-zhmcclient with Apache License 2.0 6 votes vote down vote up
def setup_method(self):
        self.session = Session('vswitch-dpm-host', 'vswitch-user',
                               'vswitch-pwd')
        self.client = Client(self.session)
        with requests_mock.mock() as m:
            # Because logon is deferred until needed, we perform it
            # explicitly in order to keep mocking in the actual test simple.
            m.post('/api/sessions', json={'api-session': 'vswitch-session-id'})
            self.session.logon()

        self.cpc_mgr = self.client.cpcs
        with requests_mock.mock() as m:
            result = {
                'cpcs': [
                    {
                        'object-uri': '/api/cpcs/vswitch-cpc-id-1',
                        'name': 'CPC',
                        'status': 'service-required',
                    }
                ]
            }
            m.get('/api/cpcs', json=result)

            cpcs = self.cpc_mgr.list()
            self.cpc = cpcs[0] 
Example #10
Source File: test_virtual_function.py    From python-zhmcclient with Apache License 2.0 6 votes vote down vote up
def test_create(self):
        """
        This tests the 'Create Virtual Function' operation.
        """
        vf_mgr = self.partition.virtual_functions
        with requests_mock.mock() as m:
            result = {
                'element-uri':
                    '/api/partitions/fake-part-id-1/virtual-functions/'
                    'fake-vf-id-1'
            }
            m.post('/api/partitions/fake-part-id-1/virtual-functions',
                   json=result)

            vf = vf_mgr.create(properties={})

            assert isinstance(vf, VirtualFunction)
            assert vf.properties == result
            assert vf.uri == result['element-uri'] 
Example #11
Source File: test_driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
def driver_wrapper():
    # Reset wrappers pool values
    DriverWrappersPool._empty_pool()
    DriverWrapper.config_properties_filenames = None

    # Create a new wrapper
    driver_wrapper = DriverWrappersPool.get_default_wrapper()
    driver_wrapper.driver = mock.MagicMock()

    # Configure properties
    root_path = os.path.dirname(os.path.realpath(__file__))
    config_files = ConfigFiles()
    config_files.set_config_directory(os.path.join(root_path, 'conf'))
    config_files.set_config_properties_filenames('properties.cfg')
    config_files.set_output_directory(os.path.join(root_path, 'output'))
    driver_wrapper.configure(config_files)

    yield driver_wrapper

    # Reset wrappers pool values
    DriverWrappersPool._empty_pool()
    DriverWrapper.config_properties_filenames = None 
Example #12
Source File: tests.py    From WazeRouteCalculator with GNU General Public License v3.0 6 votes vote down vote up
def test_calc_route_info_with_path_not_ignored(self):
        with requests_mock.mock() as m:
            lat = [47.49, 47.612, 47.645]
            lon = [19.04, 18.99, 18.82]
            bounds = [{"bottom": 47.4, "top": 47.5, "left": 19, "right": 19.1}, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
            length = [400, 5000, 500]
            time = [40, 300, 50]
            address_to_coords_response = [
                '[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[0], lon[0], str(bounds[0]).replace("'", '"')),
                '[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
            ]
            m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
            route = wrc.WazeRouteCalculator("", "")
        route_mock = mock.Mock(return_value={"results": [
            {"length": length[0], "crossTime": time[0], "path": {"x": lon[0], "y": lat[0]}},
            {"length": length[1], "crossTime": time[1], "path": {"x": lon[1], "y": lat[1]}},
            {"length": length[2], "crossTime": time[2], "path": {"x": lon[2], "y": lat[2]}}
        ]})
        route.get_route = route_mock
        time, dist = route.calc_route_info()
        assert route_mock.called
        assert time == 6.5
        assert dist == 5.9 
Example #13
Source File: tests.py    From WazeRouteCalculator with GNU General Public License v3.0 6 votes vote down vote up
def test_calc_route_info_with_ignored_and_nort(self):
        with requests_mock.mock() as m:
            lat = [47.49, 47.612, 47.645]
            lon = [19.04, 18.99, 18.82]
            bounds = [{"bottom": 47.4, "top": 47.5, "left": 19, "right": 19.1}, None, {"bottom": 47.6, "top": 47.7, "left": 18.8, "right": 18.9}]
            length = [400, 5000, 500]
            time = [40, 360, 60]
            nort_time = [40, 300, 50]
            address_to_coords_response = [
                '[{"city":"Test1","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[0], lon[0], str(bounds[0]).replace("'", '"')),
                '[{"city":"Test2","location":{"lat":%s,"lon":%s},"bounds":%s}]' % (lat[2], lon[2], str(bounds[2]).replace("'", '"'))
            ]
            m.get(self.address_req, [{'text': address_to_coords_response[0]}, {'text': address_to_coords_response[1]}])
            route = wrc.WazeRouteCalculator("", "")
        route_mock = mock.Mock(return_value={"results": [
            {"length": length[0], "crossTime": time[0], "crossTimeWithoutRealTime": nort_time[0], "path": {"x": lon[0], "y": lat[0]}},
            {"length": length[1], "crossTime": time[1], "crossTimeWithoutRealTime": nort_time[1], "path": {"x": lon[1], "y": lat[1]}},
            {"length": length[2], "crossTime": time[2], "crossTimeWithoutRealTime": nort_time[2], "path": {"x": lon[2], "y": lat[2]}}
        ]})
        route.get_route = route_mock
        time, dist = route.calc_route_info(stop_at_bounds=True, real_time=False)
        assert route_mock.called
        assert time == 5.00
        assert dist == 5.00 
Example #14
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_wait_until_first_element_is_found_page_element(utils):
    # Mock Driver.save_web_element = True
    driver_wrapper.config = mock.MagicMock()
    driver_wrapper.config.getboolean_optional.return_value = True
    page_element = PageElement(By.ID, 'element_id')
    page_element._web_element = 'mock_element'

    element = utils.wait_until_first_element_is_found([page_element])

    assert page_element == element 
Example #15
Source File: test_session.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def _do_parse_error_logon(self, m, json_content, exp_msg_pattern, exp_line,
                              exp_col):
        """
        Perform a session logon, and mock the provided (invalid) JSON content
        for the response so that a JSON parsing error is triggered.

        Assert that this is surfaced via a `zhmcclient.ParseError` exception,
        with the expected message (as a regexp pattern), line and column.
        """

        m.register_uri('POST', '/api/sessions',
                       content=json_content,
                       headers={'X-Request-Id': 'fake-request-id'})

        session = Session('fake-host', 'fake-user', 'fake-pw')

        exp_pe_pattern = \
            r"^JSON parse error in HTTP response: %s\. " \
            r"HTTP request: [^ ]+ [^ ]+\. " \
            r"Response status .*" % \
            exp_msg_pattern

        with pytest.raises(ParseError) as exc_info:
            session.logon()
        exc = exc_info.value

        assert re.match(exp_pe_pattern, str(exc))
        assert exc.line == exp_line
        assert exc.column == exp_col

    # TODO: Merge the next 3 test functions into one that is parametrized 
Example #16
Source File: test_port.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def test_list_filter_name_ok(self):
        """
        Test successful list() with filter arguments using the 'name' property
        on a PortManager instance in a partition.
        """
        adapters = self.adapters
        adapter = adapters[0]
        port_mgr = adapter.ports

        with requests_mock.mock() as m:

            mock_result_port1 = {
                'parent': '/api/adapters/fake-adapter-id-1',
                'index': 0,
                'fabric-id': '',
                'description': '',
                'element-uri':
                    '/api/adapters/fake-adapter-id-1/storage-ports/0',
                'element-id': '0',
                'class': 'storage-port',
                'name': 'Port 0'
            }
            m.get('/api/adapters/fake-adapter-id-1/storage-ports/0',
                  json=mock_result_port1)

            filter_args = {'name': 'Port 0'}
            ports = port_mgr.list(filter_args=filter_args)

            assert len(ports) == 1
            port = ports[0]
            assert port.name == 'Port 0'
            assert port.uri == \
                '/api/adapters/fake-adapter-id-1/storage-ports/0'
            assert port.properties['name'] == 'Port 0'
            assert port.properties['element-id'] == '0'
            assert port.manager == port_mgr 
Example #17
Source File: test_virtual_switch.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def test_list_short_ok(self):
        """
        Test successful list() with short set of properties
        on VirtualSwitchManager instance in CPC.
        """
        vswitch_mgr = self.cpc.virtual_switches
        with requests_mock.mock() as m:
            result = {
                'virtual-switches': [
                    {
                        'name': 'VSWITCH1',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id1',
                        'type': 'osd'
                    },
                    {
                        'name': 'VSWITCH2',
                        'object-uri': '/api/virtual-switches/fake-vswitch-id2',
                        'type': 'hpersockets'
                    }
                ]
            }

            m.get('/api/cpcs/vswitch-cpc-id-1/virtual-switches', json=result)

            vswitches = vswitch_mgr.list(full_properties=False)

            assert len(vswitches) == len(result['virtual-switches'])
            for idx, vswitch in enumerate(vswitches):
                assert vswitch.properties == \
                    result['virtual-switches'][idx]
                assert vswitch.uri == \
                    result['virtual-switches'][idx]['object-uri']
                assert not vswitch.full_properties
                assert vswitch.manager == vswitch_mgr 
Example #18
Source File: test_port.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def teardown_method(self):
        with requests_mock.mock() as m:
            m.delete('/api/sessions/this-session', status_code=204)
            self.session.logoff() 
Example #19
Source File: test_port.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def test_list_short_ok(self):
        """
        Test successful list() with short set of properties on PortManager
        instance in Adapter.
        """
        adapters = self.adapters
        for idy, adapter in enumerate(adapters):
            with requests_mock.mock() as m:
                m.get(adapter.uri, json=adapter.properties)
                port_mgr = adapter.ports
            ports = port_mgr.list(full_properties=False)
            if len(ports) != 0:
                result_adapter = self.result['adapters'][idy]
                if 'storage-port-uris' in result_adapter:
                    storage_uris = result_adapter['storage-port-uris']
                    uris = storage_uris
                else:
                    network_uris = result_adapter['network-port-uris']
                    uris = network_uris
                assert adapter.properties['port-count'] == len(uris)
            else:
                uris = []

            assert len(ports) == len(uris)
            for idx, port in enumerate(ports):
                assert port.properties['element-uri'] in uris
                assert not port.full_properties
                assert port.manager == port_mgr 
Example #20
Source File: test_port.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def test_list_full_ok(self):
        """
        Test successful list() with full set of properties on PortManager
        instance in Adapter.
        """
        adapters = self.adapters
        adapter = adapters[0]
        port_mgr = adapter.ports

        with requests_mock.mock() as m:

            mock_result_port1 = {
                'parent': '/api/adapters/fake-adapter-id-1',
                'index': 0,
                'fabric-id': '',
                'description': '',
                'element-uri':
                    '/api/adapters/fake-adapter-id-1/storage-ports/0',
                'element-id': '0',
                'class': 'storage-port',
                'name': 'Port 0'
            }
            m.get('/api/adapters/fake-adapter-id-1/storage-ports/0',
                  json=mock_result_port1)

            ports = port_mgr.list(full_properties=True)
            if len(ports) != 0:
                storage_uris = self.result['adapters'][0]['storage-port-uris']
                assert adapter.properties['port-count'] == len(storage_uris)
            else:
                storage_uris = []

            assert len(ports) == len(storage_uris)
            for idx, port in enumerate(ports):
                assert port.properties['element-uri'] == storage_uris[idx]
                assert port.full_properties
                assert port.manager == port_mgr 
Example #21
Source File: test_jira.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_change_jira_status_empty_url(jira_get, logger):
    # Configure jira mock
    jira_get.side_effect = ConnectionError('exception error')

    # Configure jira module
    jira.enabled = True

    # Test method
    jira.change_jira_status('TOOLIUM-1', 'Pass', None, [])

    # Check logging error message
    logger.warning.assert_called_once_with("Test Case '%s' can not be updated: execution_url is not configured",
                                           'TOOLIUM-1') 
Example #22
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_wait_until_first_element_is_found_locator(driver_wrapper, utils):
    # Configure driver mock
    driver_wrapper.driver.find_element.return_value = 'mock_element'
    element_locator = (By.ID, 'element_id')

    element = utils.wait_until_first_element_is_found([element_locator])

    assert element_locator == element
    driver_wrapper.driver.find_element.assert_called_once_with(*element_locator) 
Example #23
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_get_web_element_from_locator(driver_wrapper, utils):
    # Configure driver mock
    driver_wrapper.driver.find_element.return_value = 'mock_element'
    element_locator = (By.ID, 'element_id')

    # Get element and assert response
    web_element = utils.get_web_element(element_locator)
    assert 'mock_element' == web_element
    driver_wrapper.driver.find_element.assert_called_once_with(*element_locator) 
Example #24
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_swipe_web(driver_wrapper, utils):
    # Configure driver mock
    driver_wrapper.config.set('Driver', 'type', 'firefox')

    # Create element mock
    element = get_mock_element(x=250, y=40, height=40, width=300)

    with pytest.raises(Exception) as excinfo:
        utils.swipe(element, 50, 100)
    assert 'Swipe method is not implemented in Selenium' == str(excinfo.value) 
Example #25
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_swipe_ios_web(driver_wrapper, utils):
    # Configure driver mock
    web_window_size = {'width': 500, 'height': 667}
    native_window_size = {'width': 250, 'height': 450}
    driver_wrapper.driver.get_window_size.side_effect = [web_window_size, native_window_size]
    driver_wrapper.config.set('Driver', 'type', 'ios')
    driver_wrapper.config.set('AppiumCapabilities', 'browserName', 'safari')

    # Create element mock
    element = get_mock_element(x=250, y=40, height=40, width=300)

    utils.swipe(element, 50, 100)
    driver_wrapper.driver.swipe.assert_called_once_with(200, 94, 50, 100, None) 
Example #26
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_swipe_android_hybrid(driver_wrapper, utils):
    # Configure driver mock
    web_window_size = {'width': 500, 'height': 667}
    native_window_size = {'width': 250, 'height': 450}
    # driver_wrapper.utils
    driver_wrapper.driver.get_window_size.side_effect = [web_window_size, native_window_size]
    driver_wrapper.driver.current_context = 'WEBVIEW'
    driver_wrapper.config.set('Driver', 'type', 'android')
    driver_wrapper.config.set('AppiumCapabilities', 'app', 'C:/Demo.apk')

    # Create element mock
    element = get_mock_element(x=250, y=40, height=40, width=300)

    utils.swipe(element, 50, 100)
    driver_wrapper.driver.swipe.assert_called_once_with(200, 30, 250, 130, None) 
Example #27
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_swipe_android_web(driver_wrapper, utils):
    # Configure driver mock
    web_window_size = {'width': 500, 'height': 667}
    native_window_size = {'width': 250, 'height': 450}
    driver_wrapper.driver.current_context = 'WEBVIEW'
    driver_wrapper.driver.execute_script.side_effect = [web_window_size['width'], web_window_size['height']]
    driver_wrapper.driver.get_window_size.side_effect = [native_window_size]
    driver_wrapper.config.set('Driver', 'type', 'android')
    driver_wrapper.config.set('AppiumCapabilities', 'browserName', 'chrome')

    # Create element mock
    element = get_mock_element(x=250, y=40, height=40, width=300)

    utils.swipe(element, 50, 100)
    driver_wrapper.driver.swipe.assert_called_once_with(200, 30, 250, 130, None) 
Example #28
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_swipe_android_native(driver_wrapper, utils):
    # Configure driver mock
    web_window_size = {'width': 500, 'height': 667}
    native_window_size = {'width': 250, 'height': 450}
    driver_wrapper.driver.get_window_size.side_effect = [web_window_size, native_window_size]
    driver_wrapper.driver.current_context = 'NATIVE_APP'
    driver_wrapper.config.set('Driver', 'type', 'android')
    driver_wrapper.config.set('AppiumCapabilities', 'app', 'C:/Demo.apk')

    # Create element mock
    element = get_mock_element(x=250, y=40, height=40, width=300)

    utils.swipe(element, 50, 100)
    driver_wrapper.driver.swipe.assert_called_once_with(400, 60, 450, 160, None) 
Example #29
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_get_native_coords_android_web(driver_wrapper, utils):
    # Configure driver mock
    web_window_size = {'width': 500, 'height': 667}
    native_window_size = {'width': 250, 'height': 450}
    driver_wrapper.driver.current_context = 'WEBVIEW'
    driver_wrapper.driver.execute_script.side_effect = [web_window_size['width'], web_window_size['height']]
    driver_wrapper.driver.get_window_size.side_effect = [native_window_size]
    driver_wrapper.config.set('Driver', 'type', 'android')
    driver_wrapper.config.set('AppiumCapabilities', 'browserName', 'chrome')

    web_coords = {'x': 105, 'y': 185}
    native_coords = {'x': 52.5, 'y': 92.5}
    assert utils.get_native_coords(web_coords) == native_coords 
Example #30
Source File: test_driver_utils.py    From toolium with Apache License 2.0 5 votes vote down vote up
def test_get_window_size_android_web_two_times(driver_wrapper, utils):
    # Configure driver mock
    window_size = {'width': 375, 'height': 667}
    driver_wrapper.driver.current_context = 'WEBVIEW'
    driver_wrapper.driver.execute_script.side_effect = [window_size['width'], window_size['height']]
    driver_wrapper.config.set('Driver', 'type', 'android')
    driver_wrapper.config.set('AppiumCapabilities', 'browserName', 'chrome')

    assert utils.get_window_size() == window_size
    assert utils.get_window_size() == window_size
    # Check that window size is calculated only one time
    driver_wrapper.driver.execute_script.assert_has_calls(
        [mock.call('return window.innerWidth'), mock.call('return window.innerHeight')])