rt-3.8.1/rt/__init__.py0000644000000000000000000000012213615410400011621 0ustar00"""Module entry point.""" from .exceptions import RtError __all__ = ['RtError'] rt-3.8.1/rt/exceptions.py0000644000000000000000000000365513615410400012261 0ustar00"""Exceptions collection for the rt library.""" class RtError(Exception): """Super class of all Rt Errors.""" class AuthorizationError(RtError): """Exception raised when module cannot access :term:`API` due to invalid or missing credentials.""" class NotAllowedError(RtError): """Exception raised when request cannot be finished due to insufficient privileges.""" class UnexpectedResponseError(RtError): """Exception raised when unexpected HTTP code is received.""" def __init__(self, message: str, status_code: int | None = None, response_message: str | None = None) -> None: """Initialization.""" super().__init__(message) self.status_code = status_code self.response_message = response_message class UnexpectedMessageFormatError(RtError): """Exception raised when response has bad status code (not the HTTP code, but code in the first line of the body as 200 in `RT/4.0.7 200 Ok`) or message parsing fails because of unexpected format. """ class NotFoundError(RtError): """Exception raised if requested resource is not found.""" class APISyntaxError(RtError): """Exception raised when syntax error is received.""" class InvalidUseError(RtError): """Exception raised when API method is not used correctly.""" class BadRequestError(RtError): """Exception raised when HTTP code 400 (Bad Request) is received.""" class ConnectionError(RtError): """Encapsulation of various exceptions indicating network problems.""" def __init__(self, message: str, cause: Exception) -> None: """Initialization of exception extended by cause parameter. :keyword message: Exception details :keyword cause: Cause exception """ super().__init__(f'{message} (Caused by {repr(cause)})') self.cause = cause class InvalidQueryError(RtError): """Exception raised when attempting to search RT with an invalid raw query.""" rt-3.8.1/rt/py.typed0000644000000000000000000000000013615410400011202 0ustar00rt-3.8.1/rt/rest1.py0000644000000000000000000017345113615410400011140 0ustar00"""Rt - Python interface to Request Tracker :term:`API`. Description of Request Tracker :term:`REST` :term:`API`: http://requesttracker.wikia.com/wiki/REST Provided functionality: * login to RT * logout * getting, creating and editing tickets * getting attachments * getting history of ticket * replying to ticket requestors * adding comments * getting and editing ticket links * searching * providing lists of last updated tickets * providing tickets with new correspondence * merging tickets * take tickets * steal tickets * untake tickets """ import datetime import logging import re import typing import warnings from urllib.parse import urljoin import requests import requests.auth from .exceptions import ( APISyntaxError, AuthorizationError, BadRequestError, InvalidQueryError, InvalidUseError, NotAllowedError, NotFoundError, UnexpectedMessageFormatError, UnexpectedResponseError, ) __license__ = """ Copyright (C) 2012 CZ.NIC, z.s.p.o. Copyright (c) 2015 Genome Research Ltd. Copyright (c) 2017 CERT Gouvernemental (GOVCERT.LU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ __docformat__ = 'reStructuredText en' __authors__ = [ '"Jiri Machalek" ', '"Joshua C. randall" ', '"Georges Toth" ', ] DEFAULT_QUEUE = 'General' """ Default queue used. """ ALL_QUEUES = object() class Rt: r""":term:`API` for Request Tracker according to http://requesttracker.wikia.com/wiki/REST. Interface is based on :term:`REST` architecture, which is based on HTTP/1.1 protocol. This module is therefore mainly sending and parsing special HTTP messages. .. note:: Use only ASCII LF as newline (``\\n``). Time is returned in UTC. All strings returned are encoded in UTF-8 and the same is expected as input for string values. """ RE_PATTERNS = { 'not_allowed_pattern': re.compile('^# You are not allowed to'), 'credentials_required_pattern': re.compile('.* 401 Credentials required$'), 'syntax_error_pattern': re.compile('.* 409 Syntax Error$'), 'requestors_pattern': re.compile('Requestors:'), 'update_pattern': re.compile('^# Ticket [0-9]+ updated.$'), 'content_pattern': re.compile('Content:'), 'content_pattern_bytes': re.compile(b'Content:'), 'attachments_pattern': re.compile('Attachments:'), 'attachments_list_pattern': re.compile(r'[^0-9]*(\d+): (.+) \((.+) / (.+)\),?$'), 'headers_pattern_bytes': re.compile(b'Headers:'), 'links_updated_pattern': re.compile('^# Links for ticket [0-9]+ updated.$'), 'created_link_pattern': re.compile('.* Created link '), 'deleted_link_pattern': re.compile('.* Deleted link '), 'merge_successful_pattern': re.compile('^# Merge completed.|^Merge Successful$'), 'bad_request_pattern': re.compile('.* 400 Bad Request$'), 'user_pattern': re.compile(r'^# User ([0-9]*) (?:updated|created)\.$'), 'queue_pattern': re.compile(r'^# Queue (\w*) (?:updated|created)\.$'), 'ticket_created_pattern': re.compile(r'^# Ticket ([0-9]+) created\.$'), 'does_not_exist_pattern': re.compile(r'^# (?:Queue|User|Ticket) \w* does not exist\.$'), 'status_pattern': re.compile(r'^\S+ (\d{3}) '), 'does_not_exist_pattern_bytes': re.compile(rb'^# (?:Queue|User|Ticket) \w* does not exist\.$'), 'not_related_pattern': re.compile(r'^# Transaction \d+ is not related to Ticket \d+'), 'invalid_attachment_pattern_bytes': re.compile(rb'^# Invalid attachment id: \d+$'), } # type: typing.Dict[str, re.Pattern] def __init__( self, url: str, default_login: str | None = None, default_password: str | None = None, cookies: dict | None = None, proxy: str | None = None, default_queue: str = DEFAULT_QUEUE, skip_login: bool = False, verify_cert: str | bool | None = True, http_auth: requests.auth.AuthBase | None = None, ) -> None: """API initialization. :keyword url: Base URL for Request Tracker API. E.g.: http://tracker.example.com/REST/1.0/ :keyword default_login: Default RT login used by self.login if no other credentials are provided :keyword default_password: Default RT password :keyword proxy: Proxy server (string with http://user:password@host/ syntax) :keyword default_queue: Default RT queue :keyword skip_login: Set this option True when HTTP Basic authentication credentials for RT are in .netrc file. You do not need to call login, because it is managed by requests library instantly. :keyword http_auth: Specify a http authentication instance, e.g. HTTPBasicAuth(), HTTPDigestAuth(), etc. to be used for authenticating to RT """ self.logger = logging.getLogger(__name__) # ensure trailing slash if not url.endswith('/'): url = url + '/' self.url = url self.default_login = default_login self.default_password = default_password self.default_queue = default_queue self.login_result = None self.session = requests.session() if cookies: self.session.headers.update({'referer': url}) self.session.cookies.update(cookies) self.login_result = True self.session.verify = verify_cert if proxy is not None: if url.lower().startswith('https://'): self.session.proxies = {'https': proxy} else: self.session.proxies = {'http': proxy} if http_auth: self.session.auth = http_auth if skip_login or http_auth: # Assume valid credentials, because we do not need to call login() # explicitly with basic or digest authentication (or if this is # assured, that we are login in instantly) self.login_result = True def __request( self, selector: str, get_params: dict[str, typing.Any] | None = None, post_data: dict[str, typing.Any] | None = None, files: list[tuple[str, typing.IO, str | None]] | None = None, without_login: bool = False, text_response: bool = True, ) -> str: r"""General request for :term:`API`. :keyword selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :keyword post_data: Dictionary with POST method fields :keyword files: List of pairs (filename, file-like object) describing files to attach as multipart/form-data (list is necessary to keep files ordered) :keyword without_login: Turns off checking last login result (usually needed just for login itself) :keyword text_response: If set to false the received message will be returned without decoding (useful for attachments) :returns: Requested message including state line in form ``RT/3.8.7 200 Ok\\n`` :rtype: string or bytes if text_response is False :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: if (not self.login_result) and (not without_login): raise AuthorizationError('First login by calling method `login`.') url = str(urljoin(self.url, selector)) if not files: if post_data: response = self.session.post(url, data=post_data) else: response = self.session.get(url, params=get_params) else: files_data = {} for i, file_pair in enumerate(files): files_data[f'attachment_{i + 1}'] = file_pair response = self.session.post(url, data=post_data, files=files_data) # type: ignore method = 'GET' if post_data or files: method = 'POST' self.logger.debug('### %s', datetime.datetime.now(tz=datetime.timezone.utc).isoformat()) self.logger.debug('Request URL: %s', url) self.logger.debug('Request method: %s', method) self.logger.debug('Response status code: %s', str(response.status_code)) self.logger.debug('Response content:') self.logger.debug(response.content.decode(errors='ignore')) if response.status_code == 401: raise AuthorizationError('Server could not verify that you are authorized to access the requested document.') if response.status_code != 200: raise UnexpectedResponseError(f'Received status code {response.status_code} instead of 200.') try: if response.encoding: result = response.content.decode(response.encoding.lower()) else: # try utf-8 if encoding is not filled result = response.content.decode('utf-8') except LookupError as exc: raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: if text_response: raise UnexpectedResponseError('Unknown response encoding (UTF-8 does not work).') from exc # replace errors - we need decoded content just to check for error codes in __check_response result = response.content.decode('utf-8', 'replace') self.__check_response(result) if not text_response: return response.content # type: ignore return result except requests.exceptions.ConnectionError as exc: raise ConnectionError('Connection error', exc) from exc @staticmethod def __get_status_code(msg: str) -> int | None: """Select status code given message. :keyword msg: Result message :returns: Status code :rtype: int """ try: return int(msg.split('\n', maxsplit=1)[0].split(' ')[1]) except (ValueError, AttributeError, LookupError): return None def __check_response(self, msg: str | list) -> None: """Search general errors in server response and raise exceptions when found. :keyword msg: Result message :raises NotAllowedError: Exception raised when operation was called with insufficient privileges :raises AuthorizationError: Credentials are invalid or missing :raises APISyntaxError: Syntax error """ if not isinstance(msg, list): msg = msg.split('\n') if (len(msg) > 2) and self.RE_PATTERNS['not_allowed_pattern'].match(msg[2]): raise NotAllowedError(msg[2][2:]) if self.RE_PATTERNS['credentials_required_pattern'].match(msg[0]): raise AuthorizationError('Credentials required.') if self.RE_PATTERNS['syntax_error_pattern'].match(msg[0]): raise APISyntaxError(msg[2][2:] if len(msg) > 2 else 'Syntax error.') if self.RE_PATTERNS['bad_request_pattern'].match(msg[0]): raise BadRequestError(msg[2] if len(msg) > 2 else 'Bad request.') @staticmethod def __normalize_list(msg: str | typing.Sequence[str]) -> typing.Sequence[str]: """Split message to list by commas and trim whitespace.""" if isinstance(msg, list): _msg = ''.join(msg) elif isinstance(msg, str): _msg = msg else: raise ValueError('Invalid parameter type.') if not _msg: return [] return [x.strip() for x in _msg.split(',')] @classmethod def __parse_response_dict( cls, msg: typing.Iterable[str], expect_keys: typing.Iterable[str] = (), ) -> dict[str, str]: """Parse an RT API response body into a Python dictionary. This method knows the general format for key-value RT API responses, and parses them into a Python dictionary as plain string values. :keyword msg: A multiline string, or an iterable of string lines, with the RT API response body. :keyword expect_keys: An iterable of strings. If any of these strings do not appear in the response, raise an error. :raises UnexpectedMessageFormatError: The body did not follow the expected format, or an expected key was missing :returns: Dictionary mapping field names to value strings :rtype: Dictionary with string keys and string values """ if isinstance(msg, str): msg = msg.split('\n') fields = {} # type: typing.Dict[str, typing.List[str]] key = '' for line in msg: if not line or line.startswith('#') or (not fields and cls.RE_PATTERNS['status_pattern'].match(line)): key = '' elif line[0].isspace(): try: fields[key].append(line.lstrip()) except KeyError: raise UnexpectedMessageFormatError( 'Response has a continuation line with no field to continue', ) from None else: if line.startswith('CF.{'): sep = '}: ' else: sep = ': ' key, sep, value = line.partition(sep) if sep: key += sep[:-2] fields[key] = [value] elif line.endswith(':'): key = line[:-1] fields[key] = [] else: raise UnexpectedMessageFormatError(f'Response has a line without a field name: {line}') for key in expect_keys: if key not in fields: raise UnexpectedMessageFormatError(f'Missing line starting with `{key}:`.') return {key: '\n'.join(lines) for key, lines in fields.items()} @classmethod def __parse_response_numlist( cls, msg: typing.Iterable[str], ) -> list[tuple[int, str]]: """Parse an RT API response body into a numbered list. The RT API for transactions and attachments returns a numbered list of items. This method returns 2-tuples to represent them, where the first item is an integer id and the second items is a string description. :keyword msg: A multiline string, or an iterable of string lines, with the RT API response body. :raises UnexpectedMessageFormatError: The body did not follow the expected format :returns: List of 2-tuples with ids and descriptions :rtype: List of 2-tuples (int, str) """ return sorted((int(key), value) for key, value in cls.__parse_response_dict(msg).items()) @classmethod def __parse_response_ticket(cls, msg: typing.Iterable[str]) -> dict[str, str | typing.Sequence[str]]: """Parse an RT API ticket response into a Python dictionary. :keyword msg: A multiline string, or an iterable of string lines, with the RT API response body. :raises UnexpectedMessageFormatError: The body did not follow the expected format :returns: Dictionary mapping field names to value strings, or lists of strings for the People fields Requestors, Cc, and AdminCc :rtype: Dictionary with string keys and values that are strings or lists of strings """ pairs = cls.__parse_response_dict(msg, ['Requestors']) if not pairs.get('id', '').startswith('ticket/'): raise UnexpectedMessageFormatError("Response from RT didn't contain a valid ticket_id") _, _, numerical_id = pairs['id'].partition('/') ticket = typing.cast('dict[str, typing.Sequence[str]]', pairs) ticket['numerical_id'] = numerical_id for key in ['Requestors', 'Cc', 'AdminCc']: try: ticket[key] = cls.__normalize_list(ticket[key]) except KeyError: pass return ticket def login(self, login: str | None = None, password: str | None = None) -> bool: """Login with default or supplied credentials. .. note:: Calling this method is not necessary when HTTP basic or HTTP digest_auth authentication is used and RT accepts it as external authentication method, because the login in this case is done transparently by requests module. Anyway this method can be useful to check whether given credentials are valid or not. :keyword login: Username used for RT, if not supplied together with *password* :py:attr:`~Rt.default_login` and :py:attr:`~Rt.default_password` are used instead :keyword password: Similarly as *login* :returns: ``True`` Successful login ``False`` Otherwise :raises AuthorizationError: In case that credentials are not supplied neither during initialization or call of this method. """ if (login is not None) and (password is not None): login_data = {'user': login, 'pass': password} # type: typing.Optional[typing.Dict[str, str]] elif (self.default_login is not None) and (self.default_password is not None): login_data = {'user': self.default_login, 'pass': self.default_password} elif self.session.auth: login_data = None else: raise AuthorizationError('Credentials required, fill login and password.') try: self.login_result = self.__get_status_code(self.__request('', post_data=login_data, without_login=True)) == 200 except AuthorizationError: # This happens when HTTP Basic or Digest authentication fails, but # we will not raise the error but just return False to indicate # invalid credentials return False return bool(self.login_result) def logout(self) -> bool: """Logout of user. :returns: ``True`` Successful logout ``False`` Logout failed (mainly because user was not login) """ ret = False if self.login_result is True: ret = self.__get_status_code(self.__request('logout')) == 200 self.login_result = None return ret def new_correspondence(self, queue: str | object | None = None) -> list[dict]: """Obtains tickets changed by other users than the system one. :keyword queue: Queue where to search :returns: List of tickets which were last updated by other user than the system one ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login) def last_updated(self, since: str, queue: str | object | None = None) -> list[dict]: """Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :keyword queue: Queue where to search :returns: List of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each tickets is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(Queue=queue, order='-LastUpdated', LastUpdatedBy__notexact=self.default_login, LastUpdated__gt=since) def search( self, Queue: str | object | None = None, order: str | None = None, raw_query: str | None = None, Format: str = 'l', Fields: list[str] | None = None, **kwargs: typing.Any, ) -> list[dict]: r"""Search arbitrary needles in given fields and queue. Example:: >>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret') >>> tracker.login() >>> tickets = tracker.search(CF_Domain='example.com', Subject__like='warning') >>> tickets = tracker.search(Queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'") :keyword Queue: Queue where to search. If you wish to search across all of your queues, pass the ALL_QUEUES object as the argument. :keyword order: Name of field sorting result list, for descending order put - before the field name. E.g. -Created will put the newest tickets at the beginning :keyword raw_query: A raw query to provide to RT if you know what you are doing. You may still pass Queue and order kwargs, so use these instead of including them in the raw query. You can refer to the RT query builder. If passing raw_query, all other \\**kwargs will be ignored. :keyword Format: Format of the query: - i: only `id` fields are populated - s: only `id` and `subject` fields are populated - l: multi-line format, all fields are populated :keyword kwargs: Other arguments possible to set if not passing raw_query: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. To alter lookup operators you can append one of the following endings to each keyword:: __exact for operator = (default) __notexact for operator != __gt for operator > __lt for operator < __like for operator LIKE __notlike for operator NOT LIKE __is for operator IS __isnot for operator IS NOT Setting values to keywords constrain search result to the tickets satisfying all of them. :returns: List of matching tickets. Each ticket is the same dictionary as in :py:meth:`~Rt.get_ticket`\\. :raises: UnexpectedMessageFormatError: Unexpected format of returned message. InvalidQueryError: If raw query is malformed """ get_params = {} query = [] url = 'search/ticket' if Queue is not ALL_QUEUES: query.append(f"Queue='{Queue or self.default_queue}'") if not raw_query: operators_map = { 'gt': '>', 'lt': '<', 'exact': '=', 'notexact': '!=', 'like': ' LIKE ', 'notlike': ' NOT LIKE ', 'is': ' IS ', 'isnot': ' IS NOT ', } for _key, value in kwargs.items(): key = _key op = '=' key_parts = key.split('__') if len(key_parts) > 1: key = '__'.join(key_parts[:-1]) op = operators_map.get(key_parts[-1], '=') if key[:3] != 'CF_': query.append(f"{key}{op}'{value}'") else: query.append(f"'CF.{{{key[3:]}}}'{op}'{value}'") else: query.append(raw_query) get_params['query'] = ' AND '.join('(' + part + ')' for part in query) if order: get_params['orderby'] = order get_params['format'] = Format if Fields: get_params['fields'] = ''.join(Fields) msg = self.__request(url, get_params=get_params) lines = msg.split('\n') if len(lines) > 2: if self.__get_status_code(lines[0]) != 200 and lines[2].startswith('Invalid query: '): raise InvalidQueryError(lines[2]) if lines[2].startswith('No matching results.'): return [] if Format == 'l': return [self.__parse_response_ticket(ticket_msg) for ticket_msg in msg.split('\n--\n')] if Format == 's': return [ {'id': 'ticket/' + key, 'numerical_id': key, 'Subject': value} for key, value in self.__parse_response_dict(msg).items() ] if Format == 'i': items = [] msgs = lines[2:] for msg in msgs: if msg == '': # Ignore blank line at the end continue _, ticket_id = msg.split('/', 1) items.append({'id': 'ticket/' + ticket_id, 'numerical_id': ticket_id}) return items return [] def get_ticket(self, ticket_id: str | int) -> dict | None: """Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys: * id * numerical_id * Queue * Owner * Creator * Subject * Status * Priority * InitialPriority * FinalPriority * Requestors * Cc * AdminCc * Created * Starts * Started * Due * Resolved * Told * TimeEstimated * TimeWorked * TimeLeft :raises UnexpectedMessageFormatError: Unexpected format of returned message. """ _msg = self.__request(f'ticket/{ticket_id}/show') status_code = self.__get_status_code(_msg) if status_code is not None and status_code == 200: msg = _msg.split('\n') try: not_found = self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]) except IndexError: not_found = None if not_found: return None return self.__parse_response_ticket(msg) raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') @staticmethod def __ticket_post_data(data_source: dict) -> str: """Convert a dictionary of RT ticket data into a REST POST data string. :param data_source: Dictionary with ticket fields and values. :returns: Equivalent string to POST to the RT REST interface. """ post_data = [] for key, data_source_value in data_source.items(): if key.startswith('CF_'): rt_key = f'CF.{{{key[3:]}}}' else: rt_key = key value = data_source_value if isinstance(value, (list, tuple)): value = ', '.join(value) value_lines = iter(value.splitlines()) post_data.append(f"""{rt_key}: {next(value_lines, '')}""") post_data.extend(' ' + line for line in value_lines) return '\n'.join(post_data) def create_ticket( self, Queue: str | object | None = None, files: list[tuple[str, typing.IO, str | None]] | None = None, **kwargs: typing.Any, ) -> int: """Create new ticket and set given parameters. Example of message sended to ``http://tracker.example.com/REST/1.0/ticket/new``:: content=id: ticket/new Queue: General Owner: Nobody Requestor: somebody@example.com Subject: Ticket created through REST API Text: Lorem Ipsum In case of success returned message has this form:: RT/3.8.7 200 Ok # Ticket 123456 created. # Ticket 123456 updated. Otherwise:: RT/3.8.7 200 Ok # Required: id, Queue + list of some key, value pairs, probably default values. :keyword Queue: Queue where to create ticket :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :keyword kwargs: Other arguments possible to set: Requestor, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. :returns: ID of new ticket or ``-1``, if creating failed """ kwargs['id'] = 'ticket/new' kwargs['Queue'] = Queue or self.default_queue post_data = self.__ticket_post_data(kwargs) if files: for file_info in files: post_data += f'\nAttachment: {file_info[0]}' msg = self.__request('ticket/new', post_data={'content': post_data}, files=files) for line in msg.split('\n')[2:-1]: res = self.RE_PATTERNS['ticket_created_pattern'].match(line) if res is not None: return int(res.group(1)) warnings.warn(line[2:], stacklevel=2) return -1 def edit_ticket(self, ticket_id: str | int, **kwargs: typing.Any) -> bool: """Edit ticket values. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = self.__ticket_post_data(kwargs) msg = self.__request(f'ticket/{ticket_id}/edit', post_data={'content': post_data}) if '' == msg: # Ticket not modified return True state = msg.split('\n')[2] return self.RE_PATTERNS['update_pattern'].match(state) is not None def get_history(self, ticket_id: str | int, transaction_id: str | int | None = None) -> list[dict] | None: """Get set of history items. :param ticket_id: ID of ticket :keyword transaction_id: If set to None, all history items are returned, if set to ID of valid transaction just one history item is returned :returns: List of history items ordered increasingly by time of event. Each history item is dictionary with following keys: Description, Creator, Data, Created, TimeTaken, NewValue, Content, Field, OldValue, Ticket, Type, id, Attachments All these fields are strings, just 'Attachments' holds list of pairs (attachment_id,filename_with_size). Returns None if ticket or transaction does not exist. :raises UnexpectedMessageFormatError: Unexpected format of returned message. """ if transaction_id is None: # We are using "long" format to get all history items at once. # Each history item is then separated by double dash. msgs = self.__request(f'ticket/{ticket_id}/history?format=l') else: msgs = self.__request(f'ticket/{ticket_id}/history/id/{transaction_id}') lines = msgs.split('\n') if (len(lines) > 2) and ( self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]) or self.RE_PATTERNS['not_related_pattern'].match(lines[2]) ): return None items = typing.cast( 'list[dict[str, str | list[tuple[int, str]]]]', [self.__parse_response_dict(msg, ['Content', 'Attachments']) for msg in msgs.split('\n--\n')], ) for body in items: attachments = typing.cast('str', body.get('Attachments', '')) body['Attachments'] = self.__parse_response_numlist(attachments) return items def get_short_history(self, ticket_id: str | int) -> list[tuple[int, str]] | None: """Get set of short history items. :param ticket_id: ID of ticket :returns: List of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). Returns None if ticket does not exist. """ msg = self.__request(f'ticket/{ticket_id}/history') lines = msg.split('\n') if self.__get_status_code(lines[0]) == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None return self.__parse_response_numlist(lines) return [] def __correspond( self, ticket_id: str | int, text: str = '', action: str = 'correspond', cc: str = '', bcc: str = '', content_type: str = 'text/plain', files: list[tuple[str, typing.IO, str | None]] | None = None, ) -> bool: """Sends out the correspondence. :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword action: correspond or comment :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this reply :keyword bcc: Blind carbon copy just for this reply :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist """ post_data = { 'content': """id: {} Action: {} Text: {} Cc: {} Bcc: {} Content-Type: {}""".format(str(ticket_id), action, re.sub(r'\n', r'\n ', text), cc, bcc, content_type) } if files: for file_info in files: post_data['content'] += f'\nAttachment: {file_info[0]}' msg = self.__request(f'ticket/{ticket_id}/comment', post_data=post_data, files=files) return self.__get_status_code(msg) == 200 def reply( self, ticket_id: str | int, text: str = '', cc: str = '', bcc: str = '', content_type: str = 'text/plain', files: list[tuple[str, typing.IO, str | None]] | None = None, ) -> bool: """Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. Form of message according to documentation:: id: Action: correspond Text: the text comment second line starts with the same indentation as first Cc: <...> Bcc: <...> TimeWorked: <...> Attachment: an attachment filename/path :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this reply :keyword bcc: Blind carbon copy just for this reply :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist """ return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files) def comment( self, ticket_id: str | int, text: str = '', cc: str = '', bcc: str = '', content_type: str = 'text/plain', files: list[tuple[str, typing.IO, str | None]] | None = None, ) -> bool: """Adds comment to the given ticket. Form of message according to documentation:: id: Action: comment Text: the text comment second line starts with the same indentation as first Attachment: an attachment filename/path Example:: >>> tracker = Rt('http://tracker.example.com/REST/1.0/', 'rt-username', 'top-secret') >>> attachment_name = sys.argv[1] >>> message_text = ' '.join(sys.argv[2:]) >>> ret = tracker.comment(ticket_id, text=message_text, ... files=[(attachment_name, open(attachment_name, 'rb'))]) >>> if not ret: ... print('Error: could not send attachment', file=sys.stderr) ... exit(1) :param ticket_id: ID of ticket to which comment belongs :keyword text: Content of comment :keyword content_type: Content type of comment, default to text/plain :keyword files: Files to attach as multipart/form-data List of 2/3 tuples: (filename, file-like object, [content type]) :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist """ return self.__correspond(ticket_id, text, 'comment', cc, bcc, content_type, files) def get_attachments(self, ticket_id: str | int) -> list[tuple[str, str, str, str]] | None: """Get attachment list for a given ticket. :param ticket_id: ID of ticket :returns: List of tuples for attachments belonging to given ticket. Tuple format: (id, name, content_type, size) Returns None if ticket does not exist. """ msg = self.__request(f'ticket/{ticket_id}/attachments') lines = msg.split('\n') if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None attachment_infos = [] if (self.__get_status_code(lines[0]) == 200) and (len(lines) >= 4): # The format of tickets with 1 attachments varies from those with >=2. # *Attachments: ...* starts at line 3 with single attachment tickets, whereas # with >=2 attachment tickets, it starts at line 4. As in the latter case, # line 3 is just an empty line, we changed this to "3:" in order to work with # single attachment tickets. # -> Bug in RT for line in lines[3:]: info = self.RE_PATTERNS['attachments_list_pattern'].match(line) if info: attachment_infos.append(info.groups()) return attachment_infos # type: ignore # type returned by the regex, if it matches, is as defined above def get_attachments_ids(self, ticket_id: str | int) -> list[int] | None: """Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :returns: List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist. """ attachments = self.get_attachments(ticket_id) return [int(at[0]) for at in attachments] if attachments is not None else None def get_attachment(self, ticket_id: str | int, attachment_id: str | int) -> dict | None: """Get attachment. :param ticket_id: ID of ticket :param attachment_id: ID of attachment for obtain :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (bytes type) * Headers * MessageId * ContentEncoding * id * Subject All these fields are strings, just 'Headers' holds another dictionary with attachment headers as strings e.g.: * Delivered-To * From * Return-Path * Content-Length * To * X-Seznam-User * X-QM-Mark * Domainkey-Signature * RT-Message-ID * X-RT-Incoming-Encryption * X-Original-To * Message-ID * X-Spam-Status * In-Reply-To * Date * Received * X-Country * X-Spam-Checker-Version * X-Abuse * MIME-Version * Content-Type * Subject .. warning:: Content-Length parameter is set after opening ticket in web interface! Set of headers available depends on mailservers sending emails not on Request Tracker! Returns None if ticket or attachment does not exist. :raises UnexpectedMessageFormatError: Unexpected format of returned message. """ _msg = self.__request(f'ticket/{ticket_id}/attachments/{attachment_id}', text_response=False) msg = typing.cast('bytes', _msg).split(b'\n') if (len(msg) > 2) and ( self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2]) ): return None msg = msg[2:] head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)] head_id = head_matching[0] if head_matching else None if not head_id: raise UnexpectedMessageFormatError( 'Unexpected headers part of attachment entry. \ Missing line starting with `Headers:`.' ) msg[head_id] = re.sub(b'^Headers: (.*)$', rb'\1', msg[head_id]) cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)] if not cont_matching: raise UnexpectedMessageFormatError( 'Unexpected content part of attachment entry. \ Missing line starting with `Content:`.' ) cont_id = cont_matching[0] pairs: dict[str, typing.Any] = {} for i in range(head_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8') headers = {} for i in range(head_id, cont_id): if b': ' in msg[i]: header, content = msg[i].split(b': ', 1) headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8') pairs['Headers'] = headers content = msg[cont_id][9:] for i in range(cont_id + 1, len(msg)): if msg[i][:9] == (b' ' * 9): content += b'\n' + msg[i][9:] pairs['Content'] = content return pairs def get_attachment_content(self, ticket_id: str | int, attachment_id: str | int) -> bytes | None: r"""Get content of attachment without headers. This function is necessary to use for binary attachment, as it can contain ``\\n`` chars, which would disrupt parsing of message if :py:meth:`~Rt.get_attachment` is used. Format of message:: RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n :param ticket_id: ID of ticket :param attachment_id: ID of attachment Returns: Bytes with content of attachment or None if ticket or attachment does not exist. """ msg = typing.cast('bytes', self.__request(f'ticket/{ticket_id}/attachments/{attachment_id}/content', text_response=False)) lines = msg.split(b'\n', 3) if (len(lines) == 4) and ( self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2]) ): return None return msg[msg.find(b'\n') + 2 :] def get_user(self, user_id: str | int) -> dict[str, str] | None: """Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang * RealName * Privileged * Disabled * Gecos * EmailAddress * Password * id * Name Or these keys for external users (e.g. Requestors replying to email from RT: * RealName * Disabled * EmailAddress * Password * id * Name None is returned if user does not exist. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ msg = self.__request(f'user/{user_id}') lines = msg.split('\n') status_code = self.__get_status_code(lines[0]) if status_code is not None and status_code == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None return self.__parse_response_dict(lines) raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') def create_user(self, Name: str, EmailAddress: str, **kwargs: typing.Any) -> int | bool: """Create user (undocumented API feature). :param Name: User name (login for privileged, required) :param EmailAddress: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user or False when create fails :raises BadRequestError: When user already exists :raises InvalidUseError: When invalid fields are set """ return self.edit_user('new', Name=Name, EmailAddress=EmailAddress, **kwargs) def edit_user(self, user_id: str | int, **kwargs: typing.Any) -> int | bool: """Edit user profile (undocumented API feature). :param user_id: Identification of user by username (str) or user ID (int) :param kwargs: Other fields to edit from the following list: * Name * Password * EmailAddress * RealName * NickName * Gecos * Organization * Address1 * Address2 * City * State * Zip * Country * HomePhone * WorkPhone * MobilePhone * PagerPhone * ContactInfo * Comments * Signature * Lang * EmailEncoding * WebEncoding * ExternalContactInfoId * ContactInfoSystem * ExternalAuthId * AuthSystem * Privileged * Disabled :returns: ID of edited user or False when edit fails :raises BadRequestError: When user does not exist :raises InvalidUseError: When invalid fields are set """ valid_fields = { 'name', 'password', 'emailaddress', 'realname', 'nickname', 'gecos', 'organization', 'address1', 'address2', 'city', 'state', 'zip', 'country', 'homephone', 'workphone', 'mobilephone', 'pagerphone', 'contactinfo', 'comments', 'signature', 'lang', 'emailencoding', 'webencoding', 'externalcontactinfoid', 'contactinfosystem', 'externalauthid', 'authsystem', 'privileged', 'disabled', } used_fields = {x.lower() for x in kwargs.keys()} if not used_fields <= valid_fields: invalid_fields = ', '.join(list(used_fields - valid_fields)) raise InvalidUseError(f'Unsupported names of fields: {invalid_fields}.') if isinstance(user_id, str) and not user_id.isnumeric(): _user = self.get_user(user_id) if _user is None: raise NotFoundError(f'User "{user_id}" does not exist.') user_id = _user['id'].split('/', 1)[1] post_data = f'id: user/{user_id}\n' for key, val in kwargs.items(): post_data += f'{key}: {val}\n' msg = self.__request('edit', post_data={'content': post_data}) msgs = msg.split('\n') if (self.__get_status_code(msg) == 200) and (len(msgs) > 2): match = self.RE_PATTERNS['user_pattern'].match(msgs[2]) if match: return int(match.group(1)) return False def get_queue(self, queue_id: str | int) -> dict[str, str] | None: """Get queue details. :param queue_id: Identification of queue by name (str) or queue ID (int) :returns: Queue details as strings in dictionary with these keys if queue exists (otherwise None): * id * Name * Description * CorrespondAddress * CommentAddress * InitialPriority * FinalPriority * DefaultDueIn :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ msg = self.__request(f'queue/{queue_id}') lines = msg.split('\n') status_code = self.__get_status_code(lines[0]) if status_code is not None and status_code == 200: if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None return self.__parse_response_dict(lines) raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') def edit_queue(self, queue_id: str | int, **kwargs: typing.Any) -> str | bool: """Edit queue (undocumented API feature). :param queue_id: Identification of queue by name (str) or ID (int) :param kwargs: Other fields to edit from the following list: * Name * Description * CorrespondAddress * CommentAddress * InitialPriority * FinalPriority * DefaultDueIn :returns: ID or name of edited queue or False when edit fails :raises BadRequestError: When queue does not exist :raises InvalidUseError: When invalid fields are set """ valid_fields = {'name', 'description', 'correspondaddress', 'commentaddress', 'initialpriority', 'finalpriority', 'defaultduein'} used_fields = {x.lower() for x in kwargs.keys()} if not used_fields <= valid_fields: invalid_fields = ', '.join(list(used_fields - valid_fields)) raise InvalidUseError(f'Unsupported names of fields: {invalid_fields}.') post_data = f'id: queue/{queue_id}\n' for key, val in kwargs.items(): post_data += f'{key}: {val}\n' msg = self.__request('edit', post_data={'content': post_data}) msgs = msg.split('\n') if (self.__get_status_code(msg) == 200) and (len(msgs) > 2): match = self.RE_PATTERNS['queue_pattern'].match(msgs[2]) if match: return match.group(1) return False def create_queue(self, Name: str, **kwargs: typing.Any) -> int: """Create queue (undocumented API feature). :param Name: Queue name (required) :param kwargs: Optional fields to set (see edit_queue) :returns: ID of new queue or False when create fails :raises BadRequestError: When queue already exists :raises InvalidUseError: When invalid fields are set """ return int(self.edit_queue('new', Name=Name, **kwargs)) def get_links(self, ticket_id: str | int) -> dict[str, list[str]] | None: """Gets the ticket links for a single ticket. :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * id * Members * MemberOf * RefersTo * ReferredToBy * DependsOn * DependedOnBy None is returned if ticket does not exist. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ msg = self.__request(f'ticket/{ticket_id}/links/show') lines = msg.split('\n') status_code = self.__get_status_code(lines[0]) if status_code is not None and status_code == 200: if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]): return None pairs = self.__parse_response_dict(lines) return {key: [link.rstrip(',') for link in links.split()] for key, links in pairs.items()} raise UnexpectedMessageFormatError(f'Received status code is {status_code} instead of 200.') def edit_ticket_links(self, ticket_id: str | int, **kwargs: typing.Any) -> bool: """Edit ticket links. .. warning:: This method is deprecated in favour of edit_link method, because there exists bug in RT 3.8 REST API causing mapping created links to ticket/1. The only drawback is that edit_link cannot process multiple links all at once. :param ticket_id: ID of ticket to edit :keyword kwargs: Other arguments possible to set: DependsOn, DependedOnBy, RefersTo, ReferredToBy, Members, MemberOf. Each value should be either ticker ID or external link. Int types are converted. Use empty string as value to delete existing link. :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ post_data = '' for key, value in kwargs.items(): post_data += f'{key}: {value}\n' msg = self.__request(f'ticket/{ticket_id}/links', post_data={'content': post_data}) state = msg.split('\n')[2] return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None def edit_link(self, ticket_id: str | int, link_name: str, link_value: str | int, delete: bool = False) -> bool: """Creates or deletes a link between the specified tickets (undocumented API feature). :param ticket_id: ID of ticket to edit :param link_name: Name of link to edit (DependsOn, DependedOnBy, RefersTo, ReferredToBy, HasMember or MemberOf) :param link_value: Either ticker ID or external link. :param delete: if True the link is deleted instead of created :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or link to delete is not found :raises InvalidUseError: When none or more then one links are specified. Also when wrong link name is used. """ valid_link_names = {'dependson', 'dependedonby', 'refersto', 'referredtoby', 'hasmember', 'memberof'} if link_name.lower() not in valid_link_names: raise InvalidUseError('Unsupported name of link.') post_data = {'rel': link_name.lower(), 'to': link_value, 'id': ticket_id, 'del': 1 if delete else 0} msg = self.__request('ticket/link', post_data=post_data) state = msg.split('\n')[2] if delete: return self.RE_PATTERNS['deleted_link_pattern'].match(state) is not None return self.RE_PATTERNS['created_link_pattern'].match(state) is not None def merge_ticket(self, ticket_id: str | int, into_id: str | int) -> bool: """Merge ticket into another (undocumented API feature). :param ticket_id: ID of ticket to be merged :param into_id: ID of destination ticket :returns: ``True`` Operation was successful ``False`` Either origin or destination ticket does not exist or user does not have ModifyTicket permission. """ msg = self.__request(f'ticket/{ticket_id}/merge/{into_id}') state = msg.split('\n')[2] return self.RE_PATTERNS['merge_successful_pattern'].match(state) is not None def take(self, ticket_id: str | int) -> bool: """Take ticket. :param ticket_id: ID of ticket to be taken :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have TakeTicket permission. """ post_data = {'content': f'Ticket: {ticket_id}\nAction: take'} msg = self.__request(f'ticket/{ticket_id}/take', post_data=post_data) return self.__get_status_code(msg) == 200 def steal(self, ticket_id: str | int) -> bool: """Steal ticket. :param ticket_id: ID of ticket to be stolen :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have StealTicket permission. """ post_data = {'content': f'Ticket: {ticket_id}\nAction: steal'} msg = self.__request(f'ticket/{ticket_id}/take', post_data=post_data) return self.__get_status_code(msg) == 200 def untake(self, ticket_id: str | int) -> bool: """Untake ticket. :param ticket_id: ID of ticket to be untaken :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not own the ticket. """ post_data = {'content': f'Ticket: {ticket_id}\nAction: untake'} msg = self.__request(f'ticket/{ticket_id}/take', post_data=post_data) return self.__get_status_code(msg) == 200 @staticmethod def split_header(line: str) -> typing.Sequence[str]: """Split a header line into field name and field value. Note that custom fields may contain colons inside the curly braces, so we need a special test for them. :param line: A message line to be split. :returns: (Field name, field value) tuple. """ match = re.match(r'^(CF\.\{.*?}): (.*)$', line) if match: return (match.group(1), match.group(2)) return line.split(': ', 1) rt-3.8.1/rt/rest2.py0000644000000000000000000040774113615410400011143 0ustar00"""Python interface to Request Tracker :term:`API`. Description of Request Tracker :term:`REST` :term:`API`: https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html """ import base64 import collections.abc import dataclasses import datetime import json import logging import re import ssl import typing from typing import Literal from urllib.parse import urljoin import httpx2 import rt.exceptions from .exceptions import AuthorizationError, InvalidUseError, NotFoundError, UnexpectedResponseError __license__ = """ Copyright (C) 2012 CZ.NIC, z.s.p.o. Copyright (c) 2015 Genome Research Ltd. Copyright (c) 2017 CERT Gouvernemental (GOVCERT.LU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ __docformat__ = 'reStructuredText en' __authors__ = [ '"Jiri Machalek" ', '"Joshua C. randall" ', '"Georges Toth" ', ] VALID_TICKET_LINK_NAMES = ('Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy') TYPE_VALID_TICKET_LINK_NAMES = Literal['Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy'] TYPE_CONTENT_TYPE = Literal['text/plain', 'text/html'] REGEX_PATTERNS = {'does_not_exist': re.compile(r"""(user|queue|resource)(?: [^does]+)? does not exist""", re.I)} @dataclasses.dataclass class Attachment: """Dataclass representing an attachment.""" file_name: str file_type: str file_content: bytes def to_dict(self) -> dict[str, str]: """Convert to a dictionary for submitting to the REST API.""" return { 'FileName': self.file_name, 'FileType': self.file_type, 'FileContent': base64.b64encode(self.file_content).decode('utf-8'), } def multipart_form_element(self) -> tuple[str, bytes, str]: """Convert to a tuple as required for multipart-form-data submission.""" return ( self.file_name, self.file_content, self.file_type, ) class Rt: r""":term:`API` for Request Tracker according to https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html. Interface is based on :term:`REST` architecture, which is based on HTTP/1.1 protocol. This module is therefore mainly sending and parsing special HTTP messages. .. warning:: You need at least version 5.0.2 of RT. .. note:: Use only ASCII LF as newline (``\\n``). Time is returned in UTC. All strings returned are encoded in UTF-8 and the same is expected as input for string values. """ def __init__( self, url: str, proxy: str | None = None, verify_cert: str | bool = True, http_auth: httpx2.Auth | None = None, token: str | None = None, http_timeout: int | None = 20, ) -> None: """API initialization. :param url: Base URL for Request Tracker API. E.g.: http://tracker.example.com/REST/2.0/ :param proxy: Proxy server (string with http://user:password@host/ syntax) :param http_auth: Specify a http authentication instance, e.g. HTTPBasicAuth(), HTTPDigestAuth(), etc. to be used for authenticating to RT :param token: Optional authentication token to be used instead of basic authentication. :param http_timeout: HTTP timeout after which a request is aborted. :raises ValueError: If the specified `url` is invalid. """ self.logger = logging.getLogger(__name__) # ensure trailing slash if not url.endswith('/'): url = f'{url}/' if not url.endswith('REST/2.0/'): raise ValueError('Invalid REST URL specified, please use a form of https://example.com/REST/2.0/') self.url = url self.base_url = url.split('REST/2.0/', 1)[0] if isinstance(verify_cert, bool): ssl_verify: ssl.SSLContext | bool = verify_cert elif isinstance(verify_cert, str): ssl_verify = ssl.create_default_context(cafile=verify_cert) else: ssl_verify = True self.session = httpx2.Client(timeout=http_timeout, verify=ssl_verify, proxy=proxy, auth=http_auth) if token is not None: # pragma: no cover # no way to add tests for this with the current docker image self.session.headers['Authorization'] = f'token {token}' def __debug_response(self, response: httpx2.Response) -> None: """Output debug information for a given HTTP response.""" response.request.read() self.logger.debug('### %s', datetime.datetime.now(tz=datetime.timezone.utc).isoformat()) self.logger.debug('Request URL: %s', response.request.url) self.logger.debug('Request method: %s', response.request.method) self.logger.debug('Request headers: %s', response.request.headers) self.logger.debug('Request body: %s', response.request.content.decode('utf8', 'ignore')) self.logger.debug('Response status code: %s', str(response.status_code)) self.logger.debug('Response content:') self.logger.debug(response.content.decode(errors='ignore')) def __request( self, selector: str, get_params: dict[str, typing.Any] | None = None, json_data: dict[str, typing.Any] | list[typing.Any] | None = None, post_data: dict[str, typing.Any] | None = None, attachments: typing.Sequence[Attachment] | None = None, ) -> dict[str, typing.Any] | list[str]: """General request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param get_params: Parameters to add for a GET request. :param json_data: JSON request to send to the API. :param post_data: Dictionary with POST method fields :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: dict or list depending on request :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) if not attachments: if json_data: response = self.session.post(url, json=json_data) elif post_data: response = self.session.post(url, data=post_data) else: response = self.session.get(url, params=get_params) else: fields: list[tuple[str, typing.Any]] = [('Attachments', attachment.multipart_form_element()) for attachment in attachments] response = self.session.post(url, files=fields, data={'JSON': json.dumps(json_data)}) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc def __request_put( self, selector: str, json_data: dict[str, typing.Any] | None = None, ) -> list[str]: """PUT request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :returns: list :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = self.session.put(url, json=json_data, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc def __request_delete( self, selector: str, ) -> dict[str, str]: """DELETE request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :returns: dict :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = self.session.delete(url, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc def __paged_request( self, selector: str, json_data: list[dict[str, typing.Any]] | dict[str, typing.Any] | None = None, params: dict[str, typing.Any] | None = None, page: int = 1, per_page: int = 20, recurse: bool = True, ) -> typing.Iterator[dict[str, typing.Any]]: """Request using pagination for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :param page: The page number to get. :param per_page: Number of results per page to get. :param recurse: Set on the initial call in order to retrieve all pages recursively. :returns: dict :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ if params: params['page'] = page params['per_page'] = per_page else: params = {'page': page, 'per_page': per_page} try: url = str(urljoin(self.url, selector)) method = 'get' if json_data is not None: method = 'post' response = self.session.request(method, url, json=json_data, params=params) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError: # pragma: no cover # replace errors - we need decoded content just to check for error codes in __check_response result = response.content.decode('utf-8', 'replace') if not isinstance(result, dict) and 'items' in result: raise UnexpectedResponseError('Server returned an unexpected result') if result.get('pages', None) is None and result['count'] == 0: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) raise NotFoundError yield from result['items'] if recurse and result.get('pages', None) is not None and result['pages'] > result['page']: for _page in range(2, result['pages'] + 1): yield from self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ) elif recurse and result.get('pages', None) is None: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) _page = result['page'] while True: _page += 1 try: yield from self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ) except NotFoundError: break except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc @staticmethod def __check_response(response: httpx2.Response) -> None: """Search general errors in server response and raise exceptions when found. :param response: Response from HTTP request. :raises BadRequestError: If the server returned an HTTP/400 error. :raises AuthorizationError: Credentials are invalid or missing. :raises NotFoundError: Resource was not found. :raises UnexpectedResponseError: Server returned an unexpected status code. """ if response.status_code == 400: # pragma: no cover try: ret = response.json() except json.JSONDecodeError: ret = 'Bad request' if isinstance(ret, dict): raise rt.exceptions.BadRequestError(ret['message']) raise rt.exceptions.BadRequestError(ret) if response.status_code == 401: # pragma: no cover raise AuthorizationError('Server could not verify that you are authorized to access the requested document.') if response.status_code == 404: raise NotFoundError('No such resource found.') if response.status_code not in (200, 201): raise UnexpectedResponseError( f'Received status code {response.status_code} instead of 200.', status_code=response.status_code, response_message=response.text, ) def __get_url(self, url: str) -> dict[str, typing.Any]: """Call a URL as specified in the returned JSON of an API operation.""" url_ = url.split('/REST/2.0/', 1)[1] res = self.__request(url_) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def new_correspondence(self, queue: str | object | None = None) -> typing.Iterator[dict[str, typing.Any]]: """Obtains tickets changed by other users than the system one. :param queue: Queue where to search :returns: Iterator of tickets which were last updated by another user than the system one, ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`. """ return self.search(queue=queue, order='-LastUpdated') def last_updated(self, since: str, queue: str | None = None) -> typing.Iterator[dict[str, typing.Any]]: """Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :param queue: Queue where to search :returns: Iterator of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each ticket is a dictionary, the same as in :py:meth:`~Rt.get_ticket`. :raises InvalidUseError: If the specified date is of an unsupported format. """ if not self.__validate_date(since): raise InvalidUseError(f'Invalid date specified - "{since}"') return self.search(queue=queue, order='-LastUpdated', LastUpdated__gt=since) @classmethod def __validate_date(cls, _date: str) -> bool: """Check whether the specified date is in the supported format.""" if m := re.match(r'(\d{4})-(\d{2})-(\d{2})', _date): try: year = int(m.group(1)) month = int(m.group(2)) day = int(m.group(3)) except ValueError: return False if 1970 < year < 2100 and 1 <= month <= 12 and 1 <= day <= 31: return True return False def search( self, queue: str | object | None = None, order: str | None = None, raw_query: str | None = None, query_format: str | list[str] | dict[str, str] = 'l', **kwargs: typing.Any, ) -> typing.Iterator[dict[str, typing.Any]]: r"""Search arbitrary needles in given fields and queue. Example:: >>> tracker = Rt('http://tracker.example.com/REST/2.0/', 'rt-username', 'top-secret') >>> tickets = list(tracker.search(CF_Domain='example.com', Subject__like='warning')) >>> tickets = list(tracker.search(queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'")) :param queue: Queue where to search. If you wish to search across all of your queues, pass None as the argument. :param order: Name of field sorting result list, for descending order put - before the field name. E.g. -Created will put the newest tickets at the beginning :param raw_query: A raw query to provide to RT if you know what you are doing. You may still pass Queue and order kwargs, so use these instead of including them in the raw query. You can refer to the RT query builder. If passing raw_query, all other \*\*kwargs will be ignored. :param query_format: Format of the query: - i: only *id* fields are populated - s: only *id* and *subject* fields are populated - l: multi-line format, all fields are populated - [field1, field2]: list of fields to be populated :param kwargs: Other arguments possible to set if not passing raw_query: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. To alter lookup operators you can append one of the following endings to each keyword: __exact for operator = (default) __notexact for operator != __gt for operator > __lt for operator < __like for operator LIKE __notlike for operator NOT LIKE Setting values to keywords constrain search result to the tickets satisfying all of them. :returns: Iterator over matching tickets. Each ticket is the same dictionary as in :py:meth:`~Rt.get_ticket`. :raises: UnexpectedMessageFormatError: Unexpected format of returned message. InvalidQueryError: If raw query is malformed """ get_params = {} query = [] url = 'tickets' if queue is not None: query.append(f"Queue='{queue}'") if not raw_query: operators_map = { 'gt': '>', 'lt': '<', 'exact': '=', 'notexact': '!=', 'like': ' LIKE ', 'notlike': ' NOT LIKE ', } for _key, value in kwargs.items(): key = _key op = '=' key_parts = key.split('__') if len(key_parts) > 1: key = '__'.join(key_parts[:-1]) op = operators_map.get(key_parts[-1], '=') if key[:3] != 'CF_': query.append(f"{key}{op}'{value}'") else: query.append(f"""CF.{{{key[3:]}}}'{op}'{value}\'""") else: query.append(raw_query) get_params['query'] = ' AND '.join('(' + part + ')' for part in query) if order: if order.startswith('-'): get_params['orderby'] = order[1:] get_params['order'] = 'DESC' else: get_params['orderby'] = order if isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif isinstance(query_format, dict): get_params = {**get_params, **query_format} elif query_format == 'l': get_params['fields'] = ( 'Owner,Status,Created,Subject,Queue,CustomFields,Requestor,Cc,AdminCc,Started,Created,TimeEstimated,Due,Type,InitialPriority,Priority,TimeLeft,LastUpdated' ) get_params['fields[Queue]'] = 'Name' elif query_format == 's': get_params['fields'] = 'Subject' yield from self.__paged_request(url, params=get_params) def get_ticket(self, ticket_id: str | int, query_format: dict[str, str] | None = None) -> dict[str, typing.Any]: """Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :param query_format: Returned fields to be populated :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys (when query_format is None): * id * numerical_id * Queue * Owner * Creator * Subject * Status * Priority * InitialPriority * FinalPriority * Requestors * Cc * AdminCc * Created * Starts * Started * Due * Resolved * Told * TimeEstimated * TimeWorked * TimeLeft :raises UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If there is no ticket with the specified ticket_id. """ if not query_format: query_format = {} res = self.__request(f'ticket/{ticket_id}', get_params={'fields[Queue]': 'Name', **query_format}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def create_ticket( self, queue: str, content_type: TYPE_CONTENT_TYPE = 'text/plain', subject: str | None = None, content: str | None = None, attachments: typing.Sequence[Attachment] | None = None, **kwargs: typing.Any, ) -> int: """Create new ticket and set given parameters. Example of message sent to ``http://tracker.example.com/REST/2.0/ticket/new``:: { "Queue": "General", "Subject": "Ticket created through REST API", "Owner": "Nobody", "Requestor": "somebody@example.com", "Cc": "user2@example.com", "CustomRoles": {"My Role": "staff1@example.com"}, "Content": "Lorem Ipsum", "CustomFields": {"Severity": "Low"} } :param queue: Queue where to create ticket :param content_type: Content-type of the Content parameter; can be either text/plain or text/html. :param subject: Optional subject for the ticket. :param content: Optional content of the ticket. Must be specified unless attachments are specified. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :param kwargs: Other arguments possible to set: Requestor, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due :returns: ID of new ticket :raises ValueError: If the `content_type` is not of a supported format. """ if content_type not in ('text/plain', 'text/html'): # pragma: no cover raise ValueError('Invalid content-type specified.') ticket_data: dict[str, typing.Any] = {'Queue': queue} if subject is not None: ticket_data['Subject'] = subject if content is not None: ticket_data['Content'] = content ticket_data['ContentType'] = content_type for k, v in kwargs.items(): ticket_data[k] = v res = self.__request('ticket', json_data=ticket_data, attachments=attachments) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) def edit_ticket(self, ticket_id: str | int, **kwargs: typing.Any) -> bool: """Edit ticket values. :param ticket_id: ID of ticket to edit :param kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields can be specified as dict: CustomFields = {"Severity": "Low"} :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ msg = self.__request_put(f'ticket/{ticket_id}', json_data=kwargs) self.logger.debug(msg) if not isinstance(msg, list): # pragma: no cover raise UnexpectedResponseError(str(msg)) if not msg: return True for k in msg: if REGEX_PATTERNS['does_not_exist'].search(k): raise rt.exceptions.NotFoundError(k) return bool(msg[0]) def get_ticket_history(self, ticket_id: str | int) -> list[dict[str, typing.Any]]: """Get set of short history items. :param ticket_id: ID of ticket :returns: List of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). Returns an empty list if ticket does not exist. """ transactions = self.__paged_request( f'ticket/{ticket_id}/history', params={ 'fields': 'Type,Creator,Created,Description,_hyperlinks', 'fields[Creator]': 'id,Name,RealName,EmailAddress', }, ) return list(transactions) def get_transaction(self, transaction_id: str | int) -> dict[str, typing.Any]: """Get a transaction. :param transaction_id: ID of transaction :returns: Return a single transaction. """ res = self.__request(f'transaction/{transaction_id}', get_params={'fields': 'Description'}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def __correspond( self, ticket_id: str | int, content: str = '', action: Literal['correspond', 'comment'] = 'correspond', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Sequence[Attachment] | None = None, ) -> list[str]: """Sends out the correspondence. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message :param action: correspond or comment :param content_type: Content type of email message, defaults to text/plain. Alternative is text/html. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: List of messages returned by the backend related to the executed action. :raises BadRequestError: When ticket does not exist :raises InvalidUseError: If the `action` parameter is invalid :raises UnexpectedResponseError: If the response from RT is not as expected """ if action not in ('correspond', 'comment'): # pragma: no cover raise InvalidUseError('action must be either "correspond" or "comment"') post_data: dict[str, typing.Any] = { 'Content': content, 'ContentType': content_type, } # Adding a one-shot cc/bcc is not supported by RT5.0.2 # if cc: # post_data['Cc'] = cc # noqa: ERA001 # # if bcc: # post_data['Bcc'] = bcc # noqa: ERA001 res = self.__request(f'ticket/{ticket_id}/{action}', json_data=post_data, attachments=attachments) if not isinstance(res, list): # pragma: no cover raise UnexpectedResponseError(str(res)) self.logger.debug(res) return res def reply( self, ticket_id: str | int, content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Sequence[Attachment] | None = None, ) -> bool: """Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message (text/plain or text/html) :param content_type: Content type of email message, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__correspond(ticket_id, content, 'correspond', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) def delete_ticket(self, ticket_id: str | int) -> None: """Mark a ticket as deleted. :param ticket_id: ID of ticket :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: self.__request_delete(f'ticket/{ticket_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover def comment( self, ticket_id: str | int, content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Sequence[Attachment] | None = None, ) -> bool: """Adds comment to the given ticket. :param ticket_id: ID of ticket to which comment belongs :param content: Content of comment :param content_type: Content type of comment, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__correspond(ticket_id, content, 'comment', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) def get_attachments( self, ticket_id: str | int, query_filter: list[dict[str, str]] | None = None, query_format: str | list[str] | dict[str, str] | None = None, ) -> typing.Sequence[dict[str, str]]: """Get attachment list for a given ticket. Example of a return result: .. code-block:: json [ { "id": "17", "Filename": "README.rst", "ContentLength": "3578", "type": "attachment", "ContentType": "test/plain", "_url": "http://localhost:8080/REST/2.0/attachment/17" } ] :param ticket_id: ID of ticket :param query_filter: JSON search filter, defaults to "filename is not empty" :param query_format: Returned fields to be populated :returns: List of tuples for attachments belonging to given ticket. Tuple format: (id, name, content_type, size) Returns None if ticket does not exist. """ attachments = [] if query_filter is None: query_filter = [{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}] get_params = {'fields': 'Filename,ContentType,ContentLength'} if isinstance(query_format, dict): get_params = {**get_params, **query_format} elif isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif isinstance(query_format, str): get_params['fields'] = query_format for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=query_filter, params=get_params, ): attachments.append(item) return attachments def get_attachments_ids( self, ticket_id: str | int, query_filter: list[dict[str, str]] | None = None, ) -> list[int]: """Get IDs of attachments for given ticket. :param ticket_id: ID of ticket :param query_filter: JSON search filter, defaults to "filename is not empty" :returns: List of IDs (type int) of attachments belonging to given ticket. Returns an empty list if ticket does not exist. """ attachments = [] if query_filter is None: query_filter = [{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}] for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=query_filter, ): attachments.append(int(item['id'])) return attachments def get_attachment(self, attachment_id: str | int) -> dict[str, typing.Any]: """Get attachment. :param attachment_id: ID of attachment to fetch :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (base64 encoded string) * Headers * MessageId * ContentEncoding * id * Subject All these fields are strings, just 'Headers' holds another dictionary with attachment headers as strings e.g.: * Delivered-To * From * Return-Path * Content-Length * To * X-Seznam-User * X-QM-Mark * Domainkey-Signature * RT-Message-ID * X-RT-Incoming-Encryption * X-Original-To * Message-ID * X-Spam-Status * In-Reply-To * Date * Received * X-Country * X-Spam-Checker-Version * X-Abuse * MIME-Version * Content-Type * Subject Set of headers available depends on mailservers sending emails not on Request Tracker! :raises UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If attachment with specified ID does not exist. """ res = self.__request(f'attachment/{attachment_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def get_user(self, user_id: int | str) -> dict[str, typing.Any]: """Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang * RealName * Privileged * Disabled * Gecos * EmailAddress * Password * id * Name Or these keys for external users (e.g. Requestors) replying to email from RT: * RealName * Disabled * EmailAddress * Password * id * Name :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: If the user does not exist. """ res = self.__request(f'user/{user_id}') if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def user_exists(self, user_id: int | str, privileged: bool = True) -> bool: """Check if a given user_id exists. :parameter user_id: User ID to lookup. :parameter privileged: If set to True, only return True if the user_id was found and is privileged. :returns: bool: True on success, else False. """ try: user_dict = self.get_user(user_id) if not privileged or (privileged and user_dict.get('Privileged', '0') == 1): return True except rt.exceptions.NotFoundError: return False return False def create_user(self, user_name: str, email_address: str, **kwargs: typing.Any) -> str: """Create user. :param user_name: Username (login for privileged, required) :param email_address: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user or False when create fails :raises BadRequestError: When user already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Password', 'EmailAddress', 'RealName', 'Nickname', 'Gecos', 'Organization', 'Address1', 'Address2', 'City', 'State', 'Zip', 'Country', 'HomePhone', 'WorkPhone', 'MobilePhone', 'PagerPhone', 'ContactInfo', 'Comments', 'Signature', 'Lang', 'EmailEncoding', 'WebEncoding', 'ExternalContactInfoId', 'ContactInfoSystem', 'ExternalAuthId', 'AuthSystem', 'Privileged', 'Disabled', 'CustomFields', } invalid_fields = [] post_data = { 'Name': user_name, 'EmailAddress': email_address, } for k, v in kwargs.items(): if k not in valid_fields: invalid_fields.append(k) else: post_data[k] = v if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = self.__request('user', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res['id'] def edit_user(self, user_id: str | int, **kwargs: typing.Any) -> list[str]: """Edit user profile. :param user_id: Identification of user by username (str) or user ID (int) :param kwargs: Other fields to edit from the following list: * Name * Password * EmailAddress * RealName * NickName * Gecos * Organization * Address1 * Address2 * City * State * Zip * Country * HomePhone * WorkPhone * MobilePhone * PagerPhone * ContactInfo * Comments * Signature * Lang * EmailEncoding * WebEncoding * ExternalContactInfoId * ContactInfoSystem * ExternalAuthId * AuthSystem * Privileged * Disabled :returns: List of status messages :raises BadRequestError: When user does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Password', 'EmailAddress', 'RealName', 'Nickname', 'Gecos', 'Organization', 'Address1', 'Address2', 'City', 'State', 'Zip', 'Country', 'HomePhone', 'WorkPhone', 'MobilePhone', 'PagerPhone', 'ContactInfo', 'Comments', 'Signature', 'Lang', 'EmailEncoding', 'WebEncoding', 'ExternalContactInfoId', 'ContactInfoSystem', 'ExternalAuthId', 'AuthSystem', 'Privileged', 'Disabled', 'CustomFields', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = self.__request_put(f'user/{user_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret def delete_user(self, user_id: str | int) -> None: """Disable a user. :param user_id: Identification of a user by name (str) or ID (int) :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = self.__request_delete(f'user/{user_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover def get_queue(self, queue_id: str | int) -> dict[str, typing.Any]: """Get queue details. Example of a return result: .. code-block:: json { "LastUpdatedBy": { "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user", "id": "RT_System" }, "LastUpdated": "2022-03-06T04:53:38Z", "AdminCc": [], "SortOrder": "0", "CorrespondAddress": "", "Creator": { "id": "RT_System", "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user" }, "Lifecycle": "default", "Cc": [], "Created": "2022-03-06T04:53:38Z", "_hyperlinks": [ { "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "id": 1, "ref": "self" }, { "ref": "history", "_url": "http://localhost:8080/REST/2.0/queue/1/history" }, { "ref": "create", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket?Queue=1" } ], "SLADisabled": "1", "Name": "General", "TicketCustomFields": [], "Disabled": "0", "TicketTransactionCustomFields": [], "CustomFields": [], "Description": "The default queue", "CommentAddress": "", "id": 1 } :param queue_id: Identification of queue by name (str) or queue ID (int) :returns: Queue details as a dictionary :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: In case the queue does not exist """ res = self.__request(f'queue/{queue_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res def get_all_queues(self, include_disabled: bool = False) -> list[dict[str, typing.Any]]: """Return a list of all queues. Example of a return result: .. code-block:: json [ { "InitialPriority": "", "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "Name": "General", "DefaultDueIn": "", "Description": "The default queue", "CorrespondAddress": "", "CommentAddress": "", "id": "1", "FinalPriority": "" } ] :param include_disabled: Set to True to also return disabled queues. :returns: Returns a list of dictionaries containing basic information on all queues. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ params = { 'fields': 'Name,Description,CorrespondAddress,CommentAddress,InitialPriority,FinalPriority,DefaultDueIn', 'find_disabled_rows': int(include_disabled), } queues = self.__paged_request('queues/all', params=params) return list(queues) def edit_queue(self, queue_id: str | int, **kwargs: typing.Any) -> list[str]: """Edit queue. :param queue_id: Identification of queue by name (str) or ID (int) :param kwargs: Other fields to edit from the following list: * Name * Description * CorrespondAddress * CommentAddress * Disabled * SLADisabled * Lifecycle * SortOrder :returns: List of status messages :raises BadRequestError: When queue does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = self.__request_put(f'queue/{queue_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret def create_queue(self, name: str, **kwargs: typing.Any) -> int: """Create queue. :param name: Queue name (required) :param kwargs: Optional fields to set (see edit_queue) :returns: ID of new queue or False when create fails :raises BadRequestError: When queue already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {'Name': name} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = self.__request('queue', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) def delete_queue(self, queue_id: str | int) -> None: """Disable a queue. :param queue_id: Identification of queue by name (str) or ID (int) :returns: ID or name of edited queue or False when edit fails :raises BadRequestError: When queue does not exist :raises NotFoundError: If the queue does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = self.__request_delete(f'queue/{queue_id}') except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover def get_links(self, ticket_id: str | int) -> list[dict[str, str]]: """Gets the ticket links for a single ticket. Example of a return result: .. code-block:: json [ { "id": "13", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket/13", "ref": "depends-on" } ] :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * depends-on * depended-on-by * parent * child * refers-to * referred-to-by :raises NotFoundError: If there is no ticket with the specified ticket_id. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ ticket = self.get_ticket(ticket_id) return [link for link in ticket['_hyperlinks'] if link.get('type', '') == 'ticket' and link['ref'] != 'self'] def edit_link( self, ticket_id: str | int, link_name: TYPE_VALID_TICKET_LINK_NAMES, link_value: str | int, delete: bool = False, ) -> bool: """Creates or deletes a link between the specified tickets. :param ticket_id: ID of ticket to edit :param link_name: Name of link to edit ('Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy') :param link_value: Either ticker ID or external link. :param delete: if True the link is deleted instead of created :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or link to delete is not found :raises InvalidUseError: When none or more than one link is specified. Also, when a wrong link name is used or when trying to link to a deleted ticket. """ if link_name not in VALID_TICKET_LINK_NAMES: raise InvalidUseError(f'Unsupported link name. Use one of "{", ".join(VALID_TICKET_LINK_NAMES)}".') if delete: json_data = {f'Delete{link_name}': link_value} else: json_data = {f'Add{link_name}': link_value} msg = self.__request_put(f'ticket/{ticket_id}', json_data=json_data) if msg and isinstance(msg, list): if msg[0].startswith("Couldn't resolve"): raise NotFoundError(msg[0]) if 'not allowed' in msg[0]: raise InvalidUseError(msg[0]) return True def merge_ticket(self, ticket_id: str | int, into_id: str | int) -> bool: """Merge ticket into another. :param ticket_id: ID of ticket to be merged :param into_id: ID of destination ticket :returns: ``True`` Operation was successful ``False`` Either origin or destination ticket does not exist or user does not have ModifyTicket permission. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}', json_data={'MergeInto': into_id}) if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower() == 'merge successful' def take(self, ticket_id: str | int) -> bool: """Take ticket. :param ticket_id: ID of ticket to be taken :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have TakeTicket permission. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}/take') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') def untake(self, ticket_id: str | int) -> bool: """Untake ticket. :param ticket_id: ID of ticket to be untaken :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not own the ticket. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}/untake') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') def steal(self, ticket_id: str | int) -> bool: """Steal ticket. :param ticket_id: ID of ticket to be stolen :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have StealTicket permission. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = self.__request_put(f'ticket/{ticket_id}/steal') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') def get_catalog(self, catalog_id: str | int) -> dict[str, typing.Any]: """ Get catalog. :param catalog_id: Catalog ID. :return: Catalog. id: int Lifecycle: str Disabled: str _hyperlinks: list[dict[dict[str, str | int]]] LastUpdated: str LastUpdatedBy: dict[str, str] Created: str Creator: dict[str, str] Description: str Name: str Contact: list[str, str] HeldBy: list[str, str] """ response = self.__request(f'catalog/{catalog_id}') self.logger.debug(str(response)) if not isinstance(response, dict): raise UnexpectedResponseError(str(response)) return response def get_asset(self, asset_id: str | int, query_format: dict[str, str] | None = None) -> dict[str, typing.Any]: """ Get asset. :param asset_id: Asset ID. :param query_format: Returned fields to be populated. :return: Asset (when `query_format` is `None`). id: int Lifecycle: str Disabled: str _hyperlinks: list[dict[dict[str, str | int]]] LastUpdated: str LastUpdatedBy: dict[str, str] Created: str Creator: dict[str, str] Description: str Name: str Contact: list[str, str] HeldBy: list[str, str] Catalog: dict[str, str] Status: str Owner: dict[str, str] CustomFields: list[dict[str, typing.Any]] """ if not query_format: query_format = {} response = self.__request(f'asset/{asset_id}', get_params=query_format) self.logger.debug(str(response)) if not isinstance(response, dict): raise UnexpectedResponseError(str(response)) return response def create_asset(self, name: str, catalog: str | int, **kwargs: typing.Any) -> int: """ Create a new asset in a catalog. :param name: Asset name. :param catalog: Catalog name or ID. :param kwargs: Name, Description, Status, CustomFields, RefersTo, etc. :return: ID of the asset. """ response = self.__request('asset', json_data={'Name': name, 'Catalog': catalog, **kwargs}) self.logger.debug(str(response)) if not isinstance(response, dict): raise UnexpectedResponseError(str(response)) return int(response['id']) def edit_asset(self, asset_id: str | int, **kwargs: typing.Any) -> bool: """ Edit an existing asset. :param asset_id: Asset ID. :param kwargs: Name, Description, Status, CustomFields, RefersTo, etc. :return: ``True`` Operation was successful ``False`` Failed (status code != 200) """ response = self.__request_put(f'asset/{asset_id}', kwargs) self.logger.debug(str(response)) return isinstance(response, list) def search_assets( self, catalog_id: str | int | None = None, search_params: list[dict[str, typing.Any]] | None = None, query_format: str | list[str] | dict[str, str] | None = None, ) -> typing.Iterator[dict[str, typing.Any]]: """ Search assets in a catalog. Example:: >>> client = Rt(...) >>> client.search_assets(1, [{"field": "Name", "value": "NameOfMyAsset"}], "Owner,Status") >>> client.search_assets(1, [{"field": "Name", "value": "NameOfMyAsset"}], ["Owner", "Status"]) >>> client.search_assets(1, [{"field": "Name", "value": "NameOfMyAsset"}], {"fields": "Owner,Status", "fields[Owner]": "id,Name"}) :param catalog_id: Catalog ID. Use `None` to search all catalogs. :param search_params: Params used to filter the results. field: str value: str | int operator: Literal[">", "<", "=", "!=", "LIKE", "NOT LIKE", ">=", "<="] | None :param query_format: Returned fields to be populated. :return: Found assets. The following is returned by default (when `query_format` is `None`) { 'Description': '', 'id': '1', '_url': 'http://localhost:8080/REST/2.0/asset/1', 'Owner': {'_url': 'http://localhost:8080/REST/2.0/user/Nobody', 'id': 'Nobody', 'type': 'user'}, 'Status': 'new', 'type': 'asset' } """ if not search_params: search_params = [] if catalog_id: search_params.append({'field': 'Catalog', 'value': catalog_id, 'operator': '='}) else: search_params.append({'field': 'Catalog', 'value': '%', 'operator': 'LIKE'}) get_params = {'fields': 'Owner,Description,Status'} if isinstance(query_format, dict): get_params = {**get_params, **query_format} elif isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif isinstance(query_format, str): get_params['fields'] = query_format yield from self.__paged_request('assets', json_data=search_params, params=get_params) def get_asset_history(self, asset_id: str | int) -> typing.Iterator[dict[str, typing.Any]]: """ Get asset history. :param asset_id: Asset ID. :return: History - transactions. Type: str type: str _url: str Creator: dict[str, str | int] Created: str Description: str _hyperlinks: list[dict[str, int | str]] id: str """ yield from self.__paged_request( f'asset/{asset_id}/history', params={ 'fields': 'Type,Creator,Created,Description,_hyperlinks', 'fields[Creator]': 'id,Name,RealName,EmailAddress', }, ) class AsyncRt: r""":term:`API` for Request Tracker according to https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html. Interface is based on :term:`REST` architecture, which is based on HTTP/1.1 protocol. This module is therefore mainly sending and parsing special HTTP messages. .. warning:: You need at least version 5.0.2 of RT. .. note:: Use only ASCII LF as newline (``\\n``). Time is returned in UTC. All strings returned are encoded in UTF-8 and the same is expected as input for string values. """ def __init__( self, url: str, proxy: str | None = None, verify_cert: str | bool = True, http_auth: httpx2.Auth | None = None, token: str | None = None, http_timeout: int | None = 20, ) -> None: """API initialization. :param url: Base URL for Request Tracker API. E.g.: http://tracker.example.com/REST/2.0/ :param proxy: Proxy server (string with http://user:password@host/ syntax) :param http_auth: Specify a http authentication instance, e.g. HTTPBasicAuth(), HTTPDigestAuth(), etc. to be used for authenticating to RT :param token: Optional authentication token to be used instead of basic authentication. :param http_timeout: HTTP timeout after which a request is aborted. :raises ValueError: If the specified `url` is invalid. """ self.logger = logging.getLogger(__name__) # ensure trailing slash if not url.endswith('/'): url = f'{url}/' if not url.endswith('REST/2.0/'): raise ValueError('Invalid REST URL specified, please use a form of https://example.com/REST/2.0/') self.url = url self.base_url = url.split('REST/2.0/', 1)[0] if isinstance(verify_cert, bool): ssl_verify: ssl.SSLContext | bool = verify_cert elif isinstance(verify_cert, str): ssl_verify = ssl.create_default_context(cafile=verify_cert) else: ssl_verify = True self.session = httpx2.AsyncClient(timeout=http_timeout, verify=ssl_verify, proxy=proxy, auth=http_auth) if token is not None: # pragma: no cover # no way to add tests for this with the current docker image self.session.headers['Authorization'] = f'token {token}' def __debug_response(self, response: httpx2.Response) -> None: """Output debug information for a given HTTP response.""" response.request.read() self.logger.debug('### %s', datetime.datetime.now(tz=datetime.timezone.utc).isoformat()) self.logger.debug('Request URL: %s', response.request.url) self.logger.debug('Request method: %s', response.request.method) self.logger.debug('Request headers: %s', response.request.headers) self.logger.debug('Request body: %s', response.request.content.decode('utf8', 'ignore')) self.logger.debug('Response status code: %s', str(response.status_code)) self.logger.debug('Response content:') self.logger.debug(response.content.decode(errors='ignore')) async def __request( self, selector: str, get_params: dict[str, typing.Any] | None = None, json_data: dict[str, typing.Any] | list[typing.Any] | None = None, post_data: dict[str, typing.Any] | None = None, attachments: typing.Sequence[Attachment] | None = None, ) -> dict[str, typing.Any] | list[str]: """General request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param get_params: Parameters to add for a GET request. :param json_data: JSON request to send to the API. :param post_data: Dictionary with POST method fields :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: dict or list depending on request :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) if not attachments: if json_data: response = await self.session.post(url, json=json_data) elif post_data: response = await self.session.post(url, data=post_data) else: response = await self.session.get(url, params=get_params) else: fields: list[tuple[str, typing.Any]] = [('Attachments', attachment.multipart_form_element()) for attachment in attachments] response = await self.session.post(url, files=fields, data={'JSON': json.dumps(json_data)}) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc async def __request_put( self, selector: str, json_data: dict[str, typing.Any] | None = None, ) -> list[str]: """PUT request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :returns: list :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = await self.session.put(url, json=json_data, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc async def __request_delete(self, selector: str) -> dict[str, str]: """DELETE request for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :returns: dict :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ try: url = str(urljoin(self.url, selector)) _headers = dict(self.session.headers) _headers['Content-Type'] = 'application/json' response = await self.session.delete(url, headers=_headers) self.__debug_response(response) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError as exc: # pragma: no cover raise UnexpectedResponseError( f"""Unknown response encoding (UTF-8 does not work) - "{response.content.decode('utf-8', 'replace')}".""" ) from exc return result except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc async def __paged_request( self, selector: str, json_data: list[dict[str, typing.Any]] | dict[str, typing.Any] | None = None, params: dict[str, typing.Any] | None = None, page: int = 1, per_page: int = 20, recurse: bool = True, ) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """Request using pagination for :term:`API`. :param selector: End part of URL which completes self.url parameter set during class initialization. E.g.: ``ticket/123456/show`` :param json_data: JSON request to send to the API. :param page: The page number to get. :param per_page: Number of results per page to get. :param recurse: Set on the initial call in order to retrieve all pages recursively. :returns: collections.abc.AsyncIterator[typing.Dict[str, typing.Any]] :raises AuthorizationError: In case that request is called without previous login or login attempt failed. :raises ConnectionError: In case of connection error. """ if params: params['page'] = page params['per_page'] = per_page else: params = {'page': page, 'per_page': per_page} try: url = str(urljoin(self.url, selector)) method = 'get' if json_data is not None: method = 'post' response = await self.session.request(method, url, json=json_data, params=params) self.__check_response(response) try: result = response.json() except LookupError as exc: # pragma: no cover raise UnexpectedResponseError(f'Unknown response encoding: {response.encoding}.') from exc except UnicodeError: # pragma: no cover # replace errors - we need decoded content just to check for error codes in __check_response result = response.content.decode('utf-8', 'replace') if not isinstance(result, dict) and 'items' in result: raise UnexpectedResponseError('Server returned an unexpected result') if result.get('pages', None) is None and result['count'] == 0: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) raise NotFoundError for item in result['items']: yield item if recurse and result.get('pages', None) is not None and result['pages'] > result['page']: for _page in range(2, result['pages'] + 1): async for item in self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ): yield item elif recurse and result.get('pages', None) is None: # no more results found, exit here # (workaround for the >=RT5.0.5 undefined pages variable for non-superusers) _page = result['page'] while True: _page += 1 try: async for item in self.__paged_request( selector, json_data=json_data, page=_page, per_page=result['per_page'], params=params, recurse=False ): yield item except NotFoundError: break except httpx2.ConnectError as exc: # pragma: no cover raise ConnectionError('Connection error', exc) from exc except httpx2.TransportError as exc: # pragma: no cover raise ConnectionError('Transport error', exc) from exc @staticmethod def __check_response(response: httpx2.Response) -> None: """Search general errors in server response and raise exceptions when found. :param response: Response from HTTP request. :raises BadRequestError: If the server returned an HTTP/400 error. :raises AuthorizationError: Credentials are invalid or missing. :raises NotFoundError: Resource was not found. :raises UnexpectedResponseError: Server returned an unexpected status code. """ if response.status_code == 400: # pragma: no cover try: ret = response.json() except json.JSONDecodeError: ret = 'Bad request' if isinstance(ret, dict): raise rt.exceptions.BadRequestError(ret['message']) raise rt.exceptions.BadRequestError(ret) if response.status_code == 401: # pragma: no cover raise AuthorizationError('Server could not verify that you are authorized to access the requested document.') if response.status_code == 404: raise NotFoundError('No such resource found.') if response.status_code not in (200, 201): raise UnexpectedResponseError( f'Received status code {response.status_code} instead of 200.', status_code=response.status_code, response_message=response.text, ) async def __get_url(self, url: str) -> dict[str, typing.Any]: """Call a URL as specified in the returned JSON of an API operation.""" url_ = url.split('/REST/2.0/', 1)[1] res = await self.__request(url_) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def new_correspondence(self, queue: str | object | None = None) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """Obtains tickets changed by other users than the system one. :param queue: Queue where to search :returns: Iterator of tickets which were last updated by another user than the system one, ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in :py:meth:`~Rt.get_ticket`. collections.abc.AsyncIterator[dict[str, typing.Any]] """ return self.search(queue=queue, order='-LastUpdated') async def last_updated(self, since: str, queue: str | None = None) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """Obtains tickets changed after given date. :param since: Date as string in form '2011-02-24' :param queue: Queue where to search :returns: Iterator of tickets with LastUpdated parameter later than *since* ordered in decreasing order by LastUpdated. Each ticket is a dictionary, the same as in :py:meth:`~Rt.get_ticket`. collections.abc.AsyncIterator[dict[str, typing.Any]] :raises InvalidUseError: If the specified date is of an unsupported format. """ if not self.__validate_date(since): raise InvalidUseError(f'Invalid date specified - "{since}"') return self.search(queue=queue, order='-LastUpdated', LastUpdated__gt=since) @classmethod def __validate_date(cls, _date: str) -> bool: """Check whether the specified date is in the supported format.""" if m := re.match(r'(\d{4})-(\d{2})-(\d{2})', _date): try: year = int(m.group(1)) month = int(m.group(2)) day = int(m.group(3)) except ValueError: return False if 1970 < year < 2100 and 1 <= month <= 12 and 1 <= day <= 31: return True return False async def search( self, queue: str | object | None = None, order: str | None = None, raw_query: str | None = None, query_format: str | list[str] | dict[str, str] = 'l', **kwargs: typing.Any, ) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: r"""Search arbitrary needles in given fields and queue. Example:: >>> tracker = Rt('http://tracker.example.com/REST/2.0/', 'rt-username', 'top-secret') >>> tickets = list(tracker.search(CF_Domain='example.com', Subject__like='warning')) >>> tickets = list(tracker.search(queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'")) :param queue: Queue where to search. If you wish to search across all of your queues, pass None as the argument. :param order: Name of field sorting result list, for descending order put - before the field name. E.g. -Created will put the newest tickets at the beginning :param raw_query: A raw query to provide to RT if you know what you are doing. You may still pass Queue and order kwargs, so use these instead of including them in the raw query. You can refer to the RT query builder. If passing raw_query, all other \*\*kwargs will be ignored. :param query_format: Format of the query: - i: only *id* fields are populated - s: only *id* and *subject* fields are populated - l: multi-line format, all fields are populated - [field1, field2]: list of fields to be populated :param kwargs: Other arguments possible to set if not passing raw_query: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields CF.{} could be set with keywords CF_CustomFieldName. To alter lookup operators you can append one of the following endings to each keyword: __exact for operator = (default) __notexact for operator != __gt for operator > __lt for operator < __like for operator LIKE __notlike for operator NOT LIKE Setting values to keywords constrain search result to the tickets satisfying all of them. :returns: Iterator over matching tickets. Each ticket is the same dictionary as in :py:meth:`~Rt.get_ticket`. collections.abc.AsyncIterator[dict[str, typing.Any]] :raises: UnexpectedMessageFormatError: Unexpected format of returned message. InvalidQueryError: If raw query is malformed """ get_params = {} query = [] url = 'tickets' if queue is not None: query.append(f"Queue='{queue}'") if not raw_query: operators_map = { 'gt': '>', 'lt': '<', 'exact': '=', 'notexact': '!=', 'like': ' LIKE ', 'notlike': ' NOT LIKE ', } for _key, value in kwargs.items(): key = _key op = '=' key_parts = key.split('__') if len(key_parts) > 1: key = '__'.join(key_parts[:-1]) op = operators_map.get(key_parts[-1], '=') if key[:3] != 'CF_': query.append(f"{key}{op}'{value}'") else: query.append(f"""CF.{{{key[3:]}}}'{op}'{value}\'""") else: query.append(raw_query) get_params['query'] = ' AND '.join('(' + part + ')' for part in query) if order: if order.startswith('-'): get_params['orderby'] = order[1:] get_params['order'] = 'DESC' else: get_params['orderby'] = order if isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif isinstance(query_format, dict): get_params = {**get_params, **query_format} elif query_format == 'l': get_params['fields'] = ( 'Owner,Status,Created,Subject,Queue,CustomFields,Requestor,Cc,AdminCc,Started,Created,TimeEstimated,Due,Type,InitialPriority,Priority,TimeLeft,LastUpdated' ) get_params['fields[Queue]'] = 'Name' elif query_format == 's': get_params['fields'] = 'Subject' async for item in self.__paged_request(url, params=get_params): yield item async def get_ticket(self, ticket_id: str | int, query_format: dict[str, str] | None = None) -> dict[str, typing.Any]: """Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :param query_format: Returned fields to be populated :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys (when query_format is None): * id * numerical_id * Queue * Owner * Creator * Subject * Status * Priority * InitialPriority * FinalPriority * Requestors * Cc * AdminCc * Created * Starts * Started * Due * Resolved * Told * TimeEstimated * TimeWorked * TimeLeft :raises UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If there is no ticket with the specified ticket_id. """ if not query_format: query_format = {} res = await self.__request(f'ticket/{ticket_id}', get_params={'fields[Queue]': 'Name', **query_format}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def create_ticket( self, queue: str, content_type: TYPE_CONTENT_TYPE = 'text/plain', subject: str | None = None, content: str | None = None, attachments: typing.Sequence[Attachment] | None = None, **kwargs: typing.Any, ) -> int: """Create new ticket and set given parameters. Example of message sent to ``http://tracker.example.com/REST/2.0/ticket/new``:: { "Queue": "General", "Subject": "Ticket created through REST API", "Owner": "Nobody", "Requestor": "somebody@example.com", "Cc": "user2@example.com", "CustomRoles": {"My Role": "staff1@example.com"}, "Content": "Lorem Ipsum", "CustomFields": {"Severity": "Low"} } :param queue: Queue where to create ticket :param content_type: Content-type of the Content parameter; can be either text/plain or text/html. :param subject: Optional subject for the ticket. :param content: Optional content of the ticket. Must be specified unless attachments are specified. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :param kwargs: Other arguments possible to set: Requestors, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due :returns: ID of new ticket :raises ValueError: If the `content_type` is not of a supported format. """ if content_type not in ('text/plain', 'text/html'): # pragma: no cover raise ValueError('Invalid content-type specified.') ticket_data: dict[str, typing.Any] = {'Queue': queue} if subject is not None: ticket_data['Subject'] = subject if content is not None: ticket_data['Content'] = content ticket_data['ContentType'] = content_type for k, v in kwargs.items(): ticket_data[k] = v res = await self.__request('ticket', json_data=ticket_data, attachments=attachments) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) async def edit_ticket(self, ticket_id: str | int, **kwargs: typing.Any) -> bool: """Edit ticket values. :param ticket_id: ID of ticket to edit :param kwargs: Other arguments possible to set: Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,... (according to RT fields) Custom fields can be specified as dict: CustomFields = {"Severity": "Low"} :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed) """ msg = await self.__request_put(f'ticket/{ticket_id}', json_data=kwargs) self.logger.debug(msg) if not isinstance(msg, list): # pragma: no cover raise UnexpectedResponseError(str(msg)) if not msg: return True for k in msg: if REGEX_PATTERNS['does_not_exist'].search(k): raise rt.exceptions.NotFoundError(k) return bool(msg[0]) async def get_ticket_history(self, ticket_id: str | int) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """Get set of short history items. :param ticket_id: ID of ticket :returns: Iterator of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). collections.abc.AsyncIterator[typing.Dict[str, typing.Any]] """ async for transaction in self.__paged_request( f'ticket/{ticket_id}/history', params={ 'fields': 'Type,Creator,Created,Description,_hyperlinks', 'fields[Creator]': 'id,Name,RealName,EmailAddress', }, ): yield transaction async def get_transaction(self, transaction_id: str | int) -> dict[str, typing.Any]: """Get a transaction. :param transaction_id: ID of transaction :returns: Return a single transaction. """ res = await self.__request(f'transaction/{transaction_id}', get_params={'fields': 'Description'}) if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def __correspond( self, ticket_id: str | int, content: str = '', action: Literal['correspond', 'comment'] = 'correspond', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Sequence[Attachment] | None = None, ) -> list[str]: """Sends out the correspondence. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message :param action: correspond or comment :param content_type: Content type of email message, defaults to text/plain. Alternative is text/html. :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: List of messages returned by the backend related to the executed action. :raises BadRequestError: When ticket does not exist :raises InvalidUseError: If the `action` parameter is invalid :raises UnexpectedResponseError: If the response from RT is not as expected """ if action not in ('correspond', 'comment'): # pragma: no cover raise InvalidUseError('action must be either "correspond" or "comment"') post_data: dict[str, typing.Any] = { 'Content': content, 'ContentType': content_type, } # Adding a one-shot cc/bcc is not supported by RT5.0.2 # if cc: # post_data['Cc'] = cc # noqa: ERA001 # # if bcc: # post_data['Bcc'] = bcc # noqa: ERA001 res = await self.__request(f'ticket/{ticket_id}/{action}', json_data=post_data, attachments=attachments) if not isinstance(res, list): # pragma: no cover raise UnexpectedResponseError(str(res)) self.logger.debug(res) return res async def reply( self, ticket_id: str | int, content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Sequence[Attachment] | None = None, ) -> bool: """Sends email message to the contacts in ``Requestors`` field of given ticket with subject as is set in ``Subject`` field. :param ticket_id: ID of ticket to which message belongs :param content: Content of email message (text/plain or text/html) :param content_type: Content type of email message, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__correspond(ticket_id, content, 'correspond', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) async def delete_ticket(self, ticket_id: str | int) -> None: """Mark a ticket as deleted. :param ticket_id: ID of ticket :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: await self.__request_delete(f'ticket/{ticket_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover async def comment( self, ticket_id: str | int, content: str = '', content_type: TYPE_CONTENT_TYPE = 'text/plain', attachments: typing.Sequence[Attachment] | None = None, ) -> bool: """Adds comment to the given ticket. :param ticket_id: ID of ticket to which comment belongs :param content: Content of comment :param content_type: Content type of comment, default to text/plain :param attachments: Optional list of :py:class:`~rt.rest2.Attachment` objects :returns: ``True`` Operation was successful ``False`` Sending failed (status code != 200) :raises BadRequestError: When ticket does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__correspond(ticket_id, content, 'comment', content_type, attachments) if not (isinstance(msg, list) and len(msg) >= 1): # pragma: no cover raise UnexpectedResponseError(str(msg)) return bool(msg[0]) async def get_attachments( self, ticket_id: str | int, query_filter: list[dict[str, str]] | None = None, query_format: str | list[str] | dict[str, str] | None = None, ) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """Get attachment list for a given ticket. Example of a return result: .. code-block:: json [ { "id": "17", "Filename": "README.rst", "ContentLength": "3578", "type": "attachment", "ContentType": "test/plain", "_url": "http://localhost:8080/REST/2.0/attachment/17" } ] :param ticket_id: ID of ticket :param query_filter: JSON search filter, defaults to "filename is not empty" :param query_format: Returned fields to be populated :returns: Iterator of attachments belonging to given ticket. collections.abc.AsyncIterator[typing.Dict[str, str]] """ if query_filter is None: query_filter = [{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}] get_params = {'fields': 'Filename,ContentType,ContentLength'} if isinstance(query_format, dict): get_params = {**get_params, **query_format} elif isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif isinstance(query_format, str): get_params['fields'] = query_format async for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=query_filter, params=get_params, ): yield item async def get_attachments_ids( self, ticket_id: str | int, query_filter: list[dict[str, str]] | None = None, ) -> collections.abc.AsyncIterator[int]: """Get IDs of attachments for given ticket. :param ticket_id: ID of :param query_filter: JSON search filter, defaults to "filename is not empty" :returns: Iterator of IDs (type int) of attachments belonging to given ticket. collections.abc.AsyncIterator[int] """ if query_filter is None: query_filter = [{'field': 'Filename', 'operator': 'IS NOT', 'value': ''}] async for item in self.__paged_request( f'ticket/{ticket_id}/attachments', json_data=query_filter, ): yield int(item['id']) async def get_attachment(self, attachment_id: str | int) -> dict[str, typing.Any]: """Get attachment. :param attachment_id: ID of attachment to fetch :returns: Attachment as dictionary with these keys: * Transaction * ContentType * Parent * Creator * Created * Filename * Content (base64 encoded string) * Headers * MessageId * ContentEncoding * id * Subject All these fields are strings, just 'Headers' holds another dictionary with attachment headers as strings e.g.: * Delivered-To * From * Return-Path * Content-Length * To * X-Seznam-User * X-QM-Mark * Domainkey-Signature * RT-Message-ID * X-RT-Incoming-Encryption * X-Original-To * Message-ID * X-Spam-Status * In-Reply-To * Date * Received * X-Country * X-Spam-Checker-Version * X-Abuse * MIME-Version * Content-Type * Subject Set of headers available depends on mailservers sending emails not on Request Tracker! :raises UnexpectedMessageFormatError: Unexpected format of returned message. :raises NotFoundError: If attachment with specified ID does not exist. """ res = await self.__request(f'attachment/{attachment_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def get_user(self, user_id: int | str) -> dict[str, typing.Any]: """Get user details. :param user_id: Identification of user by username (str) or user ID (int) :returns: User details as strings in dictionary with these keys for RT users: * Lang * RealName * Privileged * Disabled * Gecos * EmailAddress * Password * id * Name Or these keys for external users (e.g. Requestors) replying to email from RT: * RealName * Disabled * EmailAddress * Password * id * Name :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: If the user does not exist. """ res = await self.__request(f'user/{user_id}') if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def user_exists(self, user_id: int | str, privileged: bool = True) -> bool: """Check if a given user_id exists. :parameter user_id: User ID to lookup. :parameter privileged: If set to True, only return True if the user_id was found and is privileged. :returns: bool: True on success, else False. """ try: user_dict = await self.get_user(user_id) if not privileged or (privileged and user_dict.get('Privileged', '0') == 1): return True except rt.exceptions.NotFoundError: return False return False async def create_user(self, user_name: str, email_address: str, **kwargs: typing.Any) -> str: """Create user. :param user_name: Username (login for privileged, required) :param email_address: Email address (required) :param kwargs: Optional fields to set (see edit_user) :returns: ID of new user or False when create fails :raises BadRequestError: When user already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Password', 'EmailAddress', 'RealName', 'Nickname', 'Gecos', 'Organization', 'Address1', 'Address2', 'City', 'State', 'Zip', 'Country', 'HomePhone', 'WorkPhone', 'MobilePhone', 'PagerPhone', 'ContactInfo', 'Comments', 'Signature', 'Lang', 'EmailEncoding', 'WebEncoding', 'ExternalContactInfoId', 'ContactInfoSystem', 'ExternalAuthId', 'AuthSystem', 'Privileged', 'Disabled', 'CustomFields', } invalid_fields = [] post_data = { 'Name': user_name, 'EmailAddress': email_address, } for k, v in kwargs.items(): if k not in valid_fields: invalid_fields.append(k) else: post_data[k] = v if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = await self.__request('user', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return res['id'] async def edit_user(self, user_id: str | int, **kwargs: typing.Any) -> list[str]: """Edit user profile. :param user_id: Identification of user by username (str) or user ID (int) :param kwargs: Other fields to edit from the following list: * Name * Password * EmailAddress * RealName * NickName * Gecos * Organization * Address1 * Address2 * City * State * Zip * Country * HomePhone * WorkPhone * MobilePhone * PagerPhone * ContactInfo * Comments * Signature * Lang * EmailEncoding * WebEncoding * ExternalContactInfoId * ContactInfoSystem * ExternalAuthId * AuthSystem * Privileged * Disabled :returns: List of status messages :raises BadRequestError: When user does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Password', 'EmailAddress', 'RealName', 'Nickname', 'Gecos', 'Organization', 'Address1', 'Address2', 'City', 'State', 'Zip', 'Country', 'HomePhone', 'WorkPhone', 'MobilePhone', 'PagerPhone', 'ContactInfo', 'Comments', 'Signature', 'Lang', 'EmailEncoding', 'WebEncoding', 'ExternalContactInfoId', 'ContactInfoSystem', 'ExternalAuthId', 'AuthSystem', 'Privileged', 'Disabled', 'CustomFields', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = await self.__request_put(f'user/{user_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret async def delete_user(self, user_id: str | int) -> None: """Disable a user. :param user_id: Identification of a user by name (str) or ID (int) :raises BadRequestError: When user does not exist :raises NotFoundError: If the user does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = await self.__request_delete(f'user/{user_id}') except UnexpectedResponseError as exc: if exc.status_code == 400: # pragma: no cover raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover async def get_queue(self, queue_id: str | int) -> dict[str, typing.Any]: """Get queue details. Example of a return result: .. code-block:: json { "LastUpdatedBy": { "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user", "id": "RT_System" }, "LastUpdated": "2022-03-06T04:53:38Z", "AdminCc": [], "SortOrder": "0", "CorrespondAddress": "", "Creator": { "id": "RT_System", "_url": "http://localhost:8080/REST/2.0/user/RT_System", "type": "user" }, "Lifecycle": "default", "Cc": [], "Created": "2022-03-06T04:53:38Z", "_hyperlinks": [ { "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "id": 1, "ref": "self" }, { "ref": "history", "_url": "http://localhost:8080/REST/2.0/queue/1/history" }, { "ref": "create", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket?Queue=1" } ], "SLADisabled": "1", "Name": "General", "TicketCustomFields": [], "Disabled": "0", "TicketTransactionCustomFields": [], "CustomFields": [], "Description": "The default queue", "CommentAddress": "", "id": 1 } :param queue_id: Identification of queue by name (str) or queue ID (int) :returns: Queue details as a dictionary :raises UnexpectedMessageFormatError: In case that returned status code is not 200 :raises NotFoundError: In case the queue does not exist """ res = await self.__request(f'queue/{queue_id}') if not (res is None or isinstance(res, dict)): # pragma: no cover raise UnexpectedResponseError(str(res)) return res async def get_all_queues(self, include_disabled: bool = False) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """Return a list of all queues. Example of a return result: .. code-block:: json [ { "InitialPriority": "", "_url": "http://localhost:8080/REST/2.0/queue/1", "type": "queue", "Name": "General", "DefaultDueIn": "", "Description": "The default queue", "CorrespondAddress": "", "CommentAddress": "", "id": "1", "FinalPriority": "" } ] :param include_disabled: Set to True to also return disabled queues. :returns: Iterator of dictionaries containing basic information on all queues. collections.abc.AsyncIterator[typing.Dict[str, typing.Any]] :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ params = { 'fields': 'Name,Description,CorrespondAddress,CommentAddress,InitialPriority,FinalPriority,DefaultDueIn', 'find_disabled_rows': int(include_disabled), } async for item in self.__paged_request('queues/all', params=params): yield item async def edit_queue(self, queue_id: str | int, **kwargs: typing.Any) -> list[str]: """Edit queue. :param queue_id: Identification of queue by name (str) or ID (int) :param kwargs: Other fields to edit from the following list: * Name * Description * CorrespondAddress * CommentAddress * Disabled * SLADisabled * Lifecycle * SortOrder :returns: List of status messages :raises BadRequestError: When queue does not exist :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: ret = await self.__request_put(f'queue/{queue_id}', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise return ret async def create_queue(self, name: str, **kwargs: typing.Any) -> int: """Create queue. :param name: Queue name (required) :param kwargs: Optional fields to set (see edit_queue) :returns: ID of new queue or False when create fails :raises BadRequestError: When queue already exists :raises InvalidUseError: When invalid fields are set :raises UnexpectedResponseError: If the response from RT is not as expected """ valid_fields = { 'Name', 'Description', 'CorrespondAddress', 'CommentAddress', 'Disabled', 'SLADisabled', 'Lifecycle', 'SortOrder', } invalid_fields = [] post_data = {'Name': name} for key, val in kwargs.items(): if key not in valid_fields: invalid_fields.append(key) else: post_data[key] = val if invalid_fields: raise InvalidUseError(f"""Unsupported names of fields: {', '.join(invalid_fields)}.""") try: res = await self.__request('queue', json_data=post_data) except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc raise if not isinstance(res, dict): # pragma: no cover raise UnexpectedResponseError(str(res)) return int(res['id']) async def delete_queue(self, queue_id: str | int) -> None: """Disable a queue. :param queue_id: Identification of queue by name (str) or ID (int) :returns: ID or name of edited queue or False when edit fails :raises BadRequestError: When queue does not exist :raises NotFoundError: If the queue does not exist :raises UnexpectedResponseError: If the response from RT is not as expected """ try: _ = await self.__request_delete(f'queue/{queue_id}') except UnexpectedResponseError as exc: # pragma: no cover if exc.status_code == 400: raise rt.exceptions.BadRequestError(exc.response_message) from exc if exc.status_code == 204: return raise # pragma: no cover async def get_links(self, ticket_id: str | int) -> list[dict[str, str]]: """Gets the ticket links for a single ticket. Example of a return result: .. code-block:: json [ { "id": "13", "type": "ticket", "_url": "http://localhost:8080/REST/2.0/ticket/13", "ref": "depends-on" } ] :param ticket_id: ticket ID :returns: Links as lists of strings in dictionary with these keys (just those which are defined): * depends-on * depended-on-by * parent * child * refers-to * referred-to-by :raises NotFoundError: If there is no ticket with the specified ticket_id. :raises UnexpectedMessageFormatError: In case that returned status code is not 200 """ ticket = await self.get_ticket(ticket_id) return [link for link in ticket['_hyperlinks'] if link.get('type', '') == 'ticket' and link['ref'] != 'self'] async def edit_link( self, ticket_id: str | int, link_name: TYPE_VALID_TICKET_LINK_NAMES, link_value: str | int, delete: bool = False, ) -> bool: """Creates or deletes a link between the specified tickets. :param ticket_id: ID of ticket to edit :param link_name: Name of link to edit ('Parent', 'Child', 'RefersTo', 'ReferredToBy', 'DependsOn', 'DependedOnBy') :param link_value: Either ticker ID or external link. :param delete: if True the link is deleted instead of created :returns: ``True`` Operation was successful ``False`` Ticket with given ID does not exist or link to delete is not found :raises InvalidUseError: When none or more than one link is specified. Also, when a wrong link name is used or when trying to link to a deleted ticket. """ if link_name not in VALID_TICKET_LINK_NAMES: raise InvalidUseError(f'Unsupported link name. Use one of "{", ".join(VALID_TICKET_LINK_NAMES)}".') if delete: json_data = {f'Delete{link_name}': link_value} else: json_data = {f'Add{link_name}': link_value} msg = await self.__request_put(f'ticket/{ticket_id}', json_data=json_data) if msg and isinstance(msg, list): if msg[0].startswith("Couldn't resolve"): raise NotFoundError(msg[0]) if 'not allowed' in msg[0]: raise InvalidUseError(msg[0]) return True async def merge_ticket(self, ticket_id: str | int, into_id: str | int) -> bool: """Merge ticket into another. :param ticket_id: ID of ticket to be merged :param into_id: ID of destination ticket :returns: ``True`` Operation was successful ``False`` Either origin or destination ticket does not exist or user does not have ModifyTicket permission. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}', json_data={'MergeInto': into_id}) if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower() == 'merge successful' async def take(self, ticket_id: str | int) -> bool: """Take ticket. :param ticket_id: ID of ticket to be taken :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have TakeTicket permission. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}/take') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') async def untake(self, ticket_id: str | int) -> bool: """Untake ticket. :param ticket_id: ID of ticket to be untaken :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not own the ticket. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}/untake') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') async def steal(self, ticket_id: str | int) -> bool: """Steal ticket. :param ticket_id: ID of ticket to be stolen :returns: ``True`` Operation was successful ``False`` Either the ticket does not exist or user does not have StealTicket permission. :raises UnexpectedResponseError: If the response from RT is not as expected """ msg = await self.__request_put(f'ticket/{ticket_id}/steal') if not isinstance(msg, list) or len(msg) != 1: # pragma: no cover raise UnexpectedResponseError(str(msg)) self.logger.debug(str(msg)) return msg[0].lower().startswith('owner changed') async def get_catalog(self, catalog_id: str | int) -> dict[str, typing.Any]: """ Get catalog. :param catalog_id: Catalog ID. :return: Catalog. id: int Lifecycle: str Disabled: str _hyperlinks: list[dict[dict[str, str | int]]] LastUpdated: str LastUpdatedBy: dict[str, str] Created: str Creator: dict[str, str] Description: str Name: str Contact: list[str, str] HeldBy: list[str, str] """ response = await self.__request(f'catalog/{catalog_id}') self.logger.debug(str(response)) if not isinstance(response, dict): raise UnexpectedResponseError(str(response)) return response async def get_asset(self, asset_id: str | int, query_format: dict[str, str] | None = None) -> dict[str, typing.Any]: """ Get asset. :param asset_id: Asset ID. :param query_format: Returned fields to be populated. :return: Asset (when `query_format` is `None`). id: int Lifecycle: str Disabled: str _hyperlinks: list[dict[dict[str, str | int]]] LastUpdated: str LastUpdatedBy: dict[str, str] Created: str Creator: dict[str, str] Description: str Name: str Contact: list[str, str] HeldBy: list[str, str] Catalog: dict[str, str] Status: str Owner: dict[str, str] CustomFields: list[dict[str, typing.Any]] """ if not query_format: query_format = {} response = await self.__request(f'asset/{asset_id}', get_params=query_format) self.logger.debug(str(response)) if not isinstance(response, dict): raise UnexpectedResponseError(str(response)) return response async def create_asset(self, name: str, catalog: str | int, **kwargs: typing.Any) -> int: """ Create a new asset in a catalog. :param name: Asset name. :param catalog: Catalog name or ID. :param kwargs: Name, Description, Status, CustomFields, RefersTo, etc. :return: ID of the asset. """ response = await self.__request('asset', json_data={'Name': name, 'Catalog': catalog, **kwargs}) self.logger.debug(str(response)) if not isinstance(response, dict): raise UnexpectedResponseError(str(response)) return int(response['id']) async def edit_asset(self, asset_id: str | int, **kwargs: typing.Any) -> bool: """ Edit an existing asset. :param asset_id: Asset ID. :param kwargs: Name, Description, Status, CustomFields, RefersTo, etc. :return: ``True`` Operation was successful ``False`` Failed (status code != 200) """ response = await self.__request_put(f'asset/{asset_id}', kwargs) self.logger.debug(str(response)) return isinstance(response, list) async def search_assets( self, catalog_id: str | int | None = None, search_params: list[dict[str, typing.Any]] | None = None, query_format: str | list[str] | dict[str, str] | None = None, ) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """ Search assets in a catalog. Example:: >>> client = AsyncRt(...) >>> await client.search_assets(1, [{"field": "Name", "value": "NameOfMyAsset"}], "Owner,Status") >>> await client.search_assets(1, [{"field": "Name", "value": "NameOfMyAsset"}], ["Owner", "Status"]) >>> await client.search_assets(1, [{"field": "Name", "value": "NameOfMyAsset"}], {"fields": "Owner,Status", "fields[Owner]": "id,Name"}) :param catalog_id: Catalog ID. Use `None` to search all catalogs. :param search_params: Params used to filter the results. field: str value: str | int operator: Literal[">", "<", "=", "!=", "LIKE", "NOT LIKE", ">=", "<="] | None :param query_format: Returned fields to be populated. :return: Found assets. The following is returned by default (when `query_format` is `None`) { 'Description': '', 'id': '1', '_url': 'http://localhost:8080/REST/2.0/asset/1', 'Owner': {'_url': 'http://localhost:8080/REST/2.0/user/Nobody', 'id': 'Nobody', 'type': 'user'}, 'Status': 'new', 'type': 'asset' } """ if not search_params: search_params = [] if catalog_id: search_params.append({'field': 'Catalog', 'value': catalog_id, 'operator': '='}) else: search_params.append({'field': 'Catalog', 'value': '%', 'operator': 'LIKE'}) get_params = {'fields': 'Owner,Description,Status'} if isinstance(query_format, dict): get_params = {**get_params, **query_format} elif isinstance(query_format, list): get_params['fields'] = ','.join(query_format) elif isinstance(query_format, str): get_params['fields'] = query_format async for item in self.__paged_request('assets', json_data=search_params, params=get_params): yield item async def get_asset_history(self, asset_id: str | int) -> collections.abc.AsyncIterator[dict[str, typing.Any]]: """ Get asset history. :param asset_id: Asset ID. :return: History - transactions. Type: str type: str _url: str Creator: dict[str, str | int] Created: str Description: str _hyperlinks: list[dict[str, int | str]] id: str """ async for transaction in self.__paged_request( f'asset/{asset_id}/history', params={ 'fields': 'Type,Creator,Created,Description,_hyperlinks', 'fields[Creator]': 'id,Name,RealName,EmailAddress', }, ): yield transaction rt-3.8.1/tests/__init__.py0000644000000000000000000000032113615410400012337 0ustar00# ruff: noqa: S311 import random import string def random_string(length: int = 15) -> str: """Return a random string.""" return ''.join([random.choice(string.ascii_letters) for i in range(length)]) rt-3.8.1/tests/conftest.py0000644000000000000000000000137113615410400012433 0ustar00# ruff: noqa: S105 import typing import httpx2 import pytest if typing.TYPE_CHECKING: import rt.rest2 # blank setup defaults RT_URL = 'http://localhost:8080/REST/2.0/' RT_USER = 'root' RT_PASSWORD = 'password' RT_QUEUE = 'General' @pytest.fixture(scope='session') def rt_connection() -> 'rt.rest2.Rt': """Setup a generic connection.""" import rt.rest2 # noqa: PLC0415 return rt.rest2.Rt(url=RT_URL, http_auth=httpx2.BasicAuth(RT_USER, RT_PASSWORD), http_timeout=None) @pytest.fixture(scope='session') def async_rt_connection() -> 'rt.rest2.AsyncRt': """Setup a generic connection.""" import rt.rest2 # noqa: PLC0415 return rt.rest2.AsyncRt(url=RT_URL, http_auth=httpx2.BasicAuth(RT_USER, RT_PASSWORD), http_timeout=None) rt-3.8.1/tests/test_basic.py0000644000000000000000000004736513615410400012743 0ustar00"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101, S105, S311 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ __docformat__ = 'reStructuredText en' __authors__ = [ '"Jiri Machalek" ', '"Georges Toth" ', ] import base64 import random import string import httpx2 import pytest import rt.exceptions import rt.rest2 from . import random_string RT_URL = 'http://localhost:8080/REST/2.0/' RT_USER = 'root' RT_PASSWORD = 'password' RT_QUEUE = 'General' def test_get_user(rt_connection: rt.rest2.Rt): user = rt_connection.get_user(RT_USER) assert user['Name'] == RT_USER assert '@' in user['EmailAddress'] assert user['Privileged'] == 1 def test_invalid_api_url(): with pytest.raises(ValueError): rt.rest2.Rt(url='https://example.com', http_auth=httpx2.BasicAuth('dummy', 'dummy')) def test_ticket_operations(rt_connection: rt.rest2.Rt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # empty search result search_result = list(rt_connection.search(Subject=ticket_subject)) assert not search_result # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # search search_result = list(rt_connection.search(Subject=ticket_subject)) assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # search with query_format field list search_result = list(rt_connection.search(Subject=ticket_subject, query_format=['Status', 'Subject'])) assert len(search_result) == 1 assert search_result[0]['Subject'] == str(ticket_subject) assert search_result[0]['Status'] == 'new' assert 'Requestor' not in search_result[0].keys() # search with query_format field dict search_result = list(rt_connection.search(Subject=ticket_subject, query_format={'fields': 'Owner', 'fields[Owner]': 'Name'})) assert len(search_result) == 1 assert 'Subject' not in search_result[0] assert 'Status' not in search_result[0] assert search_result[0]['Owner']['Name'] == 'Nobody' # raw search search_result = list(rt_connection.search(raw_query=f'Subject="{ticket_subject}"')) assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # get ticket ticket = rt_connection.get_ticket(ticket_id) search_result[0]['id'] = int(search_result[0]['id']) for k in search_result[0]: if k.startswith('_') or k in ('type', 'CustomFields'): continue assert k in ticket assert ticket[k] == search_result[0][k] # edit ticket requestors = ['tester1@example.com', 'tester2@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # get ticket (edited) ticket = rt_connection.get_ticket(ticket_id) assert ticket['Status'] == 'open' for requestor in ticket['Requestor']: assert requestor['id'] in requestors for requestor in requestors: found = False for _requestor in ticket['Requestor']: if _requestor['id'] == requestor: found = True break assert found # get history hist = rt_connection.get_ticket_history(ticket_id) assert len(hist) > 0 transaction = rt_connection.get_transaction(hist[0]['id']) found = False for hyperlink in transaction['_hyperlinks']: if hyperlink['ref'] == 'attachment': attachment_id = hyperlink['_url'].rsplit('/', 1)[1] attachment = base64.b64decode(rt_connection.get_attachment(attachment_id)['Content']).decode('utf-8') found = True assert attachment == ticket_text break assert found # get_short_history short_hist = rt_connection.get_ticket_history(ticket_id) assert len(short_hist) > 0 assert short_hist[0]['Type'] == 'Create' assert short_hist[0]['Creator']['Name'] == RT_USER # create 2nd ticket ticket2_subject = 'Testing issue ' + ''.join([random.choice(string.ascii_letters) for i in range(15)]) ticket2_id = rt_connection.create_ticket(queue=RT_QUEUE, subject=ticket2_subject) assert ticket2_id > -1 # edit link assert rt_connection.edit_link(ticket_id, 'DependsOn', ticket2_id) # get links links1 = rt_connection.get_links(ticket_id) found = False for link in links1: if link['ref'] == 'depends-on' and link['id'] == str(ticket2_id): found = True assert found links2 = rt_connection.get_links(ticket2_id) found = False for link in links2: if link['ref'] == 'depended-on-by' and link['id'] == str(ticket_id): found = True assert found # reply with attachment attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) assert rt_connection.reply(ticket_id, content=reply_text, attachments=[attachment]) # reply with a comment reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert rt_connection.comment(ticket_id, content=reply_text) # reply with a html content reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert rt_connection.reply(ticket_id, content=reply_text, content_type='text/html') # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list at_names = [at['Filename'] for at in at_list] assert attachment_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(attachment_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == attachment_content # set invalid user with pytest.raises(rt.exceptions.NotFoundError): rt_connection.edit_ticket(ticket_id, Owner='invalid_user') # set invalid queue with pytest.raises(rt.exceptions.NotFoundError): rt_connection.edit_ticket(ticket_id, Queue='invalid_queue') # edit invalid ticket with pytest.raises(rt.exceptions.NotFoundError): rt_connection.edit_ticket(999999999, Owner='Nobody') # merge tickets assert rt_connection.merge_ticket(ticket2_id, ticket_id) # delete ticket assert rt_connection.delete_ticket(ticket_id) is None # delete invalid ticket with pytest.raises(rt.exceptions.NotFoundError): assert rt_connection.delete_ticket(999999999) def test_attachments_create(rt_connection: rt.rest2.Rt): """Create a ticket with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=attachments) assert ticket_id > -1 # get ticket ticket = rt_connection.get_ticket(ticket_id) assert int(ticket['id']) == ticket_id # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == k.file_content def test_attachments_search(rt_connection: rt.rest2.Rt): """Create a ticket with an attachments and verify that attachment search and filtering works correctly.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=[attachment]) at_list = [item for item in rt_connection.get_attachments(ticket_id, query_format=['TransactionId', 'Headers'])] assert at_list assert len(at_list) == 1 assert at_list[0]['TransactionId'] assert at_list[0]['Headers'] def test_attachments_comment(rt_connection: rt.rest2.Rt): """Create a ticket and comment to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = rt_connection.comment(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == k.file_content def test_attachments_reply(rt_connection: rt.rest2.Rt): """Create a ticket and reply to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = rt_connection.reply(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = rt_connection.get_attachments(ticket_id) assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode(rt_connection.get_attachment(at_id)['Content']) assert at_content == k.file_content def test_ticket_operations_admincc_cc(rt_connection: rt.rest2.Rt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) def compare_list(from_list: list[str], ticket_list: list[dict]) -> bool: """Lists (Requestor, AdminCc, Cc) returned from REST2 contain a list of dicts with additional user information. Thus a simple compare of both lists is not enough. """ if len(from_list) != len(ticket_list): return False to_list = [entry['id'] for entry in ticket_list] diff = set(from_list) ^ set(to_list) return not diff ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # make sure Requestor, AdminCc and Cc are present and an empty list, as would be expected ticket = rt_connection.get_ticket(ticket_id) assert len(ticket['Requestor']) >= 0 assert len(ticket['AdminCc']) >= 0 assert len(ticket['Cc']) >= 0 # set requestors requestors = ['tester1@example.com', 'tester2@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) # set admincc admincc = ['tester2@example.com', 'tester3@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # update admincc admincc = ['tester2@example.com', 'tester3@example.com', 'tester4@example.com'] rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # unset requestors and admincc requestors = [] admincc = [] rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors, AdminCc=admincc) # verify ticket = rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) def test_users(rt_connection: rt.rest2.Rt): assert rt_connection.get_user('tester1@example.com') is not None assert rt_connection.user_exists('root', privileged=True) is True assert rt_connection.user_exists('tester1@example.com', privileged=False) is True assert rt_connection.user_exists('tester1@example.com', privileged=True) is False assert rt_connection.user_exists('does-not-exist@example.com') is False random_user_name = f'username_{random_string()}' random_user_email = f'user-{random_string()}@example.com' random_user_password = f'user_password-{random_string()}' assert rt_connection.create_user(random_user_name, random_user_email, Password=random_user_password) == random_user_name rt_connection.delete_user(random_user_name) with pytest.raises(rt.exceptions.NotFoundError): rt_connection.delete_user(f'username_{random_string()}') assert rt_connection.edit_user(user_id=random_user_name, RealName=random_user_name) def test_queues(rt_connection: rt.rest2.Rt): queue = rt_connection.get_queue(RT_QUEUE) assert queue['Name'] == RT_QUEUE queues = rt_connection.get_all_queues() assert len(queues) >= 1 found = False for q in queues: if q['Name'] == RT_QUEUE: found = True assert found random_queue_name = f'Queue {random_string()}' random_queue_email = f'q-{random_string()}@example.com' rt_connection.create_queue(random_queue_name, CorrespondAddress=random_queue_email, Description='test queue') queues = rt_connection.get_all_queues() found = False for q in queues: if q['Name'] == random_queue_name: found = True assert found rt_connection.edit_queue(random_queue_name, Disabled='1') assert rt_connection.get_queue(random_queue_name)['Disabled'] == '1' rt_connection.edit_queue(random_queue_name, Disabled='0') assert rt_connection.get_queue(random_queue_name)['Disabled'] == '0' with pytest.raises(rt.exceptions.NotFoundError): rt_connection.get_queue('InvalidName') rt_connection.delete_queue(random_queue_name) with pytest.raises(rt.exceptions.NotFoundError): rt_connection.delete_queue(f'Queue {random_string()}') def test_catalog(rt_connection: rt.rest2.Rt): catalog = rt_connection.get_catalog(1) assert catalog['id'] == 1 def test_assets(rt_connection: rt.rest2.Rt): asset_name = random_string() asset_name_new = random_string() asset_id = rt_connection.create_asset(asset_name, 1, Creator='root') assert asset_id asset = rt_connection.get_asset(asset_id) assert asset['id'] == asset_id asset_history = rt_connection.get_asset_history(asset_id) assert len(list(asset_history)) == 1 asset_edited = rt_connection.edit_asset(asset_id, Name=asset_name_new) assert asset_edited search = rt_connection.search_assets(1, [{'field': 'Name', 'value': asset_name_new}]) items = list(search) assert len(items) == 1 assert items[0]['Status'] == 'new' search = rt_connection.search_assets(1, [{'field': 'Name', 'value': asset_name_new}], query_format='Owner') items = list(search) assert len(items) == 1 assert items[0]['Owner']['id'] == 'Nobody' assert 'Status' not in items[0] search = rt_connection.search_assets(1, [{'field': 'Name', 'value': asset_name_new}], query_format=['Owner']) items = list(search) assert len(items) == 1 assert items[0]['Owner']['id'] == 'Nobody' assert 'Status' not in items[0] search = rt_connection.search_assets() items = list(search) assert items search = rt_connection.search_assets( 1, [{'field': 'Name', 'value': asset_name_new}], query_format={'fields': 'Owner', 'fields[Owner]': 'Name'} ) items = list(search) assert len(items) == 1 assert items[0]['Owner']['Name'] == 'Nobody' assert 'Status' not in items[0] rt-3.8.1/tests/test_basic_async.py0000644000000000000000000005277213615410400014136 0ustar00"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101, S105, S311 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ __docformat__ = 'reStructuredText en' __authors__ = [ '"Jiri Machalek" ', '"Georges Toth" ', ] import base64 import random import string import httpx2 import pytest import rt.exceptions import rt.rest2 from . import random_string RT_URL = 'http://localhost:8080/REST/2.0/' RT_USER = 'root' RT_PASSWORD = 'password' RT_QUEUE = 'General' @pytest.mark.asyncio async def test_get_user(async_rt_connection: rt.rest2.AsyncRt): user = await async_rt_connection.get_user(RT_USER) assert user['Name'] == RT_USER assert '@' in user['EmailAddress'] assert user['Privileged'] == 1 @pytest.mark.asyncio async def test_invalid_api_url(): with pytest.raises(ValueError): rt.rest2.AsyncRt(url='https://example.com', http_auth=httpx2.BasicAuth('dummy', 'dummy')) @pytest.mark.asyncio async def test_ticket_operations(async_rt_connection: rt.rest2.AsyncRt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # empty search result search_result = [item async for item in async_rt_connection.search(Subject=ticket_subject)] assert not search_result # create ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # search search_result = [item async for item in async_rt_connection.search(Subject=ticket_subject)] assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # search with query_format field list search_result = [item async for item in async_rt_connection.search(Subject=ticket_subject, query_format=['Status', 'Subject'])] assert len(search_result) == 1 assert search_result[0]['Subject'] == str(ticket_subject) assert search_result[0]['Status'] == 'new' assert 'Requestor' not in search_result[0].keys() # search with query_format field dict search_result = [ item async for item in async_rt_connection.search(Subject=ticket_subject, query_format={'fields': 'Owner', 'fields[Owner]': 'Name'}) ] assert len(search_result) == 1 assert 'Subject' not in search_result[0] assert 'Status' not in search_result[0] assert search_result[0]['Owner']['Name'] == 'Nobody' # raw search search_result = [item async for item in async_rt_connection.search(raw_query=f'Subject="{ticket_subject}"')] assert len(search_result) == 1 assert search_result[0]['id'] == str(ticket_id) assert search_result[0]['Status'] == 'new' # get ticket ticket = await async_rt_connection.get_ticket(ticket_id) search_result[0]['id'] = int(search_result[0]['id']) for k in search_result[0]: if k.startswith('_') or k in ('type', 'CustomFields'): continue assert k in ticket assert ticket[k] == search_result[0][k] # edit ticket requestors = ['tester1@example.com', 'tester2@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # get ticket (edited) ticket = await async_rt_connection.get_ticket(ticket_id) assert ticket['Status'] == 'open' for requestor in ticket['Requestor']: assert requestor['id'] in requestors for requestor in requestors: found = False for _requestor in ticket['Requestor']: if _requestor['id'] == requestor: found = True break assert found # get history hist = [item async for item in async_rt_connection.get_ticket_history(ticket_id)] assert len(hist) > 0 transaction = await async_rt_connection.get_transaction(hist[0]['id']) found = False for hyperlink in transaction['_hyperlinks']: if hyperlink['ref'] == 'attachment': attachment_id = hyperlink['_url'].rsplit('/', 1)[1] attachment = base64.b64decode((await async_rt_connection.get_attachment(attachment_id))['Content']).decode('utf-8') found = True assert attachment == ticket_text break assert found # get_short_history short_hist = [item async for item in async_rt_connection.get_ticket_history(ticket_id)] assert len(short_hist) > 0 assert short_hist[0]['Type'] == 'Create' assert short_hist[0]['Creator']['Name'] == RT_USER # create 2nd ticket ticket2_subject = 'Testing issue ' + ''.join([random.choice(string.ascii_letters) for i in range(15)]) ticket2_id = await async_rt_connection.create_ticket(queue=RT_QUEUE, subject=ticket2_subject) assert ticket2_id > -1 # edit link assert await async_rt_connection.edit_link(ticket_id, 'DependsOn', ticket2_id) # get links links1 = await async_rt_connection.get_links(ticket_id) found = False for link in links1: if link['ref'] == 'depends-on' and link['id'] == str(ticket2_id): found = True assert found links2 = await async_rt_connection.get_links(ticket2_id) found = False for link in links2: if link['ref'] == 'depended-on-by' and link['id'] == str(ticket_id): found = True assert found # reply with attachment attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) assert await async_rt_connection.reply(ticket_id, content=reply_text, attachments=[attachment]) # reply with a comment reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert await async_rt_connection.comment(ticket_id, content=reply_text) # reply with a html content reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' assert await async_rt_connection.reply(ticket_id, content=reply_text, content_type='text/html') # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list at_names = [at['Filename'] for at in at_list] assert attachment_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(attachment_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == attachment_content # set invalid user with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.edit_ticket(ticket_id, Owner='invalid_user') # set invalid queue with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.edit_ticket(ticket_id, Queue='invalid_queue') # edit invalid ticket with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.edit_ticket(999999999, Owner='Nobody') # merge tickets assert await async_rt_connection.merge_ticket(ticket2_id, ticket_id) # delete ticket assert await async_rt_connection.delete_ticket(ticket_id) is None # delete invalid ticket with pytest.raises(rt.exceptions.NotFoundError): assert await async_rt_connection.delete_ticket(999999999) @pytest.mark.asyncio async def test_attachments_create(async_rt_connection: rt.rest2.AsyncRt): """Create a ticket with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # create ticket_id = await async_rt_connection.create_ticket( subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=attachments ) assert ticket_id > -1 # get ticket ticket = await async_rt_connection.get_ticket(ticket_id) assert int(ticket['id']) == ticket_id # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == k.file_content @pytest.mark.asyncio async def test_attachments_search(async_rt_connection: rt.rest2.AsyncRt): """Create a ticket with an attachments and verify that attachment search and filtering works correctly.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) ticket_id = await async_rt_connection.create_ticket( subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=[attachment] ) at_list = [item async for item in async_rt_connection.get_attachments(ticket_id, query_format=['TransactionId', 'Headers'])] assert at_list assert len(at_list) == 1 assert at_list[0]['TransactionId'] assert at_list[0]['Headers'] @pytest.mark.asyncio async def test_attachments_comment(async_rt_connection: rt.rest2.AsyncRt): """Create a ticket and comment to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = await async_rt_connection.comment(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == k.file_content @pytest.mark.asyncio async def test_attachments_reply(async_rt_connection: rt.rest2.AsyncRt): """Create a ticket and reply to it with a random (>= 2) number of attachments and verify that they have been successfully added to the ticket.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) # create ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 attachment_count = random.randint(2, 10) attachments = [] for _i in range(attachment_count): attachment_content = random_string(length=100).encode() attachment_name = f'attachment-{random_string(length=10)}.txt' attachments.append(rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content)) # comment with attachments ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) comment_success = await async_rt_connection.reply(ticket_id=ticket_id, content=ticket_text, attachments=attachments) assert comment_success # attachments list at_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert at_list assert len(at_list) == len(attachments) at_names = [at['Filename'] for at in at_list] for k in attachments: assert k.file_name in at_names # get the attachment and compare it's content at_id = at_list[at_names.index(k.file_name)]['id'] at_content = base64.b64decode((await async_rt_connection.get_attachment(at_id))['Content']) assert at_content == k.file_content @pytest.mark.asyncio async def test_ticket_operations_admincc_cc(async_rt_connection: rt.rest2.AsyncRt): ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) def compare_list(from_list: list[str], ticket_list: list[dict]) -> bool: """Lists (Requestor, AdminCc, Cc) returned from REST2 contain a list of dicts with additional user information. Thus a simple compare of both lists is not enough. """ if len(from_list) != len(ticket_list): return False to_list = [entry['id'] for entry in ticket_list] diff = set(from_list) ^ set(to_list) return not diff ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id > -1 # make sure Requestor, AdminCc and Cc are present and an empty list, as would be expected ticket = await async_rt_connection.get_ticket(ticket_id) assert len(ticket['Requestor']) >= 0 assert len(ticket['AdminCc']) >= 0 assert len(ticket['Cc']) >= 0 # set requestors requestors = ['tester1@example.com', 'tester2@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) # set admincc admincc = ['tester2@example.com', 'tester3@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # update admincc admincc = ['tester2@example.com', 'tester3@example.com', 'tester4@example.com'] await async_rt_connection.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) # unset requestors and admincc requestors = [] admincc = [] await async_rt_connection.edit_ticket(ticket_id, Status='open', Requestor=requestors, AdminCc=admincc) # verify ticket = await async_rt_connection.get_ticket(ticket_id) assert compare_list(requestors, ticket['Requestor']) assert compare_list(admincc, ticket['AdminCc']) @pytest.mark.asyncio async def test_users(async_rt_connection: rt.rest2.AsyncRt): assert await async_rt_connection.get_user('tester1@example.com') is not None assert await async_rt_connection.user_exists('root', privileged=True) is True assert await async_rt_connection.user_exists('tester1@example.com', privileged=False) is True assert await async_rt_connection.user_exists('tester1@example.com', privileged=True) is False assert await async_rt_connection.user_exists('does-not-exist@example.com') is False random_user_name = f'username_{random_string()}' random_user_email = f'user-{random_string()}@example.com' random_user_password = f'user_password-{random_string()}' assert await async_rt_connection.create_user(random_user_name, random_user_email, Password=random_user_password) == random_user_name await async_rt_connection.delete_user(random_user_name) with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.delete_user(f'username_{random_string()}') assert await async_rt_connection.edit_user(user_id=random_user_name, RealName=random_user_name) @pytest.mark.asyncio async def test_queues(async_rt_connection: rt.rest2.AsyncRt): queue = await async_rt_connection.get_queue(RT_QUEUE) assert queue['Name'] == RT_QUEUE queues = [item async for item in async_rt_connection.get_all_queues()] assert len(queues) >= 1 found = False for q in queues: if q['Name'] == RT_QUEUE: found = True assert found random_queue_name = f'Queue {random_string()}' random_queue_email = f'q-{random_string()}@example.com' await async_rt_connection.create_queue(random_queue_name, CorrespondAddress=random_queue_email, Description='test queue') queues = [item async for item in async_rt_connection.get_all_queues()] found = False for q in queues: if q['Name'] == random_queue_name: found = True assert found await async_rt_connection.edit_queue(random_queue_name, Disabled='1') assert (await async_rt_connection.get_queue(random_queue_name))['Disabled'] == '1' await async_rt_connection.edit_queue(random_queue_name, Disabled='0') assert (await async_rt_connection.get_queue(random_queue_name))['Disabled'] == '0' with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.get_queue('InvalidName') await async_rt_connection.delete_queue(random_queue_name) with pytest.raises(rt.exceptions.NotFoundError): await async_rt_connection.delete_queue(f'Queue {random_string()}') @pytest.mark.asyncio async def test_catalog(async_rt_connection: rt.rest2.AsyncRt): catalog = await async_rt_connection.get_catalog(1) assert catalog['id'] == 1 @pytest.mark.asyncio async def test_assets(async_rt_connection: rt.rest2.AsyncRt): asset_name = random_string() asset_name_new = random_string() asset_id = await async_rt_connection.create_asset(asset_name, 1, Creator='root') assert asset_id asset = await async_rt_connection.get_asset(asset_id) assert asset['id'] == asset_id asset_history = [item async for item in async_rt_connection.get_asset_history(asset_id)] assert len(asset_history) == 1 asset_edited = await async_rt_connection.edit_asset(asset_id, Name=asset_name_new) assert asset_edited search = async_rt_connection.search_assets(1, [{'field': 'Name', 'value': asset_name_new}]) items = [item async for item in search] assert len(items) == 1 assert items[0]['Status'] == 'new' search = async_rt_connection.search_assets(1, [{'field': 'Name', 'value': asset_name_new}], query_format='Owner') items = [item async for item in search] assert len(items) == 1 assert items[0]['Owner']['id'] == 'Nobody' assert 'Status' not in items[0] search = async_rt_connection.search_assets(1, [{'field': 'Name', 'value': asset_name_new}], query_format=['Owner']) items = [item async for item in search] assert len(items) == 1 assert items[0]['Owner']['id'] == 'Nobody' assert 'Status' not in items[0] search = async_rt_connection.search_assets() items = [item async for item in search] assert items search = async_rt_connection.search_assets( 1, [{'field': 'Name', 'value': asset_name_new}], query_format={'fields': 'Owner', 'fields[Owner]': 'Name'} ) items = [item async for item in search] assert len(items) == 1 assert items[0]['Owner']['Name'] == 'Nobody' assert 'Status' not in items[0] rt-3.8.1/tests/test_rest1.py0000644000000000000000000003320413615410400012703 0ustar00"""Tests for Rt - Python interface to Request Tracker :term:`API`""" # ruff: noqa: S311 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ __docformat__ = 'reStructuredText en' __authors__ = [ '"Jiri Machalek" ', ] import random import string import unittest import requests.utils import rt.rest1 class RtTestCase(unittest.TestCase): rt.DEBUG_MODE = True RT_VALID_CREDENTIALS = { 'RT4.4 stable': { 'url': 'http://localhost:8080/REST/1.0/', 'support': { 'default_login': 'root', 'default_password': 'password', }, }, # HTTP timeout # 'RT4.6 dev': { # 'url': 'http://rt.easter-eggs.org/demos/4.6/REST/1.0', # 'admin': { # 'default_login': 'administrateur', # 'default_password': 'administrateur', # }, # 'john.foo': { # 'default_login': 'support', # 'default_password': 'support', # } # }, } RT_INVALID_CREDENTIALS = { 'RT4.4 stable (bad credentials)': { 'url': 'http://localhost:8080/REST/1.0/', 'default_login': 'idontexist', 'default_password': 'idonthavepassword', }, } RT_MISSING_CREDENTIALS = { 'RT4.4 stable (missing credentials)': { 'url': 'http://localhost:8080/REST/1.0/', }, } RT_BAD_URL = { 'RT (bad url)': { 'url': 'http://httpbin.org/status/404', 'default_login': 'idontexist', 'default_password': 'idonthavepassword', }, } def _have_creds(*creds_seq): return all(creds[name].get('url') for creds in creds_seq for name in creds) @staticmethod def _fix_unsecure_cookie(tracker: rt.rest1.Rt) -> None: """As of RT 5.0.4, cookies returned by the REST API are marked as secure by default. This breaks tests though as we are connecting via HTTP. This method fixes these cookies for the tests to work. """ cookies = requests.utils.dict_from_cookiejar(tracker.session.cookies) tracker.session.cookies.clear() tracker.session.cookies.update(cookies) @unittest.skipUnless( _have_creds(RT_VALID_CREDENTIALS, RT_INVALID_CREDENTIALS, RT_MISSING_CREDENTIALS, RT_BAD_URL), 'missing credentials required to run test', ) def test_login_and_logout(self): for name in self.RT_VALID_CREDENTIALS: tracker = rt.rest1.Rt(self.RT_VALID_CREDENTIALS[name]['url'], **self.RT_VALID_CREDENTIALS[name]['support']) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) # unsecure cookie self._fix_unsecure_cookie(tracker) self.assertTrue(tracker.logout(), 'Invalid logout from RT demo site ' + name) for name, params in self.RT_INVALID_CREDENTIALS.items(): tracker = rt.rest1.Rt(**params) self.assertFalse(tracker.login(), 'Login to RT demo site ' + name + ' should fail but did not') self.assertRaises(rt.exceptions.AuthorizationError, lambda: tracker.search()) # noqa: PLW0108 for _name, params in self.RT_MISSING_CREDENTIALS.items(): tracker = rt.rest1.Rt(**params) self.assertRaises(rt.exceptions.AuthorizationError, lambda: tracker.login()) # noqa: PLW0108 for _name, params in self.RT_BAD_URL.items(): tracker = rt.rest1.Rt(**params) self.assertRaises(rt.exceptions.UnexpectedResponseError, lambda: tracker.login()) # noqa: PLW0108 @unittest.skipUnless(_have_creds(RT_VALID_CREDENTIALS), 'missing credentials required to run test') def test_ticket_operations(self): ticket_subject = 'Testing issue ' + ''.join([random.choice(string.ascii_letters) for i in range(15)]) ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) for name in ('RT4.4 stable',): url = self.RT_VALID_CREDENTIALS[name]['url'] default_login = self.RT_VALID_CREDENTIALS[name]['support']['default_login'] default_password = self.RT_VALID_CREDENTIALS[name]['support']['default_password'] tracker = rt.rest1.Rt(url, default_login=default_login, default_password=default_password) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) # unsecure cookie self._fix_unsecure_cookie(tracker) # empty search result search_result = tracker.search(Subject=ticket_subject) self.assertEqual(search_result, [], 'Search for ticket with random subject returned non empty list.') # create ticket_id = tracker.create_ticket(Subject=ticket_subject, Text=ticket_text) self.assertTrue(ticket_id > -1, 'Creating ticket failed.') # search search_result = tracker.search(Subject=ticket_subject) self.assertEqual(len(search_result), 1, 'Created ticket is not found by the subject.') self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') self.assertEqual(search_result[0]['Status'], 'new', 'Bad status in search result of just created ticket.') # search all queues search_result = tracker.search(Queue=rt.rest1.ALL_QUEUES, Subject=ticket_subject) self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') # raw search search_result = tracker.search(raw_query=f'Subject="{ticket_subject}"') self.assertEqual(len(search_result), 1, 'Created ticket is not found by the subject.') self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') self.assertEqual(search_result[0]['Status'], 'new', 'Bad status in search result of just created ticket.') # raw search all queues search_result = tracker.search(Queue=rt.rest1.ALL_QUEUES, raw_query=f'Subject="{ticket_subject}"') self.assertEqual(search_result[0]['id'], 'ticket/' + str(ticket_id), 'Bad id in search result of just created ticket.') # get ticket ticket = tracker.get_ticket(ticket_id) self.assertEqual(ticket, search_result[0], 'Ticket get directly by its id is not equal to previous search result.') # edit ticket requestors = ['tester1@example.com', 'tester2@example.com'] tracker.edit_ticket(ticket_id, Status='open', Requestors=requestors) # get ticket (edited) ticket = tracker.get_ticket(ticket_id) self.assertEqual(ticket['Status'], 'open', 'Ticket status was not changed to open.') self.assertEqual(ticket['Requestors'], requestors, 'Ticket requestors were not added properly.') # get history hist = tracker.get_history(ticket_id) self.assertTrue(len(hist) > 0, 'Empty ticket history.') self.assertEqual(hist[0]['Content'], ticket_text, 'Ticket text was not receives is it was submited.') # get_short_history short_hist = tracker.get_short_history(ticket_id) self.assertTrue(len(short_hist) > 0, 'Empty ticket short history.') self.assertEqual(short_hist[0][1], f'Ticket created by {default_login}') # create 2nd ticket ticket2_subject = 'Testing issue ' + ''.join([random.choice(string.ascii_letters) for i in range(15)]) ticket2_id = tracker.create_ticket(Subject=ticket2_subject) self.assertTrue(ticket2_id > -1, 'Creating 2nd ticket failed.') # edit link self.assertTrue(tracker.edit_link(ticket_id, 'DependsOn', ticket2_id)) # get links links1 = tracker.get_links(ticket_id) self.assertTrue('DependsOn' in links1, 'Missing just created link DependsOn.') self.assertTrue(links1['DependsOn'][0].endswith('ticket/' + str(ticket2_id)), 'Unexpected value of link DependsOn.') links2 = tracker.get_links(ticket2_id) self.assertTrue('DependedOnBy' in links2, 'Missing just created link DependedOnBy.') self.assertTrue(links2['DependedOnBy'][0].endswith('ticket/' + str(ticket_id)), 'Unexpected value of link DependedOnBy.') # reply with attachment attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' reply_text = 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' # should provide a content type as RT 4.0 type guessing is broken (missing use statement for guess_media_type in REST.pm) self.assertTrue( tracker.reply(ticket_id, text=reply_text, files=[(attachment_name, attachment_content, 'text/plain')]), 'Reply to ticket returned False indicating error.', ) # attachments list at_list = tracker.get_attachments(ticket_id) self.assertTrue(at_list, 'Empty list with attachment ids, something went wrong.') at_names = [at[1] for at in at_list] self.assertTrue(attachment_name in at_names, 'Attachment name is not in the list of attachments.') # get the attachment and compare it's content at_id = at_list[at_names.index(attachment_name)][0] at_content = tracker.get_attachment_content(ticket_id, at_id) self.assertEqual(at_content, attachment_content, 'Recorded attachment is not equal to the original file.') # merge tickets self.assertTrue(tracker.merge_ticket(ticket2_id, ticket_id), 'Merging tickets failed.') # delete ticket self.assertTrue(tracker.edit_ticket(ticket_id, Status='deleted'), 'Ticket delete failed.') # get user self.assertIn('@', tracker.get_user(default_login)['EmailAddress']) @unittest.skipUnless(_have_creds(RT_VALID_CREDENTIALS), 'missing credentials required to run test') def test_ticket_operations_admincc_cc(self): ticket_subject = 'Testing issue ' + ''.join([random.choice(string.ascii_letters) for i in range(15)]) ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) for name in ('RT4.4 stable',): url = self.RT_VALID_CREDENTIALS[name]['url'] default_login = self.RT_VALID_CREDENTIALS[name]['support']['default_login'] default_password = self.RT_VALID_CREDENTIALS[name]['support']['default_password'] tracker = rt.rest1.Rt(url, default_login=default_login, default_password=default_password) self.assertTrue(tracker.login(), 'Invalid login to RT demo site ' + name) # unsecure cookie self._fix_unsecure_cookie(tracker) ticket_id = tracker.create_ticket(Subject=ticket_subject, Text=ticket_text) self.assertTrue(ticket_id > -1, 'Creating ticket failed.') # make sure Requestors, AdminCc and Cc are present and an empty list, as would be expected ticket = tracker.get_ticket(ticket_id) self.assertTrue(len(ticket['Requestors']) >= 0) self.assertTrue(len(ticket['AdminCc']) >= 0) self.assertTrue(len(ticket['Cc']) >= 0) # set requestors requestors = ['tester1@example.com', 'tester2@example.com'] tracker.edit_ticket(ticket_id, Status='open', Requestors=requestors) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) # set admincc admincc = ['tester2@example.com', 'tester3@example.com'] tracker.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) self.assertListEqual(admincc, ticket['AdminCc']) # update admincc admincc = ['tester2@example.com', 'tester3@example.com', 'tester4@example.com'] tracker.edit_ticket(ticket_id, Status='open', AdminCc=admincc) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) self.assertListEqual(admincc, ticket['AdminCc']) # unset requestors and admincc requestors = [] admincc = [] tracker.edit_ticket(ticket_id, Status='open', Requestors=requestors, AdminCc=admincc) # verify ticket = tracker.get_ticket(ticket_id) self.assertListEqual(requestors, ticket['Requestors']) self.assertListEqual(admincc, ticket['AdminCc']) if __name__ == '__main__': unittest.main() rt-3.8.1/tests/test_tickets.py0000644000000000000000000000617713615410400013324 0ustar00"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ __docformat__ = 'reStructuredText en' __authors__ = [ '"Jiri Machalek" ', '"Georges Toth" ', ] import base64 import rt.rest2 from . import random_string from .conftest import RT_QUEUE def test_ticket_attachments(rt_connection: rt.rest2.Rt): """Test various ticket attachment operations.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=[attachment]) assert ticket_id att_ids = rt_connection.get_attachments_ids(ticket_id) assert len(att_ids) == 1 att_list = rt_connection.get_attachments(ticket_id) assert len(att_list) == 1 att_names = [att['Filename'] for att in att_list] assert attachment_name in att_names # get the attachment and compare it's content att_id = att_list[att_names.index(attachment_name)]['id'] att_content = base64.b64decode(rt_connection.get_attachment(att_id)['Content']) assert att_content == attachment_content # test filter parameter att_ids = rt_connection.get_attachments_ids(ticket_id, query_filter=None) assert len(att_ids) == 1 att_ids = rt_connection.get_attachments_ids(ticket_id, query_filter=[]) assert len(att_ids) == 3 att_ids = rt_connection.get_attachments_ids(ticket_id, query_filter=[{'field': 'Filename', 'value': 'non-existant.txt'}]) assert not att_ids def test_ticket_take(rt_connection: rt.rest2.Rt): """Test take/untake.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) ticket_id = rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id assert rt_connection.take(ticket_id) assert rt_connection.untake(ticket_id) rt-3.8.1/tests/test_tickets_async.py0000644000000000000000000000675513615410400014523 0ustar00"""Tests for python-rt / REST2 - Python interface to Request Tracker :term:`API`.""" # ruff: noqa: S101 __license__ = """ Copyright (C) 2013 CZ.NIC, z.s.p.o. Copyright (c) 2021 CERT Gouvernemental (GOVCERT.LU) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ __docformat__ = 'reStructuredText en' __authors__ = [ '"Jiri Machalek" ', '"Georges Toth" ', ] import base64 import pytest import rt.rest2 from . import random_string from .conftest import RT_QUEUE @pytest.mark.asyncio async def test_ticket_attachments(async_rt_connection: rt.rest2.AsyncRt): """Test various ticket attachment operations.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) attachment_content = b'Content of attachment.' attachment_name = 'attachment-name.txt' attachment = rt.rest2.Attachment(attachment_name, 'text/plain', attachment_content) ticket_id = await async_rt_connection.create_ticket( subject=ticket_subject, content=ticket_text, queue=RT_QUEUE, attachments=[attachment] ) assert ticket_id att_ids = [item async for item in async_rt_connection.get_attachments_ids(ticket_id)] assert len(att_ids) == 1 att_list = [item async for item in async_rt_connection.get_attachments(ticket_id)] assert len(att_list) == 1 att_names = [att['Filename'] for att in att_list] assert attachment_name in att_names # get the attachment and compare it's content att_id = att_list[att_names.index(attachment_name)]['id'] att_content = base64.b64decode((await async_rt_connection.get_attachment(att_id))['Content']) assert att_content == attachment_content # test filter parameter att_ids = [item async for item in async_rt_connection.get_attachments_ids(ticket_id, query_filter=None)] assert len(att_ids) == 1 att_ids = [item async for item in async_rt_connection.get_attachments_ids(ticket_id, query_filter=[])] assert len(att_ids) == 3 att_ids = [ item async for item in async_rt_connection.get_attachments_ids( ticket_id, query_filter=[{'field': 'Filename', 'value': 'non-existant.txt'}] ) ] assert not att_ids @pytest.mark.asyncio async def test_ticket_take(async_rt_connection: rt.rest2.AsyncRt): """Test take/untake.""" ticket_subject = f'Testing issue {random_string()}' ticket_text = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' ) ticket_id = await async_rt_connection.create_ticket(subject=ticket_subject, content=ticket_text, queue=RT_QUEUE) assert ticket_id assert await async_rt_connection.take(ticket_id) assert await async_rt_connection.untake(ticket_id) rt-3.8.1/.gitignore0000644000000000000000000000020213615410400011052 0ustar00*.pyc .coverage coverage.xml uv.lock build dist rt.egg-info .idea .vscode .mypy_cache .pytest_cache doc/_build/ venv .ruff_cache rt-3.8.1/AUTHORS0000644000000000000000000000036413615410400010143 0ustar00Development Lead: community Maintainer: - Georges Toth Someone with write permissions - Edvard Rejthar Patches and Suggestions: - Stewart Perrygrove Original Author: - Jiří Machálek rt-3.8.1/LICENSE0000644000000000000000000010451313615410400010101 0ustar00 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . rt-3.8.1/README.rst0000644000000000000000000001032713615410400010562 0ustar00.. image:: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml/badge.svg :target: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml :alt: tests .. image:: https://readthedocs.org/projects/python-rt/badge/?version=stable :target: https://python-rt.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://badge.fury.io/py/rt.svg :target: https://badge.fury.io/py/rt ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: - https://rt-wiki.bestpractical.com/wiki/REST - https://docs.bestpractical.com/rt/6.0.3/RT/REST2.html .. csv-table:: Python version compatibility: :header: "Python", "rt" :widths: 15, 15 "2.7", "< 2.0.0" ">= 3.5, <3.7", ">= 2.0.0, < 3.0.0" ">= 3.7", ">= 3.0.0, < 3.1.0" ">= 3.8", ">= 3.0.0, < 3.3.0" ">= 3.9", ">= 3.3.0, < 3.7.0" ">= 3.10", ">= 3.7.0" ℹ️ **Note**: Please note that starting with the release of v3.7.0, this library requires Python version >= 3.10. See the *Python version compatibility* table above for more detailed information. ⚡ **Note**: As of version 3.1.0, this library is async compatible. Usage:: import rt.rest2 import httpx2 tracker = rt.rest2.AsyncRt('http://localhost/rt/REST/2.0/', http_auth=httpx2.BasicAuth('root', 'password')) ⚠️ **Warning**: Though version 3.x still supports RT REST API version 1, it contains minor breaking changes. Please see the changelog in the documentation for details. Documentation ============= https://python-rt.readthedocs.io/en/latest/ Installation ============ Install the python-rt package using:: pip install rt Licence ======= This module is distributed under the terms of GNU General Public Licence v3 and was developed by CZ.NIC Labs - research and development department of CZ.NIC association - top level domain registry for .CZ. Copy of the GNU General Public License is distributed along with this module. Usage ===== An example is worth a thousand words:: >>> import rt.rest2 >>> import httpx2 >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx2.BasicAuth('root', 'password')) >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['1', '2', '10', '15'] >>> tracker.create_ticket(queue='helpdesk', \ ... subject='Coffee (important)', content='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestor='addicted@example.com') True >>> tracker.reply(19, content='Do you know Starbucks?') True Get the last important updates from a specific queue that have been updated recently:: >>> import datetime >>> import base64 >>> import rt.rest2 >>> import httpx2 >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx2.BasicAuth('root', 'password')) >>> fifteen_minutes_ago = str(datetime.datetime.now() - datetime.timedelta(minutes=15)) >>> tickets = tracker.last_updated(since=fifteen_minutes_ago) >>> for ticket in tickets: >>> id = ticket['id'] >>> history = tracker.get_ticket_history(id) >>> last_update = list(reversed([h for h in history if h['Type'] in ('Correspond', 'Comment')])) >>> hid = tracker.get_transaction(last_update[0]['id'] if last_update else history[0]['id']) >>> >>> attachment_id = None >>> for k in hid['_hyperlinks']: >>> if k['ref'] == 'attachment': >>> attachment_id = k['_url'].rsplit('/', 1)[1] >>> break >>> >>> if attachment_id is not None: >>> attachment = tracker.get_attachment(attachment_id) >>> if attachment['Content'] is not None: >>> content = base64.b64decode(attachment['Content']).decode() >>> print(content) Please use docstrings to see how to use different functions. They are written in ReStructuredText. You can also generate HTML documentation by running ``make html`` in doc directory (Sphinx required). Official Site ============= Project site, issue tracking and git repository: https://github.com/python-rt/python-rt rt-3.8.1/pyproject.toml0000644000000000000000000001126613615410400012012 0ustar00[build-system] requires = ["hatchling", "hatch-vcs"] build-backend = "hatchling.build" [project] name = "rt" description = "Python interface to Request Tracker API" readme = "README.rst" license = { text = "GNU General Public License v3 (GPLv3)" } authors = [{ name = "Georges Toth", email = "georges.toth@govcert.etat.lu" }] classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: POSIX", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ] requires-python = ">= 3.10" dependencies = [ "httpx2~=2.7", "requests~=2.32", ] dynamic = ["version"] [project.urls] Homepage = "https://github.com/python-rt/python-rt" Documentation = "https://python-rt.readthedocs.io/" Source = "https://github.com/python-rt/python-rt" Tracker = "https://github.com/python-rt/python-rt/issues" Changelog = "https://github.com/python-rt/python-rt/blob/master/CHANGELOG.md" [dependency-groups] docs = [ "sphinx", "sphinx-autodoc-typehints", "sphinx-rtd-theme", "furo", "sphinx-copybutton", ] dev = [ "mypy", "ruff", "types-requests", "codespell", "bandit", "prek>=0.3.2", ] test = [ "pytest~=9.1", "pytest-asyncio~=1.4", "coverage~=7.6", ] [tool.hatch.envs.default] installer = "uv" [tool.hatch.build.targets.sdist] include = [ "/rt", "/tests", ] exclude = [] [tool.hatch.version] source = "vcs" [tool.mypy] show_error_codes = true show_error_context = true show_column_numbers = true ignore_missing_imports = true disallow_incomplete_defs = true disallow_untyped_defs = true disallow_untyped_calls = false warn_no_return = true warn_redundant_casts = true warn_unused_ignores = true strict_optional = true check_untyped_defs = false files = [ "rt/**/*.py" ] [tool.pytest.ini_options] minversion = "8.0" asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "session" testpaths = [ "tests" ] [tool.ruff] line-length = 140 indent-width = 4 target-version = "py310" include = [ "pyproject.toml", "rt/**/*.py", "tests/**/*.py" ] [tool.ruff.lint] select = [ "E", # pycodestyle errors "W", # pycodestyle warnings "F", # pyflakes "I", # isort "C", # flake8-comprehensions "B", # flake8-bugbear "D", # pydocstyle "N", # pep8-naming "UP", # pyupgrade "YTT", # flake8-2020 "ANN", # flake8-annotations "ASYNC", # flake8-async "S", # flake8-bandit "BLE", # flake8-blind-except "B", # flake8-bugbear "A", # flake8-builtins "COM", # flake8-commas "C4", # flake8-comprehensions "DTZ", # flake8-datetimez "EM103", # flake8-errmsg - dot-format-in-exception "EXE", # flake8-executable "ISC", # flake8-implicit-str-concat "ICN", # flake8-import-conventions "G", # flake8-logging-format "INP", # flake8-no-pep420 "PIE", # flake8-pie "T20", # flake8-print "PYI", # flake8-pyi "RSE", # flake8-raise "RET", # flake8-return "SLF", # flake8-self "SLOT", # flake8-slots # "SIM", # flake8-simplify "TID", # flake8-tidy-imports "TCH", # flake8-type-checking "PTH", # flake8-use-pathlib "TD", # flake8-todos "FIX", # flake8-fixme "ERA", # eradicate "PL", # Pylint "PLC", # Convention "PLE", # Error "PLR", # Refactor "PLW", # Warning "B904", # reraise-no-cause "FLY", # flynt # "PERF", # Perflint "RUF013", # implicit-optional ] unfixable = [ 'ERA001', 'T201', # `print` found ] extend-select = ['Q', 'RUF100', 'C90'] flake8-quotes = { inline-quotes = 'single', multiline-quotes = 'single' } ignore = [ "C901", # too complex "E501", # line too long "B008", # do not perform function call in argument defaults "ANN401", # any-type "ANN002", # missing-type-args "ANN003", # missing-type-kwargs "PLR0913", # Too many arguments to function call "PLR0915", # Too many statements "PLR2004", # Magic value used in comparison "PLW0603", # Using the global statement "PLR0912", # Too many branches "COM812", # missing-trailing-comma "ISC001", # single-line-implicit-string-concatenation "Q001", # bad-quotes-multiline-string "RET504", # Unnecessary assignment before `return` statement "D401", # First line of docstring should be in imperative mood "D205", # 1 blank line required between summary line and description ] [tool.ruff.lint.per-file-ignores] "tests/**" = [ "ANN", # Missing return type annotation "D", # Missing docstring "ERA001", # Found commented-out code ] "rt/rest1.py" = [ "N803", # Argument name should be lowercase ] [tool.ruff.format] quote-style = "single" [tool.ruff.lint.pydocstyle] convention = "numpy" rt-3.8.1/PKG-INFO0000644000000000000000000001255413615410400010174 0ustar00Metadata-Version: 2.5 Name: rt Version: 3.8.1 Summary: Python interface to Request Tracker API Project-URL: Homepage, https://github.com/python-rt/python-rt Project-URL: Documentation, https://python-rt.readthedocs.io/ Project-URL: Source, https://github.com/python-rt/python-rt Project-URL: Tracker, https://github.com/python-rt/python-rt/issues Project-URL: Changelog, https://github.com/python-rt/python-rt/blob/master/CHANGELOG.md Author-email: Georges Toth License: GNU General Public License v3 (GPLv3) License-File: AUTHORS License-File: LICENSE Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: POSIX Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=3.10 Requires-Dist: httpx2~=2.7 Requires-Dist: requests~=2.32 Description-Content-Type: text/x-rst .. image:: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml/badge.svg :target: https://github.com/python-rt/python-rt/actions/workflows/test_lint.yml :alt: tests .. image:: https://readthedocs.org/projects/python-rt/badge/?version=stable :target: https://python-rt.readthedocs.io/en/stable/?badge=stable :alt: Documentation Status .. image:: https://badge.fury.io/py/rt.svg :target: https://badge.fury.io/py/rt ============================================== Rt - Python interface to Request Tracker API ============================================== Python implementation of REST API described here: - https://rt-wiki.bestpractical.com/wiki/REST - https://docs.bestpractical.com/rt/6.0.3/RT/REST2.html .. csv-table:: Python version compatibility: :header: "Python", "rt" :widths: 15, 15 "2.7", "< 2.0.0" ">= 3.5, <3.7", ">= 2.0.0, < 3.0.0" ">= 3.7", ">= 3.0.0, < 3.1.0" ">= 3.8", ">= 3.0.0, < 3.3.0" ">= 3.9", ">= 3.3.0, < 3.7.0" ">= 3.10", ">= 3.7.0" ℹ️ **Note**: Please note that starting with the release of v3.7.0, this library requires Python version >= 3.10. See the *Python version compatibility* table above for more detailed information. ⚡ **Note**: As of version 3.1.0, this library is async compatible. Usage:: import rt.rest2 import httpx2 tracker = rt.rest2.AsyncRt('http://localhost/rt/REST/2.0/', http_auth=httpx2.BasicAuth('root', 'password')) ⚠️ **Warning**: Though version 3.x still supports RT REST API version 1, it contains minor breaking changes. Please see the changelog in the documentation for details. Documentation ============= https://python-rt.readthedocs.io/en/latest/ Installation ============ Install the python-rt package using:: pip install rt Licence ======= This module is distributed under the terms of GNU General Public Licence v3 and was developed by CZ.NIC Labs - research and development department of CZ.NIC association - top level domain registry for .CZ. Copy of the GNU General Public License is distributed along with this module. Usage ===== An example is worth a thousand words:: >>> import rt.rest2 >>> import httpx2 >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx2.BasicAuth('root', 'password')) >>> map(lambda x: x['id'], tracker.search(Queue='helpdesk', Status='open')) ['1', '2', '10', '15'] >>> tracker.create_ticket(queue='helpdesk', \ ... subject='Coffee (important)', content='Help I Ran Out of Coffee!') 19 >>> tracker.edit_ticket(19, Requestor='addicted@example.com') True >>> tracker.reply(19, content='Do you know Starbucks?') True Get the last important updates from a specific queue that have been updated recently:: >>> import datetime >>> import base64 >>> import rt.rest2 >>> import httpx2 >>> tracker = rt.rest2.Rt('http://localhost/rt/REST/2.0/', http_auth=httpx2.BasicAuth('root', 'password')) >>> fifteen_minutes_ago = str(datetime.datetime.now() - datetime.timedelta(minutes=15)) >>> tickets = tracker.last_updated(since=fifteen_minutes_ago) >>> for ticket in tickets: >>> id = ticket['id'] >>> history = tracker.get_ticket_history(id) >>> last_update = list(reversed([h for h in history if h['Type'] in ('Correspond', 'Comment')])) >>> hid = tracker.get_transaction(last_update[0]['id'] if last_update else history[0]['id']) >>> >>> attachment_id = None >>> for k in hid['_hyperlinks']: >>> if k['ref'] == 'attachment': >>> attachment_id = k['_url'].rsplit('/', 1)[1] >>> break >>> >>> if attachment_id is not None: >>> attachment = tracker.get_attachment(attachment_id) >>> if attachment['Content'] is not None: >>> content = base64.b64decode(attachment['Content']).decode() >>> print(content) Please use docstrings to see how to use different functions. They are written in ReStructuredText. You can also generate HTML documentation by running ``make html`` in doc directory (Sphinx required). Official Site ============= Project site, issue tracking and git repository: https://github.com/python-rt/python-rt