Skip to content
Snippets Groups Projects
Commit 465ffb8d authored by Robert Habermann's avatar Robert Habermann
Browse files

refactor dummy methods to privates

parent 54691f94
No related branches found
No related tags found
No related merge requests found
......@@ -115,7 +115,7 @@ class Article(object):
return "<{0}>".format(self.__class__.__name__)
@classmethod
def dummy(cls):
def _dummy(cls):
"""dummy data (for testing)
Returns:
......@@ -128,7 +128,7 @@ class Article(object):
"Charset": "UTF8"})
@classmethod
def dummy_force_notify(cls):
def _dummy_force_notify(cls):
"""dummy data (for testing)
Returns:
......@@ -188,7 +188,7 @@ class Attachment(object):
return self.__dict__
@classmethod
def dummy(cls):
def _dummy(cls):
"""dummy data (for testing)
Returns:
......@@ -198,8 +198,12 @@ class Attachment(object):
class DynamicField(object):
"""PyOTRS DynamicField class """
"""PyOTRS DynamicField class
.. warning::
DynamicField representation changed between OTRS 4 and OTRS 5.
**PyOTRS only supports OTRS 5 style!**
"""
def __init__(self, name=None, value=None, dct=None):
if dct:
if name or value:
......@@ -226,7 +230,7 @@ class DynamicField(object):
return {"Name": self.name, "Value": self.value}
@classmethod
def dummy1(cls):
def _dummy1(cls):
"""dummy1 data (for testing)
Returns: DynamicField
......@@ -234,7 +238,7 @@ class DynamicField(object):
return DynamicField(name="firstname", value="Jane")
@classmethod
def dummy2(cls):
def _dummy2(cls):
"""dummy2 data (for testing)
Returns:
......@@ -334,7 +338,7 @@ class Ticket(object):
return {"Ticket": self.__dict__}
@classmethod
def dummy(cls):
def _dummy(cls):
"""dummy data (for testing)
Returns:
......@@ -641,12 +645,15 @@ class Client(object):
# got one.. check whether it's still valid
try:
if self.session_check_is_valid():
print("Using valid Session ID from ({0})".format(self.session_id_store))
print("Using valid Session ID "
"from ({0})".format(self.session_id_store.file_path))
return True
except OTRSAPIError:
"""most likely invalid session_id so pass. Remove clear session_id_store.."""
# got no (valid) session_id from file.. try to create new one
# got no (valid) session_id; clean store and try to create new one
self.session_id = None
self.session_id_store.write()
if not self.session_create():
raise SessionCreateError("Failed to create a Session ID!")
......@@ -654,7 +661,7 @@ class Client(object):
if not self.session_id_store.write():
raise SessionIDFileError("Failed to save Session ID to file!")
else:
print("Saved new Session ID to file: {0}".format(self.session_id_store))
print("Saved new Session ID to file: {0}".format(self.session_id_store.file_path))
return True
def _session_create_json(self, url, payload):
......
......@@ -25,7 +25,7 @@ from pyotrs import Article # noqa
class ArticleTests(unittest.TestCase):
def test_dummy(self):
art = Article.dummy()
art = Article._dummy()
self.assertIsInstance(art, Article)
self.assertRegex(art.__repr__(), '<Article.*')
......@@ -36,7 +36,7 @@ class ArticleTests(unittest.TestCase):
'TimeUnit': 0,
'MimeType': 'text/plain',
'Charset': 'UTF8'}}
art = Article.dummy()
art = Article._dummy()
self.assertDictEqual(art.to_dct(), expected)
def test_dummy_force_notify(self):
......@@ -47,7 +47,7 @@ class ArticleTests(unittest.TestCase):
'MimeType': 'text/plain',
'Charset': 'UTF8',
"ForceNotificationToUserID": [1, 2]}}
art = Article.dummy_force_notify()
art = Article._dummy_force_notify()
self.assertDictEqual(art.to_dct(), expected)
def test_validation(self):
......
......@@ -35,7 +35,7 @@ class AttachmentTests(unittest.TestCase):
self.assertEqual(att.__repr__(), '<Attachment: dümmy.txt>')
def test_attachment_dummy(self):
att = Attachment.dummy()
att = Attachment._dummy()
self.assertIsInstance(att, Attachment)
self.assertEqual(att.__repr__(), '<Attachment: dümmy.txt>')
......
......@@ -226,7 +226,7 @@ class ClientTests(unittest.TestCase):
self.assertEqual(mock_read_s_id.call_count, 1)
self.assertEqual(mock_s_create.call_count, 1)
self.assertEqual(mock_wr.call_count, 1)
self.assertEqual(mock_wr.call_count, 2)
@mock.patch('pyotrs.SessionIDStore.write', autospec=True)
@mock.patch('pyotrs.Client.session_create', autospec=True)
......@@ -245,7 +245,7 @@ class ClientTests(unittest.TestCase):
self.assertEqual(mock_read_s_id.call_count, 1)
self.assertEqual(mock_s_create.call_count, 1)
self.assertEqual(mock_wr.call_count, 1)
self.assertEqual(mock_wr.call_count, 2)
@mock.patch('pyotrs.Client._ticket_get_json', autospec=True)
def test_ticket_get_by_id_fail(self, mock_ticket_get_json):
......
......@@ -49,12 +49,12 @@ class DynamicFieldTests(unittest.TestCase):
self.assertDictEqual(dyn1.to_dct(), {'Name': 'firstname', 'Value': 'Jane'})
def test_dummy1(self):
dyn1 = DynamicField.dummy1()
dyn1 = DynamicField._dummy1()
self.assertIsInstance(dyn1, DynamicField)
self.assertEqual(dyn1.__repr__(), '<DynamicField: firstname --> Jane >')
def test_dummy2(self):
dyn2 = DynamicField.dummy2()
dyn2 = DynamicField._dummy2()
self.assertIsInstance(dyn2, DynamicField)
self.assertEqual(dyn2.__repr__(), '<DynamicField: lastname --> Doe >')
......
# -*- coding: utf-8 -*-
from __future__ import unicode_literals # support both Python2 and 3
#
# Name: test_pyotrs.py
# Description: Test for pyotrs module
#
# Author: robert.habermann@dlh.de
# Date: 2015-07-14
# make sure (early) that parent dir (main app) is in path
import os.path
import sys
current_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(current_path, os.pardir))
import unittest2 as unittest
import responses
import requests
from mock import MagicMock, patch
from pyotrs import Client, Ticket
from pyotrs.lib import NoBaseURL, NoWebServiceName, NoCredentials
from pyotrs.lib import SessionCreateError, SessionIDFileError, OTRSAPIError, OTRSHTTPError
class PyOTRSTests(unittest.TestCase):
""" Test Responses: Check whether direct call to _helper function raises the 'get api'
exception when Error is recvd
"""
# def test_resp___get_json_ticket_data(self):
# with responses.RequestsMock() as rsps:
# # responses will return this data:
# rsps.add(responses.POST,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Session',
# body={'SessionID': 'fakesessionid'},
# status=200,
# content_type='application/json')
# rsps.add(responses.GET,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Ticket/1',
# body={'Error': {'ErrorMessage': 'TicketGet: Authorization failing!',
# 'ErrorCode' : 'TicketGet.AuthFail'}},
# status=200,
# content_type='application/json')
#
# username = 'wrong_username'
# password = 'wrong_password'
#
# url = 'https://fqdn/otrs/nph-genericinterface.pl/Webservice' \
# '/GenericTicketConnectorREST/Ticket/1'
# payload = {
# 'UserLogin' : username,
# 'Password' : password,
# 'AllArticles' : 0,
# 'DynamicFields': 1
# }
#
# obj = Client('http://localhost/', 'dummy', 'username', 'password')
# obj.session_restore_or_set_up_new()
#
# self.assertRaisesRegexp(OTRSAPIError,
# 'TicketGet API Error.*',
# obj._ticket_get_json,
# url=url,
# payload=payload)
#
# def test_resp_get_json_ticket_data_by_ticket_id(self):
# """ This tests: get_json_ticket_data_by_ticket_id - Test 200 OK;
# Body Error """
# with responses.RequestsMock() as rsps:
# # responses will return this data:
# rsps.add(responses.POST,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Session',
# body={'SessionID': 'fakesessionid'},
# status=200,
# content_type='application/json')
# rsps.add(responses.GET,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Ticket/1',
# body={'Error': {'ErrorMessage': 'TicketGet: Authorization failing!',
# 'ErrorCode' : 'TicketGet.AuthFail'}},
# status=200,
# content_type='application/json')
#
# username = 'wrong_username'
# password = 'wrong_password'
#
# obj = Client('http://localhost/', 'dummy', 'username', 'password')
# obj.session_restore_or_set_up_new()
# obj.ticket_get_by_id(1)
#
# self.assertEqual({'Error': {'ErrorMessage': 'TicketGet: Authorization failing!',
# 'ErrorCode' : 'TicketGet.AuthFail'}},
# obj.response.json())
# self.assertEqual(200, obj.response.status_code)
#
# def test_resp_update_by_ticket_id_set_title_valid(self):
# """ This tests: Test Responses: update title on valid ticket """
# with responses.RequestsMock() as rsps:
# # responses will return this data:
# rsps.add(responses.POST,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Session',
# body={'SessionID': 'fakesessionid'},
# status=200,
# content_type='application/json'
# )
# rsps.add(responses.PATCH,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Ticket/10',
# body={'TicketNumber': '1970010100000010',
# 'TicketID' : '10'},
# status=200,
# content_type='application/json')
#
# username = 'fake_username'
# password = 'fake_password'
#
# obj = Client('http://localhost/', 'dummy', 'username', 'password')
# obj.session_restore_or_set_up_new()
# obj.ticket_update_set_title(10, 'Full New Title')
#
# self.assertEqual({'TicketNumber': '1970010100000010', 'TicketID': '10'},
# obj.response.json())
# self.assertEqual(200, obj.response.status_code)
#
# def test_resp_update_by_ticket_id_set_title_invalid(self):
# """ This tests: Test Responses: update title on invalid ticket (or wrong credentials) """
# # responses will return this data:
# with responses.RequestsMock() as rsps:
# rsps.add(responses.POST,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Session',
# body={'SessionID': 'fakesessionid'},
# status=200,
# content_type='application/json')
# rsps.add(responses.PATCH,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Ticket/20',
# body={'Error': {'ErrorCode' : 'TicketUpdate.AccessDenied',
# 'ErrorMessage': 'TicketUpdate: User does not have access '
# 'to the ticket!'}},
# status=200,
# content_type='application/json')
#
# username = 'fake_username'
# password = 'fake_password'
#
# obj = Client('http://localhost/', 'dummy', 'username', 'password')
# obj.session_restore_or_set_up_new()
# obj.ticket_update_set_title(20, 'Full New Title')
#
# self.assertEqual({'Error': {'ErrorCode' : 'TicketUpdate.AccessDenied',
# 'ErrorMessage': 'TicketUpdate: User does not have access '
# 'to the ticket!'}},
# obj.response.json())
# self.assertEqual(200, obj.response.status_code)
#
# def test_mock_get_json_ticket_data_by_ticket_id(self):
# """ This tests: Test Mock: Validate that the right call to _get_json_ticket_data
# is made by requests when calling: get_json_ticket_data_by_ticket_id
# """
# with responses.RequestsMock() as rsps:
# rsps.add(responses.POST,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Session',
# body={'UserLogin': 'wrong_username',
# 'Password': 'wrong_password'},
# status=200,
# content_type='application/json')
# # Define values for function call
# username = 'wrong_username'
# password = 'wrong_password'
#
# # Define data that should be called later:
# url = 'https://fqdn/otrs/nph-genericinterface.pl/Webservice' \
# '/GenericTicketConnectorREST/Ticket/1'
# payload = {
# 'SessionID': 'fakesessionid',
# 'AllArticles': 0,
# 'DynamicFields': 1
# }
#
# # create object
# obj = Client('http://fqdn/', 'GenericTicketConnectorREST', username, password)
# obj.session_create()
# enable Mock
# obj._ticket_get_json = MagicMock()
# call function
# obj.ticket_get_by_id(1)
#
# def test_mock_get_json_ticket_data_by_ticket_id_with(self):
# """ This tests: Test Mock: Validate that the right call to requests is made """
# with responses.RequestsMock() as rsps:
# rsps.add(responses.POST,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST/Session',
# body={'SessionID': 'fakesessionid'},
# status=200,
# content_type='application/json')
# # expected content of request:
# mock_url = 'https://fqdn/otrs/nph-genericinterface.pl/Webservice' \
# '/GenericTicketConnectorREST/Ticket/1'
# mock_payload = {
# 'SessionID' : 'fakesessionid',
# 'AllArticles' : 0,
# 'DynamicFields': 1
# }
#
# mock_username = 'wrong_username'
# mock_password = 'wrong_password'
#
# obj = Client('http://localhost/', 'dummy', 'username', 'password')
# obj.session_restore_or_set_up_new()
#
# with patch('requests.get') as patched_get:
# obj.ticket_get_by_id(1)
# # Ensure patched get was called, called only once and with exactly these params.
# patched_get.assert_called_once_with(mock_url,
# params=mock_payload,
# verify=True)
#
# def test_session_handling(self):
# """ This tests: Test Responses: when calling: get_json_ticket_data_by_ticket_id - Test
# 200 OK;
# Body Error """
# with responses.RequestsMock() as rsps:
# # responses will return this data:
# rsps.add(responses.POST,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST'
# '/Session',
# body={'SessionID': 'fakesessionid'},
# status=200,
# content_type='application/json')
#
# rsps.add(responses.GET,
# 'https://fqdn/otrs/nph-genericinterface.pl/Webservice'
# '/GenericTicketConnectorREST'
# '/Ticket/1',
# body={'Ticket':
# [{'Age': 156717521,
# 'PriorityID': '3',
# 'ServiceID': '',
# 'Type': 'Unclassified',
# 'Responsible': 'root@localhost',
# 'StateID': '2',
# 'ResponsibleID': '1',
# 'ChangeBy': '2',
# 'EscalationTime': '0',
# 'OwnerID': '2',
# 'Changed': '2015-06-08 11:36:17',
# 'RealTillTimeNotUsed': '0',
# 'GroupID': '7',
# 'Owner': 'User',
# 'CustomerID': '',
# 'TypeID': 1,
# 'Created': '2010-08-02 12:00:00',
# 'Priority': '3 normal',
# 'UntilTime': 0,
# 'EscalationUpdateTime': '0',
# 'QueueID': '9',
# 'Queue': 'Operations::OTRS',
# 'State': 'closed',
# 'Title': 'Welcome to OTRS!',
# 'CreateBy': '1',
# 'TicketID': '1',
# 'StateType': 'closed',
# 'UnlockTimeout': '1433763374',
# 'EscalationResponseTime': '0',
# 'EscalationSolutionTime': '0',
# 'LockID': '1',
# 'TicketNumber': '2010080210123456',
# 'ArchiveFlag': 'n',
# 'CreateTimeUnix': '1280750400',
# 'Lock': 'unlock',
# 'SLAID': '',
# 'CustomerUser': 'root@localhost'}]},
# status=200,
# content_type='application/json')
# mock_username = 'correct_username'
# mock_password = 'correct_password'
# with patch('modules.pymisc.send_message_via_mail') as patched_send_message:
# obj = pyotrs.PyOTRS(self.baseurl, self.webservice_name, mock_username,
# mock_password)
""" TODOs
Write tests for
* _get_json_ticket_data with http request failing (e.g. due to wrong fqdn or proxy)
* search_ticket(self, payload)
* _search_json_ticket_data(self, url, payload):
"""
# Main
def main():
unittest.main()
if __name__ == '__main__':
main()
# EOF
......@@ -32,6 +32,10 @@ class SessionIDStoreTests(unittest.TestCase):
sis = SessionIDStore(file_path="/tmp/.session_id_store", session_timeout=600)
self.assertIsInstance(sis, SessionIDStore)
def test_init_ok_repr(self):
sis = SessionIDStore(file_path="/tmp/.session_id_store", session_timeout=600)
self.assertEqual(sis.__repr__(), '<SessionIDStore: /tmp/.session_id_store>')
@mock.patch('pyotrs.lib.os.path.isfile', autospec=True)
def test_read_no_file(self, mock_isfile):
"""Tests _read_session_id_from_file no file"""
......
......@@ -157,7 +157,7 @@ class TicketTests(unittest.TestCase):
'Year': 1})
def test_dummy(self):
tic = Ticket.dummy()
tic = Ticket._dummy()
self.assertDictEqual(tic.to_dct(),
{'Ticket': {'Queue': u'Raw',
'State': u'open',
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment