diff --git a/.travis.yml b/.travis.yml index 510e0ae..ac7a4ac 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: python python: - "2.7" + - "3.5" # command to install dependencies install: - python setup.py install diff --git a/iotqatools/cb_ngsiv2_utils.py b/iotqatools/cb_ngsiv2_utils.py index ec52cf5..cea1b11 100644 --- a/iotqatools/cb_ngsiv2_utils.py +++ b/iotqatools/cb_ngsiv2_utils.py @@ -264,7 +264,7 @@ def __send_request(self, method, url, headers=None, payload=None, verify=None, q # Send the requests try: response = requests.request(**parameters) - except RequestException, e: + except RequestException as e: PqaTools.log_requestAndResponse(url=url, headers=headers, params=query, data=payload, comp='CB', method=method) assert False, 'ERROR: [NETWORK ERROR] {}'.format(e) diff --git a/iotqatools/cb_utils.py b/iotqatools/cb_utils.py index b5d3aae..4322317 100644 --- a/iotqatools/cb_utils.py +++ b/iotqatools/cb_utils.py @@ -34,6 +34,12 @@ from requests.exceptions import RequestException from iotqatools.iot_tools import PqaTools +try: + unicode() +except NameError: + unicode = str + str = bytes + # Utilities def check_valid_json(payload): @@ -965,7 +971,7 @@ def __send_request(self, method, url, headers=None, payload=None, verify=None, q # Send the requests try: response = requests.request(**parameters) - except RequestException, e: + except RequestException as e: PqaTools.log_requestAndResponse(url=url, headers=headers, data=payload, comp='CB', method=method) assert False, 'ERROR: [NETWORK ERROR] {}'.format(e) @@ -1718,10 +1724,10 @@ def __send_request(self, method, url, headers=None, payload=None, verify=None, q # Send the requests try: response = requests.request(**parameters) - except RequestException, e: + except RequestException as e: PqaTools.log_requestAndResponse(url=url, headers=headers, data=payload, comp='CB', method=method) assert False, 'ERROR: [NETWORK ERROR] {}'.format(e) - print response + print(response) # Log data PqaTools.log_fullRequest(comp='CB', response=response, params=parameters) @@ -2168,7 +2174,7 @@ def __send_request(self, method, url, headers=None, payload=None, verify=None, q # Send the requests try: response = requests.request(**parameters) - except RequestException, e: + except RequestException as e: PqaTools.log_requestAndResponse(url=url, headers=headers, data=payload, comp='CB', method=method) assert False, 'ERROR: [NETWORK ERROR] {}'.format(e) @@ -2238,6 +2244,17 @@ def entities_get(self, service, entity, entity_id, pattern='false', subservice=' response = self.__send_request('post', url, headers, json.loads(payload)) return response + @staticmethod + def __replace_quotes(text): + # format avoid urlencoding due to not array inputs + return ( + text + .replace("'", '"') + .replace("u"", '"') + .replace(""", '"') + .replace("'", '"') + .replace(""", '"')) + def entity_append(self, service, entity_data, subservice=''): """ Create if not exist a CB entity or update it @@ -2265,10 +2282,7 @@ def entity_append(self, service, entity_data, subservice=''): 'ent_attributes': entity_data['attributes'], 'action_mode': 'APPEND'}) - # format avoid urlencoding due to not array inputs - payload = payload.replace("'", '"') - payload = payload.replace("u"", '"') - payload = payload.replace(""", '"') + payload = self.__replace_quotes(payload) # send the request for the subscription response = self.__send_request('post', url, headers, json.loads(payload)) @@ -2301,10 +2315,7 @@ def entity_update(self, service, entity_data, subservice=''): 'ent_attributes': entity_data['attributes'], 'action_mode': 'APPEND'}) - # format avoid urlencoding due to not array inputs - payload = payload.replace("'", '"') - payload = payload.replace("u"", '"') - payload = payload.replace(""", '"') + payload = self.__replace_quotes(payload) # send the request for the subscription response = self.__send_request('post', url, headers, json.loads(payload)) @@ -2323,7 +2334,7 @@ def subscription_add(self, service, template_data={}, verifySSL=False, subservic """ # show info received if self.verbosity >= 2: - print "###> INPUT > {}".format(template_data) + print("###> INPUT > {}".format(template_data)) # set the service header id headers = dict(self.default_headers) @@ -2365,7 +2376,7 @@ def subscription_add(self, service, template_data={}, verifySSL=False, subservic 'subs_type': template_data['subs_type'], 'ent_att_notif': template_data['ent_att_notif'], 'ent_att_cond': template_data['ent_att_cond']}) - payload = payload.replace("'", '"') + payload = self.__replace_quotes(payload) # send the request for the subscription return self.__send_request('post', url, headers, json.loads(payload), verifySSL) @@ -2405,8 +2416,8 @@ def set_auth_token(self, auth_token): ce = ContextElements() ce.add_context_element('Room1', 'Room', attr) payload = PayloadUtils.build_standard_entity_creation_payload(ce) - print payload + print(payload) resp = cb.standard_entity_creation(payload) - print resp - print resp.text - print resp.headers + print(resp) + print(resp.text) + print(resp.headers) diff --git a/iotqatools/cb_v2_utils.py b/iotqatools/cb_v2_utils.py index 58e298f..05fb2b4 100644 --- a/iotqatools/cb_v2_utils.py +++ b/iotqatools/cb_v2_utils.py @@ -343,7 +343,7 @@ def harakiri(self): url = "%s/%s" % (self.cb_url, "exit/harakiri") resp = requests.get(url=url) return resp.status_code - except Exception, e: + except Exception as e: return -1 def is_cb_started(self): @@ -355,7 +355,7 @@ def is_cb_started(self): resp = requests.get(url=url) __logger__.debug("CB code returned with version request is: %s " % str(resp.status_code)) return resp.status_code == 200 - except Exception, e: + except Exception as e: return False def __update_headers(self): @@ -521,7 +521,7 @@ def __send_request(self, method, path, **kwargs): url = "%s/%s" % (self.cb_url, path) try: resp = requests.request(method=method, url=url, headers=headers, data=payload, params=parameters, verify=False) - except Exception, e: + except Exception as e: assert False, "ERROR - send request \n - url: %s\n - %s" % (url, str(e)) if show: self.response_string = "http code: %s - %s" % (resp.status_code, resp.reason) diff --git a/iotqatools/cep_utils.py b/iotqatools/cep_utils.py index 3812ed2..ad7c17c 100644 --- a/iotqatools/cep_utils.py +++ b/iotqatools/cep_utils.py @@ -222,8 +222,8 @@ def create_visual_rule(self, rule_name, service, sensor_card_list, action_card_l cep_payload = cep_payload.replace("'", '"') url = self.default_endpoint + self.path - print url - print json.dumps(yaml.load(cep_payload)) + print(url) + print(json.dumps(yaml.load(cep_payload))) response = requests.post(url, data=json.dumps(yaml.load(cep_payload)), headers=headers, verify=False) assert response.status_code == 201, 'ERROR {}, the rule {} cannot be created. {}'.format(response.status_code, rule_name, diff --git a/iotqatools/ckan_utils.py b/iotqatools/ckan_utils.py index 9bc7822..4cb140e 100644 --- a/iotqatools/ckan_utils.py +++ b/iotqatools/ckan_utils.py @@ -106,7 +106,7 @@ def __send_request(self, method, url, headers=None, payload=None, verify=None, q # Send the requests try: response = requests.request(**parameters) - except RequestException, e: + except RequestException as e: PqaTools.log_requestAndResponse(url=url, headers=headers, data=payload, comp='CKAN') assert False, 'ERROR: [NETWORK ERROR] {}'.format(e) @@ -291,7 +291,7 @@ def get_resource_id(self, resource_name, package_name, verify_ssl=False): if resources['name'] == resource_name: resource_id = resources['id'] return resource_id - except Exception, e: + except Exception as e: raise Exception("\n-- ERROR -- get_resource_id \n{}".format(e)) def delete_resource(self, resource_name, package_name, verify_ssl=False): diff --git a/iotqatools/fabric_utils.py b/iotqatools/fabric_utils.py index a4a9ed1..e3b6649 100644 --- a/iotqatools/fabric_utils.py +++ b/iotqatools/fabric_utils.py @@ -132,7 +132,7 @@ def run(self, command, **kwargs): return self.__sub_run(command, path, sudo_run) else: return self.__sub_run(command, path, sudo_run) - except Exception, e: + except Exception as e: assert False, "ERROR - running the command \"%s\" remotely with Fabric \n - %s" % (command, str(e)) def runs(self, ops_list, **kwargs): @@ -184,7 +184,7 @@ def __sub_read_file(self, file, sudo_run): fd = StringIO() get(file, fd, use_sudo=sudo_run) return fd.getvalue() - except Exception, e: + except Exception as e: __logger__.error("ERROR - reading %s file\n %s" % (file, e)) @@ -205,5 +205,5 @@ def read_file(self, file, **kwargs): return self.__sub_read_file(file, sudo_run) else: return self.__sub_read_file(file, sudo_run) - except Exception, e: + except Exception as e: assert False, "ERROR -reading a File \"%s\" remotely with Fabric \n - %s" % (file, str(e)) diff --git a/iotqatools/helpers_utils.py b/iotqatools/helpers_utils.py index f5d55e1..54f9fa6 100644 --- a/iotqatools/helpers_utils.py +++ b/iotqatools/helpers_utils.py @@ -88,7 +88,7 @@ def convert_str_to_dict(body, content): return xmltodict.parse(body) else: return json.loads(body) - except Exception, e: + except Exception as e: assert False, " ERROR - converting string to %s dictionary: \n" \ " %s \n " \ " Exception error: %s" % (str(content), str(body), str(e)) @@ -106,7 +106,7 @@ def convert_dict_to_str(body, content): return xmltodict.unparse(body) else: return str(json.dumps(body, ensure_ascii=False).encode('utf-8')) - except Exception, e: + except Exception as e: assert False, " ERROR - converting %s dictionary to string: \n" \ " %s \n" \ " Exception error: %s" % (str(content), str(body), str(e)) @@ -121,7 +121,7 @@ def convert_str_to_list(text, separator): """ try: return text.split(separator) - except Exception, e: + except Exception as e: assert False, " ERROR - converting %s string to list with separator: %s \n" \ " Exception error:%s" % (str(text), str(separator), str(e)) @@ -135,7 +135,7 @@ def convert_list_to_string(list, separator): """ try: return separator.join(list) - except Exception, e: + except Exception as e: assert False, " ERROR - converting list to string with separator: %s \n" \ " Exception error:%s" % (str(separator), str(e)) @@ -145,10 +145,10 @@ def show_times(init_value): shows the time duration of the entire test :param init_value: initial time """ - print "**************************************************************" - print "Initial (date & time): " + str(init_value) - print "Final (date & time): " + str(time.strftime("%c")) - print "**************************************************************" + print("**************************************************************") + print("Initial (date & time): " + str(init_value)) + print("Final (date & time): " + str(time.strftime("%c"))) + print("**************************************************************") def generate_timestamp(**kwargs): @@ -210,7 +210,7 @@ def is_an_integer_value(value): if dec_v == 0: return True return False - except Exception, e: + except Exception as e: assert False, " Error - %s is not numeric... \n %s" % (str(value), str(e)) @@ -262,7 +262,7 @@ def read_file_to_json(file_name): try: with open(file_name) as config_file: return json.load(config_file) - except Exception, e: + except Exception as e: raise Exception("\n ERROR - parsing the %s/%s file \n msg= %s" % (path, file_name, str(e))) @@ -300,7 +300,7 @@ def eval_binary_expr(op1, operator, op2): if operator not in ['==', '!=']: try: op1, op2 = int(float(op1)), int(float(op2)) - except Exception, e: + except Exception as e: __logger__.warn("Some value is not a numeric format. (%s)" % str(e)) return False return get_operator_fn(operator)(op1, op2) @@ -336,7 +336,7 @@ def list_swap(l, init_pos, end_pos): """ try: l[int(init_pos)], l[int(end_pos)] = l[int(end_pos)], l[int(init_pos)] - except Exception, e: + except Exception as e: raise "ERROR - trying to swap items in a list: \n - %s" % e return l @@ -377,4 +377,4 @@ class LogLevelConfiguration: In addition, not sure if this file is the best place for this class or it should be put in its own .py """ - default_log_level = 'DEBUG' \ No newline at end of file + default_log_level = 'DEBUG' diff --git a/iotqatools/iota_measures.py b/iotqatools/iota_measures.py index 0e37382..7799e59 100644 --- a/iotqatools/iota_measures.py +++ b/iotqatools/iota_measures.py @@ -103,7 +103,7 @@ def sendMeasure(self, measure_type, apikey, idDevice, measures, field={}): url += '&ip=' url += field["ip"] - print 'url: ' + url + print('url: ' + url) data = self.getMeasure(measure_type, measures, field) res = requests.post(url,headers = {'content-type': 'text/plain'},data=data) @@ -126,7 +126,7 @@ def sendMeasure(self, measure_type, apikey, idDevice, measures, field={}): def getMeasure(self, protocol, measures, field={}): result = "" - print measures + print(measures) for measure in measures: # Format type UL or UL2 if protocol == "UL": @@ -150,7 +150,7 @@ def getMeasure(self, protocol, measures, field={}): result = str(measure) if "UL" in protocol: result = result.rpartition("#")[0] # delete the last "#" - print result + print(result) # Replace specials words and characters replaces = { "True": "1", @@ -169,7 +169,7 @@ def getMeasure(self, protocol, measures, field={}): def sendRegister(self, apikey, device, asset, model, phenomena): url = self.getUrl('RegLight', apikey, device) - print 'url: ' + url + print('url: ' + url) uom_id = 1 result = "" result += "" + device + "" @@ -177,7 +177,7 @@ def sendRegister(self, apikey, device, asset, model, phenomena): result += "" result += "" + model + "" result += "" - print phenomena + print(phenomena) for phenom in phenomena: result += "" for phenom in phenomena: @@ -190,7 +190,7 @@ def sendRegister(self, apikey, device, asset, model, phenomena): uom_id += 1 result += "" result += "" - print result + print(result) res = requests.post(url, data=result) #log request @@ -210,7 +210,7 @@ def getCommand(self, measure_type, apikey, idDevice, ip={}): url = self.getUrl(measure_type, apikey, idDevice) if ip: url += "&ip=" + ip - print 'url: ' + url + print('url: ' + url) res = requests.get(url) #log request @@ -227,7 +227,7 @@ def getCommand(self, measure_type, apikey, idDevice, ip={}): def SendCmdResponse(self, measure_type, apikey, idDevice, command, response): url = self.getUrl(measure_type, apikey, idDevice, command) - print 'url: ' + url + print('url: ' + url) data = str(command) + "|" + str(response) res = requests.post(url, data=data) diff --git a/iotqatools/iota_utils.py b/iotqatools/iota_utils.py index afd1bb6..1ac5010 100644 --- a/iotqatools/iota_utils.py +++ b/iotqatools/iota_utils.py @@ -505,7 +505,7 @@ def update_service_with_params(self, json, service_name, service_path={}, resour headers[self.srv_path_header] = '/' else: headers[self.srv_path_header] = '/' - print params + print(params) req = self.put_service('', json, headers, params) return req diff --git a/iotqatools/ks_utils.py b/iotqatools/ks_utils.py index 15ac83c..6a6d95b 100644 --- a/iotqatools/ks_utils.py +++ b/iotqatools/ks_utils.py @@ -979,8 +979,8 @@ def check_platform_config(platform): else: return True except Exception as e: - print "This is an example of platform config attribute" - print """ + print("This is an example of platform config attribute") + print(""") platform = { 'GlobalServiceAdmin': { 'user': 'admin', @@ -1011,7 +1011,7 @@ def check_platform_config(platform): } } """ - raise e + raise @staticmethod def check_environment_config(environment): diff --git a/iotqatools/mongo_utils.py b/iotqatools/mongo_utils.py index 77068e5..5ba5255 100644 --- a/iotqatools/mongo_utils.py +++ b/iotqatools/mongo_utils.py @@ -82,7 +82,7 @@ def connect(self, database=EMPTY): self.current_collection = self.current_database[self.collection_name] else: self.current_collection = self.current_database - except Exception, e: + except Exception as e: assert False, " ERROR - Connecting to MongoDB...\n %s " % (str(e)) def execute_command(self, command): @@ -93,7 +93,7 @@ def execute_command(self, command): """ try: return self.current_database.command(command) - except Exception, e: + except Exception as e: assert False, " ERROR - Executing command \"%s\" in MongoDB...\n %s " % (command, str(e)) def eval_version(self, version=EMPTY): @@ -124,7 +124,7 @@ def choice_database(self, name): try: self.current_database = self.client.get_database(name) self.current_collection = self.current_database - except Exception, e: + except Exception as e: assert False, " ERROR - Accessing to database %s in MongoDB...\n %s" % (name, str(e)) def choice_collection(self, name): @@ -135,7 +135,7 @@ def choice_collection(self, name): try: self.collection_name = name self.current_collection = self.current_database[name] - except Exception, e: + except Exception as e: assert False, " ERROR - Accessing to collection %s in MongoDB...\n %s" % (name, str(e)) def get_all_databases(self): @@ -146,7 +146,7 @@ def get_all_databases(self): try: dbs = self.client.database_names() return self.get_cursor_value(dbs) - except Exception, e: + except Exception as e: assert False, " ERROR - Get all databases in mongo...\n %s" % str(e) def get_all_collections_by_db(self, **kwargs): @@ -164,7 +164,7 @@ def get_all_collections_by_db(self, **kwargs): else: colls = self.client[db_name].collection_names(include_system_collections=system_collections) return self.get_cursor_value(colls) - except Exception, e: + except Exception as e: assert False, " ERROR - Get all colections in a databases in mongo...\n %s" % str(e) def insert_data(self, data): @@ -173,7 +173,7 @@ def insert_data(self, data): """ try: self.current_collection.insert(data) - except Exception, e: + except Exception as e: assert False, " ERROR - Inserting data into %s in MongoDB...\n %s" % (str(self.current_collection), str(e)) def update_data(self, data, query={}): @@ -182,7 +182,7 @@ def update_data(self, data, query={}): """ try: self.current_collection.update(query, data) - except Exception, e: + except Exception as e: assert False, " ERROR - Updating data in a collection %s in MongoDB...\n %s" % (self.current_collection, str(e)) def find_data(self, query={}): @@ -193,7 +193,7 @@ def find_data(self, query={}): """ try: return self.current_collection.find(query) - except Exception, e: + except Exception as e: assert False, " ERROR - Searching data from a collection %s in MongoDB...\n %s" % (self.current_collection, str(e)) def find_with_retry(self, query={}): @@ -209,7 +209,7 @@ def find_with_retry(self, query={}): if cursor.count() != 0: return cursor c += 1 - print " WARN - Retry in find documents in Mongo. No: (%s)" % str(c) + print(" WARN - Retry in find documents in Mongo. No: (%s)" % str(c)) time.sleep(self.retry_delay) return cursor @@ -230,7 +230,7 @@ def print_cursor(self, cursor): :param cursor: """ for doc in cursor: - print str(doc) + print(str(doc)) def drop_collection(self): """ @@ -238,7 +238,7 @@ def drop_collection(self): """ try: self.current_database.drop_collection(self.collection_name) - except Exception, e: + except Exception as e: assert False, " ERROR - Deleting a collection %s in MongoDB...\n %s" % (self.current_collection, str(e)) def drop_database(self, db_name=EMPTY): @@ -251,7 +251,7 @@ def drop_database(self, db_name=EMPTY): self.database_name = db_name __logger__.debug("database to delete: %s" % self.database_name) self.client.drop_database(self.database_name) - except Exception, e: + except Exception as e: assert False, " ERROR - Deleting a database %s in MongoDB...\n %s" % (self.current_collection, str(e)) def disconnect(self): @@ -260,6 +260,6 @@ def disconnect(self): """ try: self.client.close() - except Exception, e: + except Exception as e: assert False, " ERROR - Disconnecting to MongoDB...\n %s\n%s " % (self.current_collection, str(e)) diff --git a/iotqatools/mysql_utils.py b/iotqatools/mysql_utils.py index 25f30ca..6caf803 100644 --- a/iotqatools/mysql_utils.py +++ b/iotqatools/mysql_utils.py @@ -95,7 +95,7 @@ def __query(self, sql, error=False): cur = self.conn.cursor() cur.execute(sql) return cur - except Exception, e: + except Exception as e: return self.__error_assertion('DB exception: %s' % (e), error) def __drop_database(self): @@ -112,7 +112,7 @@ def connect(self): try: self.database = EMPTY self.conn = MySQLdb.connect(self.host, self.user, self.password, self.database, charset='utf8',use_unicode=True) - except Exception, e: + except Exception as e: return self.__error_assertion('DB exception: %s' % (e)) def set_database(self, database): @@ -135,7 +135,7 @@ def get_version(self): """ try: self.conn = MySQLdb.connect(self.host, self.user, self.password, self.database) - except Exception, e: + except Exception as e: return self.__error_assertion('DB exception: %s' % (e)) cur = self.__query(SELECT_VERSION) row = cur.fetchone() @@ -308,4 +308,4 @@ def get_table_records(self, database_name, table_name): if self.table_exist(database_name, table_name) != None: cur = self.__query('SELECT * FROM `%s`.`%s`;' % (database_name, table_name)) return cur.rowcount # return the number of records of the table - return False \ No newline at end of file + return False diff --git a/iotqatools/pep_utils.py b/iotqatools/pep_utils.py index 3b9c676..b895a1c 100644 --- a/iotqatools/pep_utils.py +++ b/iotqatools/pep_utils.py @@ -148,5 +148,5 @@ def request_cb_operation(self, username, password, service, subservice, cb_metho "ent_id": "Car01", "attributes": [{"name": "temperature", "type": "centigrade", "value": "99"}] } - print pep.request_cb_operation('octopus', 'octopus', 'atlantic', 'coral', 'entity_append', - {'service': 'atlantic', 'entity_data': entity_data}) + print(pep.request_cb_operation('octopus', 'octopus', 'atlantic', 'coral', 'entity_append', + {'service': 'atlantic', 'entity_data': entity_data})) diff --git a/iotqatools/remote_log_utils.py b/iotqatools/remote_log_utils.py index cfc1568..536014d 100644 --- a/iotqatools/remote_log_utils.py +++ b/iotqatools/remote_log_utils.py @@ -68,7 +68,7 @@ def __init__(self, **kwargs): self.file = temp[1] path = temp[0] self.fabric.current_directory(path) - except Exception, e: + except Exception as e: __logger__.error("ERROR - in log file... \n - %s" % str(e)) def delete_log_file(self): @@ -113,7 +113,7 @@ def find_line(self, label, text, msg_header="msg"): try: if line.find("lvl=%s" % label) >= 0: label_list.append(line) - except Exception, e: + except Exception as e: __logger__.debug("error message: %s" % e) __logger__.debug("log line: %s" % line) label_list.reverse() # list reverse because looking for the last occurrence diff --git a/iotqatools/sth_utils.py b/iotqatools/sth_utils.py index 16d4383..8007cfe 100644 --- a/iotqatools/sth_utils.py +++ b/iotqatools/sth_utils.py @@ -101,7 +101,7 @@ def __send_request(self, method, url, headers=None, payload=None, verify=None, q # Send the requests try: response = requests.request(**parameters) - except RequestException, e: + except RequestException as e: PqaTools.log_requestAndResponse(url=url, headers=headers, data=payload, comp='STH', method=method) assert False, 'ERROR: [NETWORK ERROR] {}'.format(e) diff --git a/iotqatools/tests/test_cb_utils.py b/iotqatools/tests/test_cb_utils.py index 7a15574..b5451b1 100644 --- a/iotqatools/tests/test_cb_utils.py +++ b/iotqatools/tests/test_cb_utils.py @@ -28,7 +28,10 @@ from nose.tools import eq_, ok_, assert_in from iotqatools.cb_utils import CBUtils import unittest -import mock +try: + from unittest import mock +except ImportError: # python2 + import mock last_updateContext ="" @@ -129,36 +132,36 @@ def setUp(self): @mock.patch('requests.request', side_effect=mocked_requests_get) def test_version(self, mock_requests): version = self.cb.version() - print "### Test ---> Version: " + version.content + print("### Test ---> Version: " + version.content) eq_(200, version.status_code, msg="version to CB does not return 200") assert_in("orion", version.content, msg="bad data returned to query version to CB") assert_in("version", version.content, msg="bad data returned to query version to CB") @mock.patch('requests.request', side_effect=mocked_requests_get) def test_statistics(self, mock_requests): - print "### Test ---> Statistics: " - print self.cb.statistics().content + print("### Test ---> Statistics: ") + print(self.cb.statistics().content) @mock.patch('requests.request', side_effect=mocked_requests_get) def test_create_entity(self, mock_requests): - print "### Test ---> Create a entity: " + print("### Test ---> Create a entity: ") data0 = {'ent_type': 'Sala', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '99'}]} self.cb.entity_append('x222', data0) - print "### Test ---> Recover the entity1 (method1): " + print("### Test ---> Recover the entity1 (method1): ") entity1 = self.cb.entity_get('x222', 'Sala01') eq_(200, entity1.status_code, msg="Error Code") - print "### Test ---> Recover the entity2 (method2):" + print("### Test ---> Recover the entity2 (method2):") entity2 = self.cb.entities_get('x222', 'Sala', 'Sala01', 'false') eq_(200, entity2.status_code, msg="Error Code") - print "### Test ---> Recover the entities wiht pattern (method3):" + print("### Test ---> Recover the entities wiht pattern (method3):") entity3 = self.cb.entities_get('x222', 'Sala', 'Sala.*', 'true') eq_(200, entity2.status_code, msg="Error Code") - print "### Test ---> Compare all the entities recovered: " + print("### Test ---> Compare all the entities recovered: ") jsobj_1 = json.loads(entity1.content) jsobj_2 = json.loads(entity2.content) jsobj_3 = json.loads(entity3.content) @@ -184,7 +187,7 @@ def test_create_entity(self, mock_requests): @mock.patch('requests.request', side_effect=mocked_requests_404) def test_missing_entities(self, mock_requests): - print "### Test ---> Recover missing entities: " + print("### Test ---> Recover missing entities: ") entityb1 = self.cb.entities_get('x222', 'Sala', 'S', 'false') eq_(200, entityb1.status_code, msg="Error Code") entityb2 = self.cb.entities_get('x222', 'Sal', 'Sala01', 'false') @@ -202,26 +205,26 @@ def test_missing_entities(self, mock_requests): @mock.patch('requests.request', side_effect=mocked_requests_get) def test_update_entity(self, mock_requests): - print "### Test ---> Update the entity: " + print("### Test ---> Update the entity: ") data0 = {'ent_type': 'Salass', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '99'}]} self.cb.entity_append('x222', data0) - print "### Test ---> Recover the entity1 (method1): " + print("### Test ---> Recover the entity1 (method1): ") entity1 = self.cb.entity_get('x222', 'Sala01') data1 = {'ent_type': 'Salass', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '101'}]} self.cb.entity_update('x222', data1) - print "### Test ---> Recover the updated entity: " + print("### Test ---> Recover the updated entity: ") entity2 = self.cb.entity_get('x222', 'Sala01') eq_(200, entity1.status_code, msg="Error Code") assert_in('101', entity2.content) @mock.patch('requests.request', side_effect=mocked_requests_get) def test_subscription(self, mock_requests): - print "### Test ---> Add Subscription: " + print("### Test ---> Add Subscription: ") data0 = {'ent_type': 'Salass', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '99'}]} self.cb.entity_append('x222', data0) @@ -234,9 +237,9 @@ def test_subscription(self, mock_requests): jssub = json.loads(sub.content) ok_(jssub['subscribeResponse']['subscriptionId'], msg="No subscription") eq_(jssub['subscribeResponse']['duration'], 'PT5M', msg="No Duration") - print "### Test ---> subscription added:" - print "Subscription id: {}".format(jssub['subscribeResponse']['subscriptionId']) - print "Subscription duration: {}".format(jssub['subscribeResponse']['duration']) + print("### Test ---> subscription added:") + print("Subscription id: {}".format(jssub['subscribeResponse']['subscriptionId'])) + print("Subscription duration: {}".format(jssub['subscribeResponse']['duration'])) if __name__ == '__main__': diff --git a/iotqatools/tests/test_iota_utils.py b/iotqatools/tests/test_iota_utils.py index ee5d574..fd8a520 100644 --- a/iotqatools/tests/test_iota_utils.py +++ b/iotqatools/tests/test_iota_utils.py @@ -29,7 +29,10 @@ from nose.tools import eq_, ok_, assert_in from iotqatools.iota_utils import Rest_Utils_IoTA import unittest -import mock +try: + from unittest import mock +except ImportError: # python2 + import mock last_updateContext ="" @@ -89,14 +92,14 @@ def setUp(self): def test_version(self, mock_requests): version="1.0.0" #version = self.iota.version() - print "### Test ---> Version: " + version + print("### Test ---> Version: " + version) #assert_in("Welcome to IoTAgents", version.content, msg="bad data returned to query version to IOTA") #assert_in("identifier:IoTPlatform:8080", version.content, msg="bad data returned to query version to CB") @mock.patch('requests.post', side_effect=mocked_requests_post) def tes_bad_create_service(self, mock_requests): res = self.iota.create_service(service_name="kk", protocol="bad" ) - print "### Test ---> Bade service name: " + res.content + print("### Test ---> Bade service name: " + res.content) eq_(400, res.status_code, msg="version to CB does not return 200") assert_in("a service string must not be longer than 50 characters and may only contain underscores and alphanumeric characters", res.content, msg="bad data returned to bad sewrvice name to IOTA")