Python httpretty.last_request() Examples

The following are 30 code examples of httpretty.last_request(). 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 httpretty , or try the search function .
Example #1
Source File: test_cmd_autogender.py    From grimoirelab-sortinghat with GNU General Public License v3.0 6 votes vote down vote up
def test_command_token(self):
        """Test if autogender is called with token parameter"""

        setup_genderize_server()

        code = self.cmd.run('--api-token', 'abcdefghi')

        self.assertEqual(code, CMD_SUCCESS)
        output = sys.stdout.getvalue().strip()
        self.assertEqual(output, PROFILE_AUTOGENDER)

        expected = {
            'name': ['john'],
            'apikey': ['abcdefghi']
        }

        req = httpretty.last_request()
        self.assertEqual(req.querystring, expected) 
Example #2
Source File: test.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def test_pass_the_received_ignore_hash_param_to_the_datapusher(self):
        config['datapusher.url'] = 'http://datapusher.ckan.org'
        httpretty.HTTPretty.register_uri(
            httpretty.HTTPretty.POST,
            'http://datapusher.ckan.org/job',
            content_type='application/json',
            body=json.dumps({'job_id': 'foo', 'job_key': 'bar'}))

        package = model.Package.get('annakarenina')
        resource = package.resources[0]

        tests.call_action_api(
            self.app, 'datapusher_submit', apikey=self.sysadmin_user.apikey,
            resource_id=resource.id,
            ignore_hash=True
        )

        data = json.loads(httpretty.last_request().body)
        assert data['metadata']['ignore_hash'], data 
Example #3
Source File: test.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def test_providing_res_with_url_calls_datapusher_correctly(self):
        config['datapusher.url'] = 'http://datapusher.ckan.org'
        httpretty.HTTPretty.register_uri(
            httpretty.HTTPretty.POST,
            'http://datapusher.ckan.org/job',
            content_type='application/json',
            body=json.dumps({'job_id': 'foo', 'job_key': 'bar'}))

        package = model.Package.get('annakarenina')

        tests.call_action_api(
            self.app,
            'datastore_create',
            apikey=self.sysadmin_user.apikey,
            resource=dict(package_id=package.id, url='demo.ckan.org')
        )

        assert len(package.resources) == 4, len(package.resources)
        resource = package.resources[3]
        data = json.loads(httpretty.last_request().body)
        assert data['metadata']['resource_id'] == resource.id, data
        assert not data['metadata'].get('ignore_hash'), data
        assert data['result_url'].endswith('/action/datapusher_hook'), data
        assert data['result_url'].startswith('http://'), data 
Example #4
Source File: test_task_projects.py    From grimoirelab-sirmordred with GNU General Public License v3.0 6 votes vote down vote up
def setup_http_server():
    url_projects = read_file(URL_PROJECTS_FILE)

    http_requests = []

    def request_callback(method, uri, headers):
        last_request = httpretty.last_request()

        body = url_projects
        http_requests.append(last_request)

        return 200, headers, body

    httpretty.register_uri(httpretty.GET,
                           PROJECTS_URL,
                           responses=[
                               httpretty.Response(body=request_callback)
                           ])

    return http_requests 
Example #5
Source File: test_task_identities.py    From grimoirelab-sirmordred with GNU General Public License v3.0 6 votes vote down vote up
def setup_http_server():
    remote_identities = read_file(REMOTE_IDENTITIES_FILE)

    http_requests = []

    def request_callback(method, uri, headers):
        last_request = httpretty.last_request()

        if uri.startswith(REMOTE_IDENTITIES_FILE_URL):
            body = remote_identities
        http_requests.append(last_request)

        return 200, headers, body

    httpretty.register_uri(httpretty.GET,
                           REMOTE_IDENTITIES_FILE_URL,
                           responses=[
                               httpretty.Response(body=request_callback)
                           ])

    return http_requests 
Example #6
Source File: test_posting.py    From atomicpuppy with MIT License 6 votes vote down vote up
def because_an_event_is_published_on_a_stream(self):
        httpretty.register_uri(
            httpretty.POST,
            "http://{}:{}/streams/{}".format(self._host, self._port, self.stream),
            body='{}')

        data = {'foo': 'bar'}
        metadata = {'lorem': 'ipsum'}
        evt = Event(
            id=self.event_id,
            type='my-event-type',
            data=data,
            stream=self.stream,
            sequence=None,
            metadata=metadata,
        )
        self.publisher.post(evt, correlation_id=self.correlation_id)
        self.response_body = json.loads(httpretty.last_request().body.decode())[0] 
