From f4c1c6b118a605444834d3449695cc19833968f0 Mon Sep 17 00:00:00 2001 From: Leo Antunes Date: Tue, 30 May 2017 16:47:16 +0200 Subject: [PATCH] fix several flake8 issues; replace print with logging modules shouldn't expect to have usable stdout ;) --- glpi/glpi.py | 38 +++---- setup.cfg | 3 + tests/test_glpi_module.py | 213 ++++++++++++++++++++------------------ 3 files changed, 125 insertions(+), 129 deletions(-) diff --git a/glpi/glpi.py b/glpi/glpi.py index e543b11..cfe5e73 100644 --- a/glpi/glpi.py +++ b/glpi/glpi.py @@ -15,13 +15,17 @@ # GLPI API Rest documentation: # https://github.com/glpi-project/glpi/blob/9.1/bugfixes/apirest.md +from __future__ import print_function +import os import json as json_import +import logging import requests from requests.structures import CaseInsensitiveDict -import os from version import __version__ +logger = logging.getLogger(__name__) + def load_from_vcap_services(service_name): vcap_services = os.getenv("VCAP_SERVICES") @@ -168,7 +172,7 @@ def set_session_token(self): self.session = r.json()['session_token'] return True except Exception as e: - raise Exception("Unable to init session in GLPI server: %s" % e) + raise GlpiException("Unable to init session in GLPI server: %s" % e) return False @@ -215,7 +219,7 @@ def request(self, method, url, accept_json=False, headers={}, self.set_session_token() headers.update({'Session-Token': self.session}) except Exception as e: - raise Exception("Unable to get Session token. ERROR: %s" % e) + raise GlpiException("Unable to get Session token. ERROR: %s" % e) if self.app_token is not None: headers.update({'App-Token': self.app_token}) @@ -234,6 +238,7 @@ def request(self, method, url, accept_json=False, headers={}, headers=headers, params=params, data=data, **kwargs) except Exception: + logger.error("ERROR requesting uri(%s) payload(%s)" % (url, data)) raise return response @@ -266,12 +271,7 @@ def create(self, data_json=None): payload = '{"input": { %s }}' % (self.get_payload(data_json)) - try: - response = self.request('POST', self.uri, data=payload, - accept_json=True) - except Exception as e: - print "#>> ERROR requesting uri(%s) payload(%s)" % (uri, payload) - raise + response = self.request('POST', self.uri, data=payload, accept_json=True) return response.json() @@ -327,14 +327,7 @@ def update(self, data): payload = '{"input": { %s }}' % (self.get_payload(data)) new_url = "%s/%d" % (self.uri, data['id']) - try: - response = self.request('PUT', self.uri, data=payload) - except Exception as e: - print { - "message_error": "ERROR requesting uri(%s) payload(%s)" % ( - uri, payload) - } - raise + response = self.request('PUT', new_url, data=payload) return response.json() @@ -350,14 +343,7 @@ def delete(self, item_id, force_purge=False): else: payload = '{"input": { "id": %d }}' % (item_id) - try: - response = self.request('DELETE', self.uri, data=payload) - except Exception as e: - print { - "message_error": "ERROR requesting uri(%s) payload(%s)" % ( - uri, payload) - } - raise + response = self.request('DELETE', self.uri, data=payload) return response.json() @@ -442,7 +428,7 @@ def init_item(self, item_name): try: self.init_api() except: - print "message_error: Unable to InitSession in GLPI Server." + logger.error("Unable to InitSession in GLPI Server.") return False if update_api: diff --git a/setup.cfg b/setup.cfg index b88034e..e91ee50 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,2 +1,5 @@ [metadata] description-file = README.md + +[flake8] +max-line-length = 120 diff --git a/tests/test_glpi_module.py b/tests/test_glpi_module.py index 55e8fce..a7cfa36 100644 --- a/tests/test_glpi_module.py +++ b/tests/test_glpi_module.py @@ -1,5 +1,7 @@ # This is a big script to test some SDK items. +from __future__ import print_function + import json import time import sys @@ -22,89 +24,91 @@ def load_from_vcap_services(service_name): else: return None + def test_profile(): glpi_pfl = GlpiProfile(url, - glpi_app_token, username=username, - password=password) + glpi_app_token, username=username, + password=password) - - print "Getting profile " - print json.dumps(glpi_pfl.get_my_profiles(), - indent=4, separators=(',', ': ')) + print("Getting profile ") + print(json.dumps(glpi_pfl.get_my_profiles(), + indent=4, separators=(',', ': '))) token_session = glpi_pfl.get_session_token() - print "Current session is: %s" % token_session + print("Current session is: %s" % token_session) + def test_ticket(): glpi_ticket = GlpiTicket(url, glpi_app_token, username=username, password=password) - print "##> Update Ticket object to session: %s" %\ - glpi_ticket.update_session_token(token_session) + print("##> Update Ticket object to session: %s" % + glpi_ticket.update_session_token(token_session)) tickets_all = glpi_ticket.get_all() - print "Retrieving all tickets: %s" % json.dumps(tickets_all, - indent=4, - separators=(',', ': '), - sort_keys=True) + print("Retrieving all tickets: %s" % json.dumps(tickets_all, + indent=4, + separators=(',', ': '), + sort_keys=True)) ticket = Ticket(name="New ticket from SDK %s" % t, content=" Content of ticket created by SDK API %s" % t) ticket_dict = glpi_ticket.create(ticket.get_data()) - print "Created the ticket: %s" % ticket_dict + print("Created the ticket: %s" % ticket_dict) - print "Getting ticket recently created with id %d ..." % ticket_dict['id'] + print("Getting ticket recently created with id %d ..." % ticket_dict['id']) ticket_get = glpi_ticket.get(ticket_dict['id']) - print "Got this ticket: %s" % json.dumps(ticket_get, - indent=4, - separators=(',', ': '), - sort_keys=True) + print("Got this ticket: %s" % json.dumps(ticket_get, + indent=4, + separators=(',', ': '), + sort_keys=True)) + def test_kb(): kb_item = GlpiKnowBase(url, glpi_app_token, - username=username, - password=password) + username=username, + password=password) res = kb_item.get_all() - print "Retrieving all KBs: %s" % json.dumps(res, - indent=4, - separators=(',', ': '), - sort_keys=True) + print("Retrieving all KBs: %s" % json.dumps(res, + indent=4, + separators=(',', ': '), + sort_keys=True)) res = kb_item.get(1) - print "Retrieve KB ID: %s" % json.dumps(res, - indent=4, - separators=(',', ': '), - sort_keys=True) + print("Retrieve KB ID: %s" % json.dumps(res, + indent=4, + separators=(',', ': '), + sort_keys=True)) kb = KnowBase() - print "Print default KB: %s" % kb.get_attribute('id') + print("Print default KB: %s" % kb.get_attribute('id')) if res is not None: kb.set_attributes(res) - print "Print default KB: %s" % kb.get_attribute('id') - print "Retrieving all KBs: %s" % json.dumps(kb.get_stream(), - indent=4, - separators=(',', ': '), - sort_keys=True) + print("Print default KB: %s" % kb.get_attribute('id')) + print("Retrieving all KBs: %s" % json.dumps(kb.get_stream(), + indent=4, + separators=(',', ': '), + sort_keys=True)) - print "SDK Version: %s" % kb_item.get_version() - print "SDK Version: %s" % kb_item.__version__ + print("SDK Version: %s" % kb_item.get_version()) + print("SDK Version: %s" % kb_item.__version__) - print "KB Creating new one..." + print("KB Creating new one...") name = "New KB Title %s" % t subject = "New KB Body %s" % t kb2 = KnowBase() kb2.set_attribute('name', name) kb2.set_attribute('answer', subject) res = kb2.get_attributes() - print "Retrieving KB obj: %s" % json.dumps(res, - indent=4, - separators=(',', ': '), - sort_keys=True) + print("Retrieving KB obj: %s" % json.dumps(res, + indent=4, + separators=(',', ': '), + sort_keys=True)) kb_dict = kb_item.create(kb2.get_data()) - print "Creating: %s " % kb_dict + print("Creating: %s " % kb_dict) def test_general(): @@ -112,16 +116,16 @@ def test_general(): # Basic usage glpi = GLPI(url, glpi_app_token, (username, password)) - print "#> Getting help()" - print glpi.help_item() + print("#> Getting help()") + print(glpi.help_item()) - print "#> Getting standard items: ticket" - print json.dumps(glpi.get_all('ticket'), - indent=4, - separators=(',', ': '), - sort_keys=True) + print("#> Getting standard items: ticket") + print(json.dumps(glpi.get_all('ticket'), + indent=4, + separators=(',', ': '), + sort_keys=True)) - print "#> Setting up new items..." + print("#> Setting up new items...") new_map = { "ticket": "/Ticket", "knowbase": "/knowbaseitem", @@ -132,34 +136,34 @@ def test_general(): "network": "/networkequipment", } glpi.set_item_map(new_map) - print "#> Getting new item: COMPUTER" - print json.dumps(glpi.get_all('computer'), - indent=4, - separators=(',', ': '), - sort_keys=True) + print("#> Getting new item: COMPUTER") + print(json.dumps(glpi.get_all('computer'), + indent=4, + separators=(',', ': '), + sort_keys=True)) # Setting up new map - print "#####> Creating new MAP..." + print("#####> Creating new MAP...") new_map = { "knowbase": "/knowbaseitem" } glpi2 = GLPI(url, glpi_app_token, (username, password), item_map=new_map) - print "#> Getting item: KB" - print json.dumps(glpi2.get_all('knowbase'), - indent=4, - separators=(',', ': '), - sort_keys=True) + print("#> Getting item: KB") + print(json.dumps(glpi2.get_all('knowbase'), + indent=4, + separators=(',', ': '), + sort_keys=True)) - print "#> Getting item KB by ID 1" + print("#> Getting item KB by ID 1") kb_dict = glpi2.get('knowbase', 1) - print json.dumps(kb_dict, - indent=4, - separators=(',', ': '), - sort_keys=True) - print kb_dict - print "#> Creating new KB copying from previous..." + print(json.dumps(kb_dict, + indent=4, + separators=(',', ': '), + sort_keys=True)) + print(kb_dict) + print("#> Creating new KB copying from previous...") kb_data = { "name": "New KB copyied from ID %s at %s" % ( kb_dict['id'], t), @@ -169,59 +173,61 @@ def test_general(): "users_id": kb_dict['users_id'], "view": kb_dict['view'] } - print "Creating object data: %s" % repr(kb_data) + print("Creating object data: %s" % repr(kb_data)) kb_res = glpi2.create('knowbase', kb_data) - print json.dumps(kb_res, + print(json.dumps(kb_res, indent=4, separators=(',', ': '), - sort_keys=True) + sort_keys=True)) def test_general_search(): glpi = GLPI(url, glpi_app_token, (username, password)) - print "#> Getting help()" - print glpi.help_item() + print("#> Getting help()") + print(glpi.help_item()) - print glpi.init_item('listSearchOptions') + print(glpi.init_item('listSearchOptions')) token_session = glpi.api_session - print ">>>> Current session is: %s" % token_session + print(">>>> Current session is: %s" % token_session) - print "#> Getting search options" - print json.dumps(glpi.search_options('knowbaseitem'), - indent=4, - separators=(',', ': '), - sort_keys=True) + print("#> Getting search options") + print(json.dumps(glpi.search_options('knowbaseitem'), + indent=4, + separators=(',', ': '), + sort_keys=True)) def test_search(): glpi = GLPI(url, glpi_app_token, (username, password)) - criteria = {"criteria": [{"field": "name", "value":"portal"}]} - print "#> Searching an str(valud) in KBs" - print json.dumps(glpi.search('knowbase', criteria), - indent=4, - separators=(',', ': '), - sort_keys=True) + criteria = {"criteria": [{"field": "name", "value": "portal"}]} + print("#> Searching an str(valud) in KBs") + print(json.dumps(glpi.search('knowbase', criteria), + indent=4, + separators=(',', ': '), + sort_keys=True)) + def test_update(): glpi = GLPI(url, glpi_app_token, (username, password)) item_data = {"id": 60, "name": "[test] Updating an ticket 2"} - print "#> Updating item 'ticket' with %s" % str(item_data) - print json.dumps(glpi.update('ticket', item_data), - indent=4, - separators=(',', ': '), - sort_keys=True) + print("#> Updating item 'ticket' with %s" % str(item_data)) + print(json.dumps(glpi.update('ticket', item_data), + indent=4, + separators=(',', ': '), + sort_keys=True)) + def test_delete(): glpi = GLPI(url, glpi_app_token, (username, password)) item_id = 63 - print "#> Deleting item 'ticket' with ID %d" % item_id - print json.dumps(glpi.delete('ticket', item_id), - indent=4, - separators=(',', ': '), - sort_keys=True) + print("#> Deleting item 'ticket' with ID %d" % item_id) + print(json.dumps(glpi.delete('ticket', item_id), + indent=4, + separators=(',', ': '), + sort_keys=True)) if __name__ == '__main__': @@ -230,25 +236,26 @@ def test_delete(): url = username = password = glpi_app_token = token_session = "" if vcap_service_credentials is not None and isinstance( - vcap_service_credentials, dict): + vcap_service_credentials, dict): url = vcap_service_credentials['url'] username = vcap_service_credentials['username'] password = vcap_service_credentials['password'] glpi_app_token = vcap_service_credentials['app_token'] else: - print("Unable to load .env file. Please create using tests/.env.sample") + print("Unable to load .env file." + "Please create using tests/.env.sample") sys.exit(1) - print repr(vcap_service_credentials) + print(repr(vcap_service_credentials)) t = time.strftime("%Y/%m/%d-%H:%M:%S") # test_profile() # test_ticket() - #test_kb() + # test_kb() # test_general() - #test_general_search() - #test_search() + # test_general_search() + # test_search() # [C]REATE # test_create()