def setUp(self): from certbot_dns_desec.dns_desec import _DesecConfigClient self.adapter = requests_mock.Adapter() self.client = _DesecConfigClient(FAKE_ENDPOINT, FAKE_TOKEN) self.client.session.mount("mock", self.adapter)
def setUp(self): self.adapter = requests_mock.Adapter() self.path = '/foo' self.url = settings.SCHEDULER_URL + self.path # use the real scheduler client. self.scheduler = scheduler.KubeHTTPClient(settings.SCHEDULER_URL) self.scheduler.session.mount(self.url, self.adapter)
def test_post(mock_login, sm): import json from requests.exceptions import HTTPError adapter = requests_mock.Adapter() sm.session.mount("mock", adapter) mock_url = "mock://test.com" expected = [ { "text": '{"error": "login error"}', "status_code": 401 }, { "text": '{"test": "321"}', "status_code": 200 }, { "text": '{"error": "resource not found"}', "status_code": 404 }, ] adapter.register_uri("POST", mock_url, expected) resp1 = sm.post(mock_url) with pytest.raises(HTTPError) as e: sm.post(mock_url) assert resp1 == json.loads(expected[1]["text"]) assert mock_login.call_count == 1 assert "404 Client Error" in str(e.value)
def test_replace(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter) response_data = "replace_songs.txt" data = [ { "theme": "Surfing", "artist": "Wavves", "title": "King of the Beach", "year": "2010" }, { "theme": "History", "artist": "Best Friends Forever", "title": "Abe Lincoln", "year": "2008" }, ] setup_mock(adapter, "PUT", response_data, 200) response = client.replace(DATASET_IDENTIFIER, data) assert isinstance(response, dict) assert response.get("Rows Created") == 2 client.close()
def test_create(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter) response_data = "create_foobar.txt" setup_mock(adapter, "POST", response_data, 200, dataset_identifier=None) columns = [ {"fieldName": "foo", "name": "Foo", "dataTypeName": "text"}, {"fieldName": "bar", "name": "Bar", "dataTypeName": "number"} ] tags = ["foo", "bar"] response = client.create("Foo Bar", description="test dataset", columns=columns, tags=tags, row_identifier="bar") request = adapter.request_history[0] request_payload = json.loads(request.text) # can't figure out how to use .json # Test request payload for dataset_key in ["name", "description", "columns", "tags"]: assert dataset_key in request_payload for column_key in ["fieldName", "name", "dataTypeName"]: assert column_key in request_payload["columns"][0] # Test response assert isinstance(response, dict) assert len(response.get("id")) == 9 client.close()
def test_client_do_basic(): c = Client() c.set_base_url('mock://test/') adapter = requests_mock.Adapter() c.session.mount('mock', adapter) adapter.register_uri('GET', 'mock://test/', text='ok') with pytest.raises(Exception): res = c.do('GET', '/') adapter.register_uri('GET', 'mock://test/', text='{"key":"value"}') res = c.do('GET', '/') assert res['key'] == 'value' adapter.register_uri('GET', 'mock://test/', text='{}', status_code=400) res = c.do('GET', '/') # no exception, because no error present adapter.register_uri('GET', 'mock://test/', text='{"error_code":"code","error":"message"}', status_code=400) with pytest.raises(APIError) as e: res = c.do('GET', '/') assert e.value.code == 'code' assert e.value.message == 'message'
def test_delete(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) uri = "{0}{1}{2}/{3}.json".format(PREFIX, DOMAIN, OLD_API_PATH, DATASET_IDENTIFIER) adapter.register_uri("DELETE", uri, status_code=200) response = client.delete(DATASET_IDENTIFIER) assert response.status_code == 200 try: client.delete("foobar") except Exception as e: assert isinstance(e, requests_mock.exceptions.NoMockAddress) finally: client.close()
def test_issuer_plugin_create_certificate(certificate_="""\ -----BEGIN CERTIFICATE----- abc -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- def -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- ghi -----END CERTIFICATE----- """): import requests_mock from lemur.plugins.lemur_digicert.plugin import DigiCertIssuerPlugin pem_fixture = certificate_ subject = DigiCertIssuerPlugin() adapter = requests_mock.Adapter() adapter.register_uri('POST', 'mock://www.digicert.com/services/v2/order/certificate/ssl_plus', text=json.dumps({'id': 'id123'})) adapter.register_uri('GET', 'mock://www.digicert.com/services/v2/order/certificate/id123', text=json.dumps({'status': 'issued', 'certificate': {'id': 'cert123'}})) adapter.register_uri('GET', 'mock://www.digicert.com/services/v2/certificate/cert123/download/format/pem_all', text=pem_fixture) subject.session.mount('mock', adapter) cert, intermediate, external_id = subject.create_certificate("", {'common_name': 'test.com'}) assert cert == "-----BEGIN CERTIFICATE-----\nabc\n-----END CERTIFICATE-----" assert intermediate == "-----BEGIN CERTIFICATE-----\ndef\n-----END CERTIFICATE-----"
def test_handle_crawl_request_response(): content = create_input_file() session = requests.Session() adapter = requests_mock.Adapter() session.mount('mock', adapter) adapter.register_uri('POST', 'mock://test.com/fail_schedule.json', text='Not Found', status_code=404) adapter.register_uri('POST', 'mock://test.com/pass_schedule.json', text='Found', status_code=200) not_found_response = session.post('mock://test.com/fail_schedule.json') found_response = session.post('mock://test.com/pass_schedule.json') cr = create_class_instance(['-f', content.name, '-c', 'gb']) assert cr.handle_crawl_request_response(not_found_response) == False assert cr.handle_crawl_request_response(found_response) == True e_msg = '404 Client Error: None for url: mock://test.com/fail_schedule.json' with pytest.raises(requests.exceptions.HTTPError) as excinfo: raise requests.exceptions.HTTPError(e_msg) assert excinfo.value.message == e_msg content.delete
def init_failed_mock(smart_system): adapter = requests_mock.Adapter() adapter.register_uri( "POST", "https://smart.gardena.com/sg-1/sessions", json={ "sessions": { "token": "7867e26c-05eb-4a60-bf30-7c3a1b4480aa", "user_id": "196ab891-a521-872c-ab1d-1685d1e77afc", } }, status_code=200, ) adapter.register_uri( "GET", "https://smart.gardena.com/sg-1/locations/?user_id=196ab891-a521-872c-ab1d-1685d1e77afc", json={}, status_code=400, ) adapter.register_uri( "GET", "https://smart.gardena.com/sg-1/devices/?locationId=1c8b301f-22c8-423d-1b4d-ec25315d1377", json={}, status_code=400, ) smart_system.request_session.mount("https://smart.gardena.com/", adapter)
def setUp(self): from certbot_dns_yandexcloud.dns_yandexcloud import _YandexCloudClient self.adapter = requests_mock.Adapter() self.client = _YandexCloudClient(FAKE_ENDPOINT, FAKE_USER, FAKE_PW) self.client.session.mount("mock", self.adapter)
def setUp(self): from certbot_dns_constellix.dns_constellix import _ConstellixClient self.adapter = requests_mock.Adapter() self.client = _ConstellixClient(FAKE_ENDPOINT, FAKE_USER, FAKE_PW) self.client.session.mount("mock", self.adapter)
def create_adapter(): """ Factory :return: """ adapter = requests_mock.Adapter() return register_mock_endpoints(adapter)
def __init__(self, conf): super(MockSchemaRegistryClient, self).__init__(conf) adapter = requests_mock.Adapter() adapter.register_uri('GET', self.compatibility, json=self.get_compatibility_callback) adapter.register_uri('PUT', self.compatibility, json=self.put_compatibility_callback) adapter.register_uri('GET', self.schemas, json=self.get_schemas_callback) adapter.register_uri('DELETE', self.subjects, json=self.delete_subject_callback) adapter.register_uri('GET', self.subjects, json=self.get_subject_callback) adapter.register_uri('POST', self.subjects, json=self.post_subject_callback) adapter.register_uri('GET', self.subject_versions, json=self.get_subject_version_callback) adapter.register_uri('DELETE', self.subject_versions, json=self.delete_subject_version_callback) adapter.register_uri('POST', self.subject_versions, json=self.post_subject_version_callback) self._rest_client.session.mount('http://', adapter)
def __init__( self, url: str, instance_name: str, user_domain: str = None, username: str = None, password: str = None, client_cert: tuple = None, session_token: str = None, ): """Init.""" self.logger = logging.getLogger(__name__) self.url = url self.instance_name = instance_name self.user_domain = user_domain self.username = username self.password = password self.session_token = session_token self.api_url_base = f"{self.url}/api/" self.content_api_url_base = f"{self.url}/contentapi/" self.platform_api_url_base = f"{self.url}/platformapi/" self.session = requests.Session() self.session.cert = client_cert # For mocking self.adapter = requests_mock.Adapter() self.session.mount('mock', self.adapter) self.mock_response = None self.adapter.add_matcher(stubber)
def mock_rpc_session(): adapter = requests_mock.Adapter() session = requests.Session() session.mount('mock', adapter) session.adapter = adapter responses = {} def _text_callback(request, context): request_json = json.dumps(request.json(), sort_keys=True) if request_json not in responses: raise MockRPCMatchException( 'No mock response found for this request: %s' % json.dumps(request.json(), sort_keys=True, indent=2)) return responses[request_json] for action, tests in load_mock_rpc_tests().items(): for test in tests: req_body = json.dumps(test['request'], sort_keys=True) res_body = json.dumps(test['response'], sort_keys=True) responses[req_body] = res_body adapter.register_uri('POST', 'mock://localhost:7076/', text=_text_callback) return session
def setUp(self): session = requests.Session() adapter = requests_mock.Adapter() session.mount('mock', adapter) self.get_hook = HttpHook(method='GET') self.get_lowercase_hook = HttpHook(method='get') self.post_hook = HttpHook(method='POST')
def verify_find_nodes_call(self, prefix, expected_branch_nodes, expected_leaf_nodes, bff, bf_mock_response): actual_branch_nodes = set() actual_leaf_nodes = set() session = requests.Session() adapter = requests_mock.Adapter() session.mount('mock', adapter) with requests_mock.mock() as m: m.get('/v2.0/99999/metric_name/search', json=bf_mock_response, status_code=200) for n in bff.find_nodes(storage.FindQuery(prefix, 1, 2)): if isinstance(n, BranchNode): actual_branch_nodes.add(n.path) else: actual_leaf_nodes.add(n.path) # Leaf node print "Branch Nodes: %s" % actual_branch_nodes print "Leaf nodes: %s" % actual_leaf_nodes self.assertEquals(expected_branch_nodes, actual_branch_nodes) self.assertEquals(expected_leaf_nodes, actual_leaf_nodes)
def test_upsert(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) response_data = "upsert_songs.txt" data = [{ "theme": "Surfing", "artist": "Wavves", "title": "King of the Beach", "year": "2010", }] setup_mock(adapter, "POST", response_data, 200) response = client.upsert(DATASET_IDENTIFIER, data) assert isinstance(response, dict) assert response.get("Rows Created") == 1 client.close()
def setUp(self): session = requests.Session() adapter = requests_mock.Adapter() session.mount('mock', adapter) self.get_hook = HttpHook(method='GET') self.post_hook = HttpHook(method='POST') configuration.load_test_config()
def test_replace_non_data_file(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) response_data = "successblobres.txt" nondatasetfile_path = "tests/test_data/nondatasetfile.zip" setup_replace_non_data_file(adapter, "POST", response_data, 200) with open(nondatasetfile_path, "rb") as fin: file = {"file": ("nondatasetfile.zip", fin)} response = client.replace_non_data_file(DATASET_IDENTIFIER, {}, file) assert isinstance(response, dict) assert response.get("blobFileSize") == 496 client.close()
def setUp(self): from certbot_dns_ispconfig.dns_ispconfig import _ISPConfigClient self.adapter = requests_mock.Adapter() self.client = _ISPConfigClient(FAKE_ENDPOINT, FAKE_USER, FAKE_PW) self.client.session.mount("mock", self.adapter)
def verify_find_nodes_call(self, prefix, expected_branch_nodes, expected_leaf_nodes, bff, bf_mock_response, bf_enum_mock_response): actual_branch_nodes = set() actual_leaf_nodes = set() session = requests.Session() adapter = requests_mock.Adapter() session.mount('mock', adapter) with requests_mock.mock() as m: m.get('/v2.0/99999/metrics/search', json=bf_mock_response, status_code=200) query_parts = prefix.split('.') if len(query_parts) > 1: enum_name = ".".join(query_parts[:-1]) m.get( '/v2.0/99999/metrics/search?include_enum_values=true&query=' + enum_name, json=bf_enum_mock_response, status_code=200) for n in bff.find_nodes(storage.FindQuery(prefix, 1, 2)): if isinstance(n, BranchNode): actual_branch_nodes.add(n.path) else: actual_leaf_nodes.add(n.path) # Leaf node print "Branch Nodes: %s" % actual_branch_nodes print "Leaf nodes: %s" % actual_leaf_nodes self.assertEquals(expected_branch_nodes, actual_branch_nodes) self.assertEquals(expected_leaf_nodes, actual_leaf_nodes)
def setUp(self): self.session = requests.Session() self.adapter = requests_mock.Adapter() self.session.mount('https://', self.adapter) APIGebiedenLoader._get_session = lambda instance: self.session self.api_loader = APIGebiedenLoader(**{'type_string': 'stadsdeel'}) # We mock the API output using some saved API output (edited to have # only two stadsdeel instances). self.centrum_url = 'https://api.data.amsterdam.nl/gebieden/stadsdeel/03630000000018/' self.zuidoost_url = 'https://api.data.amsterdam.nl/gebieden/stadsdeel/03630000000016/' self.list_endpoint = 'https://api.data.amsterdam.nl/gebieden/stadsdeel/' self.page_1_url = 'https://api.data.amsterdam.nl/gebieden/stadsdeel/?page_size=1' self.page_2_url = 'https://api.data.amsterdam.nl/gebieden/stadsdeel/?page=2&page_size=1' url_json_mapping = [ (self.centrum_url, 'centrum.json'), (self.zuidoost_url, 'zuidoost.json'), (self.page_1_url, 'gebieden_page_1.json'), (self.list_endpoint, 'gebieden_page_1.json' ), # first page serves as stand-in for list endpoint (self.page_2_url, 'gebieden_page_2.json'), ] for url, json_file in url_json_mapping: with open(join(THIS_DIR, json_file), 'r') as f: data = json.load(f) self.adapter.register_uri('GET', url, json=data)
def test_set_permission(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter) response_data = "empty.txt" setup_old_api_mock(adapter, "PUT", response_data, 200) # Test response response = client.set_permission(DATASET_IDENTIFIER, "public") assert response.status_code == 200 # Test request request = adapter.request_history[0] query_string = request.url.split("?")[-1] params = query_string.split("&") assert len(params) == 2 assert "method=setPermission" in params assert "value=public.read" in params client.close()
def test_get_all(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter) setup_mock(adapter, "GET", "bike_counts_page_1.json", 200, query="$offset=0") setup_mock(adapter, "GET", "bike_counts_page_2.json", 200, query="$offset=1000") response = client.get_all(DATASET_IDENTIFIER) assert inspect.isgenerator(response) data = list(response) assert len(data) == 1001 assert data[0]["date"] == "2016-09-21T15:45:00.000" assert data[-1]["date"] == "2016-10-02T01:45:00.000" client.close()
def setUpRequestsMocking(self, obj, contents=None, status_codes=None, headers=None, protocol='https'): """ """ if status_codes is None: status_codes = [200 for item in contents] if contents is None: contents = [None for item in status_codes] # This will work for headers in most cases. if headers is None: headers = [{'Content-Type': 'text/html'} for item in contents] adapter = requests_mock.Adapter() obj.session.mount(f'{protocol}://', adapter) z = zip(contents, status_codes, headers) response_list = [ { 'content': content, 'status_code': status_code, 'headers': headers, } for content, status_code, headers in z ] adapter.register_uri(requests_mock.ANY, requests_mock.ANY, response_list=response_list)
def test_post_records_details(self, requests_mock): def callback(request): response = requests.Response() response.status_code = 200 return {} url = 'https://fake_url' js = json.dumps({'foo': 'bar'}) adapter = req_mock.Adapter() session = requests.Session() session.mount('mock', adapter) adapter.add_matcher(callback) requests_mock.post(url, json=js) with HttpRequestsManager() as temp_dir: HttpRequests().post(url, json=js) file_path = temp_dir + '/request_001.txt' assert os.path.isfile(file_path) is True assert os.stat(file_path).st_size > 0 with open(file_path) as f: first_line = f.readline() parts = first_line.strip().split(' ') assert len(parts) == 2 assert parts[0] == 'POST' assert parts[1] == 'https://fake_url' rest_of_file = f.read() response_js = json.loads(rest_of_file) assert 'foo' in response_js assert response_js['foo'] == 'bar'
def setUp(self): """Setup function for each unit test.""" super(AdsUniversalAppCampaignHookTest, self).setUp() self.adapter = requests_mock.Adapter() self.session = requests.Session() self.session.mount('mock', self.adapter) base_hook.BaseHook.get_connection = mock.MagicMock(autospec=True) conn = mock.Mock(password='******') base_hook.BaseHook.get_connection.return_value = conn self.test_hook = ads_uac_hook.AdsUniversalAppCampaignHook('uac', True) self.test_hook.base_url = 'mock://www.googleadservices.com' self.test_hook.get_conn = mock.MagicMock(autospec=True) self.test_hook.get_conn.return_value = self.session self.sample_data = dict( link_id='TESTLINKIDTESTLINKID', app_event_type='in_app_purchase', rdid='843c45cc-e237-4f50-b6aa-843c45cc63d6', id_type='advertisingid', lat=0, app_version='1.2.4', os_version='5.0.0', sdk_version='1.9.5r6', timestamp=time.time(), ) self.sample_url = _URL_TEMPLATE.format( dev_token=self.test_hook._get_developer_token(), **self.sample_data)
def setUp(self): from certbot_dns_shellrent.dns_shellrent import _ShellrentClient self.adapter = requests_mock.Adapter() self.client = _ShellrentClient(FAKE_ENDPOINT, FAKE_USER, FAKE_TOKEN) self.client.session.mount("mock", self.adapter)