Example #7
Source File: test_posting.py    From atomicpuppy with MIT License 6 votes vote down vote up
def because_an_event_is_published_on_a_stream(self):
        httpretty.register_uri(
            httpretty.POST,
            "http://{}:{}/streams/{}".format(self._host, self._port, self.stream),
            body='{}')

        data = {'foo': 'bar'}
        evt = Event(
            id=self.event_id,
            type='my-event-type',
            data=data,
            stream=self.stream,
            sequence=None,
            metadata=None,
        )
        self.publisher.post(evt, correlation_id=self.correlation_id)
        self.response_body = json.loads(httpretty.last_request().body.decode())[0] 
Example #8
Source File: android_test.py    From python-client with Apache License 2.0 6 votes vote down vote up
def test_find_element_by_android_data_matcher(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/element'),
            body='{"value": {"element-6066-11e4-a52e-4f735466cecf": "element-id"}}'
        )
        el = driver.find_element_by_android_data_matcher(
            name='title', args=['title', 'Animation'], className='class name')

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['using'] == '-android datamatcher'
        value_dict = json.loads(d['value'])
        assert value_dict['args'] == ['title', 'Animation']
        assert value_dict['name'] == 'title'
        assert value_dict['class'] == 'class name'
        assert el.id == 'element-id' 
Example #9
Source File: android_test.py    From python-client with Apache License 2.0 6 votes vote down vote up
def test_find_elements_by_android_data_matcher(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/elements'),
            body='{"value": [{"element-6066-11e4-a52e-4f735466cecf": "element-id1"}, {"element-6066-11e4-a52e-4f735466cecf": "element-id2"}]}'
        )
        els = driver.find_elements_by_android_data_matcher(name='title', args=['title', 'Animation'])

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['using'] == '-android datamatcher'
        value_dict = json.loads(d['value'])
        assert value_dict['args'] == ['title', 'Animation']
        assert value_dict['name'] == 'title'
        assert els[0].id == 'element-id1'
        assert els[1].id == 'element-id2' 
Example #10
Source File: webelement_test.py    From python-client with Apache License 2.0 6 votes vote down vote up
def test_send_key_with_file(self):
        driver = android_w3c_driver()
        # Should not send this file
        tmp_f = tempfile.NamedTemporaryFile()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/element/element_id/value')
        )

        try:
            element = MobileWebElement(driver, 'element_id', w3c=True)
            element.send_keys(tmp_f.name)
        finally:
            tmp_f.close()

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['text'] == ''.join(d['value']) 
Example #11
Source File: android_test.py    From python-client with Apache License 2.0 6 votes vote down vote up
def test_find_element_by_android_data_matcher(self):
        driver = android_w3c_driver()
        element = MobileWebElement(driver, 'element_id', w3c=True)
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/element/element_id/element'),
            body='{"value": {"element-6066-11e4-a52e-4f735466cecf": "child-element-id"}}'
        )
        el = element.find_element_by_android_data_matcher(
            name='title', args=['title', 'Animation'], className='class name')

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['using'] == '-android datamatcher'
        value_dict = json.loads(d['value'])
        assert value_dict['args'] == ['title', 'Animation']
        assert value_dict['name'] == 'title'
        assert value_dict['class'] == 'class name'
        assert el.id == 'child-element-id' 
Example #12
Source File: test_apikey_api.py    From lecli with MIT License 6 votes vote down vote up
def test_disable_api_key(mocked_url, mocked_owner_apikey, mocked_owner_apikey_id,
                         mocked_account_resource_id, capsys):
    api_key_id = str(uuid.uuid4())
    mocked_url.return_value = '', MOCK_API_URL
    mocked_owner_apikey.return_value = str(uuid.uuid4())
    mocked_owner_apikey_id.return_value = str(uuid.uuid4())
    mocked_account_resource_id.return_value = str(uuid.uuid4())
    httpretty.register_uri(httpretty.PATCH, MOCK_API_URL,
                           status=200,
                           content_type='application/json',
                           body=json.dumps({}))

    api.update(api_key_id, False)

    out, err = capsys.readouterr()
    assert {'apikey': {'active': False}} == json.loads(httpretty.last_request().body)
    assert not err
    assert 'Disabled api key with id: %s' % api_key_id in out 
