def __init__(self): """Create a new Download class instance.""" self.temp_dir = tempfile.mkdtemp() logger.debug("__init__: temp_dir= " + self.temp_dir) self.session = requests.session() self.sso_rest_client = RestClient(self.session, self.garmin_sso_base_url) self.rest_client = RestClient(self.session, self.garmin_connect_modern_url) self.activity_service_rest_client = RestClient.inherit(self.rest_client, self.garmin_connect_activity_service) self.download_service_rest_client = RestClient.inherit(self.rest_client, self.garmin_connect_download_service) self.gc_gonfig = GarminConnectConfigManager() self.download_days_overlap = self.gc_gonfig.download_days_overlap()
def test_04_unknown_exception_get(self): ''' Tests the GET request with an unknown error ''' bad_rest_client = RestClient(RestClient(), 2, 3) success, response = \ bad_rest_client.get_request(self.test_sample_from_portion, self.test_sample_select_portion) # Test that the request contents came back as expected assert success == False assert response == "An unidentified error has occured: unsupported operand type(s) for +: 'RestClient' and 'int'."
def buckettest(oracle_file_path, rest_service_url): global client client = RestClient(rest_service_url) # static variables iterate_crash.print_after = BLOCK_SIZE iterate_crash.crashes_so_far = 0 iterate_crash.ingest_block = [] if START_GUNICORN: gunicorn_starter = GunicornStarter() try: if not BOOTSTRAP_RESUME_AT: reset_index() if TOTALLY_FAKE_DATA: synthesize(get_comparisons()) else: simulate(get_comparisons(), load_oracle_data(oracle_file_path)) except: traceback.print_exc() finally: print('Cleaing up...') if PARALLEL > 1: pool.terminate() pool.join() if START_GUNICORN: gunicorn_starter.stop_gunicorn()
def __init__(self, test, key, secret, symbol, side): self.test = test self.symbol = symbol self.client = RestClient(test, key, secret, symbol) self.side = side self.take_profit_order = None self.order_menu = []
def test_response_server_error(self): httpretty.register_uri('GET', self.TEST_BASE, status=500) from rest_client import RestClient, HTTPError with self.assertRaises(HTTPError): RestClient(self.TEST_BASE).call('GET', ())
def test_session_user_agent(self): from rest_client import RestClient user_agent = 'Poipoi/1.0' client = RestClient('http://host/base', user_agent=user_agent) self.assertIn('User-Agent', client.session.headers) self.assertIn(user_agent, client.session.headers['User-Agent'])
def test_timeout_no_auto_set_arg(self): with mock.patch('requests.Session.request') as mock_request: rest_client = RestClient('localhost', 8000) rest_client.session.request('GET', '/test', None, None, None, None, None, None, 40) mock_request.assert_called_with('GET', '/test', None, None, None, None, None, None, 40)
def main(): args = process_command_line() logging.basicConfig(level=int(args.verbose)) coap_logger = logging.getLogger('coap') coap_logger.setLevel(int(args.coap_log)) signal.signal(signal.SIGINT, signal_handler) hub_identity, authentication_key = get_hub_identity() rest_client = RestClient(hub_identity, authentication_key) if args.factory_reset: logging.info('Resetting device information') reset_tables(hub_identity, rest_client.hub_id) db = Database(rest_client) devices.rest_client = rest_client devices.db = db logging.info('Simulation: {0}'.format('on' if args.simulation else 'off')) _greenlets = [gevent.spawn(_notification_loop, rest_client.channel_id)] _greenlets = [] if args.simulation: devices.simulation_mode = True simulation.initialize(rest_client) _greenlets.append(gevent.spawn(simulation.simulation_loop)) else: _greenlets.append(gevent.spawn(tunslip.tunslip_loop)) logging.debug('Border router IP {0}'.format(get_br_ip_address())) _greenlets.append(gevent.spawn(devices.scan_loop, db, get_br_ip_address())) gevent.joinall(_greenlets) logging.info('Terminating uHub.')
def __init__(self, host='127.0.0.1', port=11211, timeout=30, admin_user="******", admin_pass="******", rest_port=8091, do_auth=True): self.host = host self.port = port self.timeout = timeout self._createConn() self.r = random.Random() self.vbucket_count = 1024 if do_auth: self.sasl_auth_plain(admin_user, admin_pass) # auth on any existing buckets rest_client = RestClient(host, port=rest_port) for bucket in rest_client.get_all_buckets(): try: self.bucket_select(bucket) except Exception as ex: # can be ignored...possibly warming up pass
def test_auth(self): from rest_client import RestClient auth = ('user_name', 'password') RestClient(self.TEST_BASE, auth=auth).call('GET', ()) req = httpretty.last_request() auth = base64.b64encode('user_name:password') self.assert_header(req, 'authorization', 'Basic %s' % auth)
def test_segment(self, path, segments): httpretty.register_uri('GET', 'http://host%s' % path, status=200) from rest_client import RestClient RestClient(self.TEST_BASE).call('GET', segments) req = httpretty.last_request() self.assertEqual(req.path, path)
def test_method(self, method): httpretty.register_uri(method, self.TEST_BASE, status=200) from rest_client import RestClient RestClient(self.TEST_BASE).call(method, ()) req = httpretty.last_request() self.assertEqual(req.method, method)
def __init__(self, test, key, secret, symbol, side): self.test = test self.symbol = symbol self.client = RestClient(test, key, secret, symbol) self.side = side self.take_profit_order = None self.limit_orders = [] self.last_entry_price = []
def testlogin(zuora_settings): client = RestClient(zuora_settings) response = client.login() if response: print('No exceptions thrown') print('Success: ', response['success']) else: print('Exceptions thrown. Login failed.')
def test_response_redirect(self): headers = {'Location': 'http://go-away.com'} httpretty.register_uri('GET', self.TEST_BASE, status=301, adding_headers=headers) from rest_client import RestClient with self.assertRaises(IOError): RestClient(self.TEST_BASE).call('GET', ())
def test_headers(self): from rest_client import RestClient RestClient(self.TEST_BASE).call('GET', ()) req = httpretty.last_request() self.assert_header(req, 'host', 'host') self.assert_header(req, 'connection', 'keep-alive') self.assert_header(req, 'accept', 'application/json') self.assert_header(req, 'accept-encoding', 'gzip, deflate')
def test_request(self): from rest_client import RestClient RestClient(self.TEST_BASE).call('GET', ()) req = httpretty.last_request() self.assertEqual(req.path, '/base') self.assertEqual(req.body, '') self.assertEqual(req.method, 'GET') self.assertEqual(req.request_version, 'HTTP/1.1')
def get_product_list(self, headers): rest_client = RestClient() products = rest_client.send_get( self.config["global"]["host"] + "/rest/" + self.config["global"]["store"] + "/V1/products?searchCriteria[filter_groups][0][filters][0][field]=sku&" "searchCriteria[filter_groups][0][filters][0][condition_type]=notnull", headers, None) return products
def test_response(self): from rest_client import RestClient response = RestClient(self.TEST_BASE).call('GET', ()) import requests self.assertIsInstance(response, requests.Response) self.assertEqual(response.text, self.TEST_BODY) self.assertEqual(response.status_code, 200) self.assertEqual(response.url, self.TEST_BASE)
def __init__(self, test, key, secret, symbol, side): self.test = test self.symbol = symbol self.client = RestClient(test, key, secret, symbol) self.take_profit_order = None self.stop_loss_order = None self.next_stop_order = None self.position = {} self.orders = [] self.side = side
def test_03_connection_error_get(self): ''' Tests the GET request with a connection error. ''' # Try making the request, but with a bad url bad_rest_client = RestClient("http://", "255.255.255.255", "22") success, response = \ self.test_rest_client.get_request(self.test_sample_from_portion, self.test_sample_select_portion) # Test that the request contents came back as expected assert success == False assert response == "A connection error has occured."
def gflag(endpoint, user, password, domain, body={}, action="get"): # Function to get and update the gflags from the clusters. # Returns response code and response. api = "clusters/gflag" rest_obj = RestClient(endpoint, user, password, domain) if action == "get": code, resp = rest_obj.get(api) else: code, resp = rest_obj.put(api, data=body) # If the response code is failed, returns empty list. Gflags APIs are # supported in cluster version >= 6.3. if code == 404: resp = json.dumps([]).encode("utf-8") return code, resp
def test_exception(self, m_errorlog): from rest_client import RestClient, RequestException client = RestClient(self.TEST_BASE) with mock.patch.object(client, 'session') as m_session: m_request = m_session.request m_request.side_effect = RequestException() with self.assertRaises(RequestException): client.call('GET', ()) m_errorlog.assert_called_once_with( 'failure', 'RequestException', 'GET', 'http://host/base', m_request.side_effect)
def test_redirect(self, m_errorlog): from rest_client import RestClient client = RestClient(self.TEST_BASE) with mock.patch.object(client, 'session') as m_session: m_response = m_session.request.return_value m_response.is_redirect = True m_response.status_code = 301 m_response.json.return_value = {'error': 'ERROR', 'message': 'MSG'} m_response.headers = {'location': 'LOCATION'} with self.assertRaises(IOError): client.call('GET', ()) m_errorlog.assert_called_once_with( 'redirect', 'redirect', 'GET', 'http://host/base', 'LOCATION', body=m_response.content, status=301)
def test_client_error(self, m_errorlog): from rest_client import RestClient, HTTPError client = RestClient(self.TEST_BASE) with mock.patch.object(client, 'session') as m_session: m_response = m_session.request.return_value m_response.is_redirect = False m_response.raise_for_status.side_effect = HTTPError() m_response.status_code = 400 m_response.json.return_value = {'error': 'ERROR', 'message': 'MSG'} with self.assertRaises(HTTPError): client.call('GET', ()) m_errorlog.assert_called_once_with( 'client', 'ERROR', 'GET', 'http://host/base', 'MSG', body=m_response.content, status=400)
def test_legacy(self): from rest_client import RestClient client = RestClient(self.TEST_BASE) client.requests_legacy = True # Force detection of requests 1.x with mock.patch.object(client, 'session') as m_session: m_response = m_session.request.return_value m_response.is_redirect = False m_response.status_code = 200 client.call('GET', [], json='[1, 2, 3]') m_session.request.assert_called_once_with( allow_redirects=False, data='"[1, 2, 3]"', headers={'Content-Type': 'application/json'}, method='GET', url='http://host/base')
def main(self): self.configure_logging() logging.getLogger("main.stdout").info( "Logging to file " + self.config["global"]["log_path"] + 'magento_updater.log') mode = "prod" if self.config["global"]["mode"] is not None: mode = self.config["global"]["mode"] rest_client = RestClient() token = self.authorize_user(rest_client) headers = { "Content-Type": "application/json", "Authorization": "Bearer " + token } if mode == "devel": self.add_dummy_products(rest_client, headers) logging.info("User has been successfully logged in.") read_item_list = self.prepare_different_items_list( rest_client, headers) self.update_magento_products(rest_client, headers, read_item_list) logging.info("Job done, exiting. Goodbye.")
def test_options(self): from rest_client import RestClient options = {'Key': 'Value'} client = RestClient('http://host/base', options=options) self.assertEqual(client.default_options, {'allow_redirects': False, 'Key': 'Value'})
def test_session_auth(self): from rest_client import RestClient auth = ('U', 'P') client = RestClient('http://host/base', auth=auth) self.assertEqual(client.session.auth, auth)
def test_session_simple(self): from rest_client import RestClient import requests client = RestClient('http://host/base') self.assertIsInstance(client.session, requests.Session) self.assertEqual(client.default_options, {'allow_redirects': False})