Example #13
Source File: test_client.py    From edx-analytics-data-api-client with Apache License 2.0 6 votes vote down vote up
def test_request_format(self):
        httpretty.register_uri(httpretty.GET, self.test_url, body='{}')

        response = self.client.get(self.test_endpoint)
        self.assertEqual(httpretty.last_request().headers['Accept'], 'application/json')
        self.assertDictEqual(response, {})

        httpretty.register_uri(httpretty.GET, self.test_url, body='not-json')
        response = self.client.get(self.test_endpoint, data_format=data_formats.CSV)
        self.assertEqual(httpretty.last_request().headers['Accept'], 'text/csv')
        self.assertEqual(response, 'not-json')

        httpretty.register_uri(httpretty.GET, self.test_url, body='{}')
        response = self.client.get(self.test_endpoint, data_format=data_formats.JSON)
        self.assertEqual(httpretty.last_request().headers['Accept'], 'application/json')
        self.assertDictEqual(response, {}) 
Example #14
Source File: test_apikey_api.py    From lecli with MIT License 6 votes vote down vote up
def test_enable_api_key(mocked_url, mocked_owner_apikey, mocked_owner_apikey_id,
                        mocked_account_resource_id, capsys):
    api_key_id = str(uuid.uuid4())
    mocked_url.return_value = '', MOCK_API_URL
    mocked_owner_apikey.return_value = str(uuid.uuid4())
    mocked_owner_apikey_id.return_value = str(uuid.uuid4())
    mocked_account_resource_id.return_value = str(uuid.uuid4())
    httpretty.register_uri(httpretty.PATCH, MOCK_API_URL,
                           status=200,
                           content_type='application/json',
                           body=json.dumps({}))

    api.update(api_key_id, True)

    out, err = capsys.readouterr()
    assert {'apikey': {'active': True}} == json.loads(httpretty.last_request().body)
    assert not err
    assert 'Enabled api key with id: %s' % api_key_id in out 
Example #15
Source File: test_saved_query_api.py    From lecli with MIT License 6 votes vote down vote up
def test_patch_saved_query_none_fields(mocked_url, mocked_rw_apikey, mocked_account_resource_id,
                                       capsys):
    test_saved_query_id = str(uuid.uuid4())
    mocked_url.return_value = '', MOCK_API_URL
    mocked_rw_apikey.return_value = str(uuid.uuid4())
    mocked_account_resource_id.return_value = str(uuid.uuid4())
    httpretty.register_uri(httpretty.PATCH, MOCK_API_URL, status=200,
                           content_type='application/json',
                           body=json.dumps({"saved_query": SAVED_QUERY_RESPONSE}))

    api.update_saved_query(test_saved_query_id, name=None,
                           statement="new_statement")
    out, err = capsys.readouterr()

    assert "Saved query with id %s updated" % test_saved_query_id in out
    body = json.loads(httpretty.last_request().body)['saved_query']
    assert "name" not in body
    assert "statement" in body['leql'] 
Example #16
Source File: test_cmd_autogender.py    From grimoirelab-sortinghat with GNU General Public License v3.0 6 votes vote down vote up
def test_genderize(self):
        """Test if the gender of a name is obtained"""

        setup_genderize_server()

        gender, acc = genderize('John')
        self.assertEqual(gender, 'male')
        self.assertEqual(acc, 99)

        expected = {
            'name': ['John']
        }

        req = httpretty.last_request()
        self.assertEqual(req.method, 'GET')
        self.assertEqual(req.querystring, expected) 
Example #17
Source File: test_cmd_autogender.py    From grimoirelab-sortinghat with GNU General Public License v3.0 6 votes vote down vote up
def test_name_not_found(self):
        """Test if a null response is returned when the name is not found"""

        setup_genderize_server()

        gender, acc = genderize('Jack')
        self.assertEqual(gender, None)
        self.assertEqual(acc, None)

        expected = {
            'name': ['Jack']
        }

        req = httpretty.last_request()
        self.assertEqual(req.method, 'GET')
        self.assertEqual(req.querystring, expected) 
Example #18
Source File: test_posting.py    From atomicpuppy with MIT License 5 votes vote down vote up
def because_an_event_is_published_on_a_stream(self):
        httpretty.register_uri(
            httpretty.POST,
            "http://{}:{}/streams/{}".format(self._host, self._port, self.stream),
            body='{}')

        data = {'foo': 'bar'}
        metadata = {'lorem': 'ipsum'}
        evt = Event(self.event_id, 'my-event-type', data, self.stream, None, metadata)
        self.publisher.post(evt)
        self.response_body = json.loads(httpretty.last_request().body.decode())[0] 
Example #19
Source File: app_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_query_app_state(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/device/app_state'),
            body='{"value": 3 }'
        )
        result = driver.query_app_state('com.app.id')

        assert {'app': 3}, get_httpretty_request_body(httpretty.last_request())
        assert result is ApplicationState.RUNNING_IN_BACKGROUND 
Example #20
Source File: app_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_app_installed(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/device/app_installed'),
            body='{"value": true}'
        )
        result = driver.is_app_installed("com.app.id")
        assert {'app': "com.app.id"}, get_httpretty_request_body(httpretty.last_request())
        assert result is True 
Example #21
Source File: screen_record_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_start_recording_screen(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/start_recording_screen'),
        )
        assert driver.start_recording_screen(user='userA', password='12345') is None

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['options']['user'] == 'userA'
        assert d['options']['pass'] == '12345'
        assert 'password' not in d['options'].keys() 
Example #22
Source File: log_events_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_log_event(self):
        driver = ios_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/log_event'),
            body=""
        )
        vendor_name = 'appium'
        event_name = 'funEvent'
        assert isinstance(driver.log_event(vendor_name, event_name), WebDriver)

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['vendor'] == vendor_name
        assert d['event'] == event_name 
Example #23
Source File: test_manager.py    From stream-django with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unfollow_user(self):
        httpretty.register_uri(httpretty.DELETE, api_url,
              body='{}', status=200,
              content_type='application/json')
        feed_manager.unfollow_user(1, 2)
        last_req = httpretty.last_request()
        self.assertEqual(last_req.method, 'DELETE')
        self.assertTrue(last_req.path.split('?')[0].endswith('1/follows/user:2/')) 
Example #24
Source File: log_events_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_get_events_args(self):
        driver = ios_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/events'),
            body=json.dumps({'value': {'appium:funEvent': [12347]}})
        )
        events_to_filter = ['appium:funEvent']
        events = driver.get_events(events_to_filter)
        assert events['appium:funEvent'] == [12347]

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['type'] == events_to_filter 
Example #25
Source File: log_events_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_get_events(self):
        driver = ios_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/events'),
            body=json.dumps({'value': {'appium:funEvent': [12347]}})
        )
        events = driver.get_events()
        assert events['appium:funEvent'] == [12347]

        d = get_httpretty_request_body(httpretty.last_request())
        assert 'type' not in d.keys() 
Example #26
Source File: app_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_activate_app(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/device/activate_app'),
            body='{"value": ""}'
        )
        result = driver.activate_app("com.app.id")

        assert {'app': 'com.app.id'}, get_httpretty_request_body(httpretty.last_request())
        assert isinstance(result, WebDriver) 
Example #27
Source File: ime_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_activate_ime_engine(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/ime/activate'),
        )
        engine = 'com.android.inputmethod.latin/.LatinIME'
        assert isinstance(driver.activate_ime_engine(engine), WebDriver)

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['engine'] == 'com.android.inputmethod.latin/.LatinIME' 
Example #28
Source File: app_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_background_app(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/app/background'),
            body='{"value": ""}'
        )
        result = driver.background_app(0)
        assert {'app': 0}, get_httpretty_request_body(httpretty.last_request())
        assert isinstance(result, WebDriver) 
Example #29
Source File: execute_driver_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_batch(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/execute_driver'),
            body='{"value": {"result":['
            '{"element-6066-11e4-a52e-4f735466cecf":"39000000-0000-0000-D39A-000000000000",'
            '"ELEMENT":"39000000-0000-0000-D39A-000000000000"},'
            '{"y":237,"x":18,"width":67,"height":24}],"logs":{'
            '"error":[],"warn":["warning message"],"log":[]}}}'
        )

        script = """
            console.warn('warning message');
            const element = await driver.findElement('accessibility id', 'Buttons');
            const rect = await driver.getElementRect(element.ELEMENT);
            return [element, rect];
        """
        response = driver.execute_driver(script=textwrap.dedent(script))
        # Python client convert an element item as WebElement in the result
        assert response.result[0].id == '39000000-0000-0000-D39A-000000000000'
        assert response.result[1]['y'] == 237
        assert response.logs['warn'] == ['warning message']

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['script'] == textwrap.dedent(script)
        assert d['type'] == 'webdriverio'
        assert 'timeout' not in d 
Example #30
Source File: performance_test.py    From python-client with Apache License 2.0 5 votes vote down vote up
def test_get_performance_data(self):
        driver = android_w3c_driver()
        httpretty.register_uri(
            httpretty.POST,
            appium_command('/session/1234567890/appium/getPerformanceData'),
            body='{"value": [["user", "kernel"], ["2.5", "1.3"]]}'
        )
        assert driver.get_performance_data('my.app.package', 'cpuinfo', 5) == [['user', 'kernel'], ['2.5', '1.3']]

        d = get_httpretty_request_body(httpretty.last_request())
        assert d['packageName'] == 'my.app.package'
        assert d['dataType'] == 'cpuinfo'
        assert d['dataReadTimeout'] == 5