From 9f9f4842144ca7896498f5ee2f0c5a065a3a2f6b Mon Sep 17 00:00:00 2001 From: Axel Suarez Date: Mon, 22 Jul 2019 15:38:46 -0700 Subject: [PATCH] Pylint fixes for botbuilder-ai library code and tests --- .../botbuilder/ai/luis/activity_util.py | 11 +- .../botbuilder/ai/luis/luis_application.py | 6 +- .../ai/luis/luis_prediction_options.py | 2 +- .../botbuilder/ai/luis/luis_recognizer.py | 34 +++--- .../botbuilder/ai/luis/luis_util.py | 104 +++++++++--------- .../botbuilder/ai/qna/qnamaker.py | 45 ++++---- .../botbuilder/ai/qna/qnamaker_options.py | 5 +- .../ai/qna/qnamaker_telemetry_client.py | 2 +- .../botbuilder/ai/qna/query_result.py | 4 +- .../tests/luis/luis_application_test.py | 15 ++- .../tests/luis/luis_recognizer_test.py | 27 +++-- libraries/botbuilder-ai/tests/qna/test_qna.py | 31 +++--- 12 files changed, 148 insertions(+), 138 deletions(-) diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py b/libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py index 3db60182c..d2656a3ba 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py +++ b/libraries/botbuilder-ai/botbuilder/ai/luis/activity_util.py @@ -11,7 +11,7 @@ ) -class ActivityUtil(object): +class ActivityUtil: @staticmethod def create_trace( turn_activity: Activity, @@ -26,11 +26,14 @@ def create_trace( :type turn_activity: Activity :param name: The value to assign to the trace activity's property. :type name: str - :param value: The value to assign to the trace activity's property., defaults to None + :param value: The value to assign to the trace activity's property., defaults + to None :param value: object, optional - :param value_type: The value to assign to the trace activity's property, defaults to None + :param value_type: The value to assign to the trace activity's property, + defaults to None :param value_type: str, optional - :param label: The value to assign to the trace activity's property, defaults to None + :param label: The value to assign to the trace activity's property, defaults + to None :param label: str, optional :return: The created trace activity. :rtype: Activity diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py index 364b9924e..8d8f8e09d 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py +++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_application.py @@ -7,21 +7,20 @@ from uuid import UUID, uuid4 -class LuisApplication(object): +class LuisApplication: """ Data describing a LUIS application. """ def __init__(self, application_id: str, endpoint_key: str, endpoint: str): """Initializes a new instance of the class. - :param application_id: LUIS application ID. :type application_id: str :param endpoint_key: LUIS subscription or endpoint key. :type endpoint_key: str :param endpoint: LUIS endpoint to use like https://westus.api.cognitive.microsoft.com. :type endpoint: str - :raises ValueError: + :raises ValueError: :raises ValueError: :raises ValueError: """ @@ -48,7 +47,6 @@ def __init__(self, application_id: str, endpoint_key: str, endpoint: str): @classmethod def from_application_endpoint(cls, application_endpoint: str): """Initializes a new instance of the class. - :param application_endpoint: LUIS application endpoint. :type application_endpoint: str :return: diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_prediction_options.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_prediction_options.py index 8dd350f1b..335e98b08 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_prediction_options.py +++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_prediction_options.py @@ -4,7 +4,7 @@ from botbuilder.core import BotTelemetryClient, NullTelemetryClient -class LuisPredictionOptions(object): +class LuisPredictionOptions: """ Optional parameters for a LUIS prediction request. """ diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py index bd70d2721..55caa3b8d 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py +++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py @@ -10,20 +10,18 @@ from botbuilder.core import ( BotAssert, - BotTelemetryClient, IntentScore, - NullTelemetryClient, RecognizerResult, TurnContext, ) -from botbuilder.schema import Activity, ActivityTypes, ChannelAccount +from botbuilder.schema import ActivityTypes from . import LuisApplication, LuisPredictionOptions, LuisTelemetryConstants from .activity_util import ActivityUtil from .luis_util import LuisUtil -class LuisRecognizer(object): +class LuisRecognizer: """ A LUIS based implementation of . """ @@ -41,7 +39,6 @@ def __init__( include_api_results: bool = False, ): """Initializes a new instance of the class. - :param application: The LUIS application to use to recognize text. :type application: LuisApplication :param prediction_options: The LUIS prediction options to use, defaults to None @@ -77,12 +74,12 @@ def top_intent( results: RecognizerResult, default_intent: str = "None", min_score: float = 0.0 ) -> str: """Returns the name of the top scoring intent from a set of LUIS results. - :param results: Result set to be searched. :type results: RecognizerResult :param default_intent: Intent name to return should a top intent be found, defaults to "None" :param default_intent: str, optional - :param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the set are below this threshold then the `defaultIntent` will be returned, defaults to 0.0 + :param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the + set are below this threshold then the `defaultIntent` will be returned, defaults to 0.0 :param min_score: float, optional :raises TypeError: :return: The top scoring intent name. @@ -111,12 +108,13 @@ async def recognize( luis_prediction_options: LuisPredictionOptions = None, ) -> RecognizerResult: """Return results of the analysis (Suggested actions and intents). - :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext - :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None + :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults + to None :param telemetry_properties: Dict[str, str], optional - :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None + :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to + None :param telemetry_metrics: Dict[str, float], optional :return: The LUIS results of the analysis of the current message text in the current turn's context activity. :rtype: RecognizerResult @@ -137,14 +135,15 @@ def on_recognizer_result( telemetry_metrics: Dict[str, float] = None, ): """Invoked prior to a LuisResult being logged. - :param recognizer_result: The Luis Results for the call. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext - :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None + :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults + to None :param telemetry_properties: Dict[str, str], optional - :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to None + :param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to + None :param telemetry_metrics: Dict[str, float], optional """ @@ -159,7 +158,7 @@ def on_recognizer_result( @staticmethod def _get_top_k_intent_score( - intent_names: List[str], intents: Dict[str, IntentScore], index: int + intent_names: List[str], intents: Dict[str, IntentScore], index: int # pylint: disable=unused-argument ) -> Tuple[str, str]: intent_name = "" intent_score = "0.00" @@ -178,14 +177,15 @@ def fill_luis_event_properties( ) -> Dict[str, str]: """Fills the event properties for LuisResult event for telemetry. These properties are logged when the recognizer is called. - :param recognizer_result: Last activity sent from user. :type recognizer_result: RecognizerResult :param turn_context: Context object containing information for a single turn of conversation with a user. :type turn_context: TurnContext - :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults to None + :param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, + defaults to None :param telemetry_properties: Dict[str, str], optional - :return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the BotMessageSend event. + :return: A dictionary that is sent as "Properties" to IBotTelemetryClient.TrackEvent method for the + BotMessageSend event. :rtype: Dict[str, str] """ diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py index 246e1539c..d9ea75df8 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py +++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py @@ -3,7 +3,7 @@ import platform from collections import OrderedDict -from typing import Dict, List, Set, Union +from typing import Dict, List, Union import azure.cognitiveservices.language.luis.runtime.models as runtime_models from azure.cognitiveservices.language.luis.runtime.models import ( @@ -11,8 +11,8 @@ EntityModel, LuisResult, ) -from botbuilder.core import IntentScore, RecognizerResult from msrest import Serializer +from botbuilder.core import IntentScore, RecognizerResult from .. import __title__, __version__ @@ -35,12 +35,11 @@ def get_intents(luis_result: LuisResult) -> Dict[str, IntentScore]: LuisUtil.normalized_intent(i.intent): IntentScore(i.score or 0) for i in luis_result.intents } - else: - return { - LuisUtil.normalized_intent( - luis_result.top_scoring_intent.intent - ): IntentScore(luis_result.top_scoring_intent.score or 0) - } + return { + LuisUtil.normalized_intent( + luis_result.top_scoring_intent.intent + ): IntentScore(luis_result.top_scoring_intent.score or 0) + } @staticmethod def extract_entities_and_metadata( @@ -58,9 +57,9 @@ def extract_entities_and_metadata( if composite_entities: composite_entity_types = set(ce.parent_type for ce in composite_entities) current = entities - for compositeEntity in composite_entities: + for composite_entity in composite_entities: current = LuisUtil.populate_composite_entity_model( - compositeEntity, current, entities_and_metadata, verbose + composite_entity, current, entities_and_metadata, verbose ) entities = current @@ -90,12 +89,12 @@ def number(value: object) -> Union[int, float]: return None try: - s = str(value) - i = int(s) - return i + str_value = str(value) + int_value = int(str_value) + return int_value except ValueError: - f = float(s) - return f + float_value = float(str_value) + return float_value @staticmethod def extract_entity_value(entity: EntityModel) -> object: @@ -108,7 +107,7 @@ def extract_entity_value(entity: EntityModel) -> object: resolution = entity.additional_properties["resolution"] if entity.type.startswith("builtin.datetime."): return resolution - elif entity.type.startswith("builtin.datetimeV2."): + if entity.type.startswith("builtin.datetimeV2."): if not resolution["values"]: return resolution @@ -117,32 +116,31 @@ def extract_entity_value(entity: EntityModel) -> object: timexes = [val["timex"] for val in resolution_values] distinct_timexes = list(OrderedDict.fromkeys(timexes)) return {"type": val_type, "timex": distinct_timexes} - else: - if entity.type in {"builtin.number", "builtin.ordinal"}: - return LuisUtil.number(resolution["value"]) - elif entity.type == "builtin.percentage": - svalue = str(resolution["value"]) - if svalue.endswith("%"): - svalue = svalue[:-1] - - return LuisUtil.number(svalue) - elif entity.type in { - "builtin.age", - "builtin.dimension", - "builtin.currency", - "builtin.temperature", - }: - units = resolution["unit"] - val = LuisUtil.number(resolution["value"]) - obj = {} - if val is not None: - obj["number"] = val - - obj["units"] = units - return obj - else: - value = resolution.get("value") - return value if value is not None else resolution.get("values") + + if entity.type in {"builtin.number", "builtin.ordinal"}: + return LuisUtil.number(resolution["value"]) + if entity.type == "builtin.percentage": + svalue = str(resolution["value"]) + if svalue.endswith("%"): + svalue = svalue[:-1] + + return LuisUtil.number(svalue) + if entity.type in { + "builtin.age", + "builtin.dimension", + "builtin.currency", + "builtin.temperature", + }: + units = resolution["unit"] + val = LuisUtil.number(resolution["value"]) + obj = {} + if val is not None: + obj["number"] = val + + obj["units"] = units + return obj + value = resolution.get("value") + return value if value is not None else resolution.get("values") @staticmethod def extract_entity_metadata(entity: EntityModel) -> Dict: @@ -202,10 +200,10 @@ def populate_composite_entity_model( # This is now implemented as O(n^2) search and can be reduced to O(2n) using a map as an optimization if n grows composite_entity_metadata = next( ( - e - for e in entities - if e.type == composite_entity.parent_type - and e.entity == composite_entity.value + ent + for ent in entities + if ent.type == composite_entity.parent_type + and ent.entity == composite_entity.value ), None, ) @@ -310,7 +308,7 @@ def recognizer_result_as_dict( for name, intent_score in recognizer_result.intents.items() } if recognizer_result.intents is not None else None - d: Dict[str, object] = { + dictionary: Dict[str, object] = { "text": recognizer_result.text, "alteredText": recognizer_result.altered_text, "intents": intents, @@ -319,13 +317,13 @@ def recognizer_result_as_dict( if recognizer_result.properties is not None: for key, value in recognizer_result.properties.items(): - if key not in d: + if key not in dictionary: if isinstance(value, LuisResult): - d[key] = LuisUtil.luis_result_as_dict(value) + dictionary[key] = LuisUtil.luis_result_as_dict(value) else: - d[key] = value + dictionary[key] = value - return d + return dictionary @staticmethod def intent_score_as_dict(intent_score: IntentScore) -> Dict[str, float]: @@ -343,5 +341,5 @@ def luis_result_as_dict(luis_result: LuisResult) -> Dict[str, object]: k: v for k, v in runtime_models.__dict__.items() if isinstance(v, type) } serializer = Serializer(client_models) - d = serializer.body(luis_result, "LuisResult") - return d + result = serializer.body(luis_result, "LuisResult") + return result diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py index e30991407..adbd6256a 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py +++ b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py @@ -1,15 +1,15 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from aiohttp import ClientSession, ClientTimeout, ClientResponse +from copy import copy +import json +import platform +from typing import Dict, NamedTuple, Union +from aiohttp import ClientSession, ClientTimeout, ClientResponse from botbuilder.schema import Activity from botbuilder.core import BotTelemetryClient, NullTelemetryClient, TurnContext -from copy import copy -import json, platform, requests -from typing import Dict, List, NamedTuple, Union -from .metadata import Metadata from .query_result import QueryResult from .qnamaker_endpoint import QnAMakerEndpoint from .qnamaker_options import QnAMakerOptions @@ -30,11 +30,11 @@ class EventData(NamedTuple): class QnAMaker(QnAMakerTelemetryClient): - """ - Class used to query a QnA Maker knowledge base for answers. + """ + Class used to query a QnA Maker knowledge base for answers. """ - def __init__( + def __init__( # pylint: disable=super-init-not-called self, endpoint: QnAMakerEndpoint, options: QnAMakerOptions = None, @@ -49,7 +49,8 @@ def __init__( if endpoint.host.endswith("v2.0"): raise ValueError( - "v2.0 of QnA Maker service is no longer supported in the Bot Framework. Please upgrade your QnA Maker service at www.qnamaker.ai." + "v2.0 of QnA Maker service is no longer supported in the Bot Framework. Please upgrade your QnA Maker" + " service at www.qnamaker.ai." ) self._endpoint: str = endpoint @@ -92,9 +93,9 @@ async def fill_qna_event( ) -> EventData: """ Fills the event properties and metrics for the QnaMessage event for telemetry. - - :return: A tuple of event data properties and metrics that will be sent to the BotTelemetryClient.track_event() method for the QnAMessage event. The properties and metrics returned the standard properties logged with any properties passed from the get_answers() method. - + :return: A tuple of event data properties and metrics that will be sent to the BotTelemetryClient.track_event() + method for the QnAMessage event. The properties and metrics returned the standard properties logged with any + properties passed from the get_answers() method. :rtype: EventData """ @@ -106,18 +107,18 @@ async def fill_qna_event( ] = self._endpoint.knowledge_base_id text: str = turn_context.activity.text - userName: str = turn_context.activity.from_property.name + user_name: str = turn_context.activity.from_property.name # Use the LogPersonalInformation flag to toggle logging PII data; text and username are common examples. if self.log_personal_information: if text: properties[QnATelemetryConstants.question_property] = text - if userName: - properties[QnATelemetryConstants.username_property] = userName + if user_name: + properties[QnATelemetryConstants.username_property] = user_name # Fill in Qna Results (found or not). - if len(query_results) > 0: + if query_results: query_result = query_results[0] result_properties = { @@ -160,9 +161,7 @@ async def get_answers( ) -> [QueryResult]: """ Generates answers from the knowledge base. - :return: A list of answers for the user's query, sorted in decreasing order of ranking score. - :rtype: [QueryResult] """ @@ -200,10 +199,10 @@ def _validate_options(self, options: QnAMakerOptions): def _hydrate_options(self, query_options: QnAMakerOptions) -> QnAMakerOptions: """ - Combines QnAMakerOptions passed into the QnAMaker constructor with the options passed as arguments into get_answers(). - - :return: QnAMakerOptions with options passed into constructor overwritten by new options passed into get_answers() - + Combines QnAMakerOptions passed into the QnAMaker constructor with the options passed as arguments + into get_answers(). + :return: QnAMakerOptions with options passed into constructor overwritten by new options passed into + get_answers() :rtype: QnAMakerOptions """ @@ -219,7 +218,7 @@ def _hydrate_options(self, query_options: QnAMakerOptions) -> QnAMakerOptions: if query_options.top != hydrated_options.top and query_options.top != 0: hydrated_options.top = query_options.top - if len(query_options.strict_filters) > 0: + if query_options.strict_filters: hydrated_options.strict_filters = query_options.strict_filters if ( diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_options.py b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_options.py index a883a84da..42cf0f0ce 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_options.py +++ b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_options.py @@ -3,6 +3,7 @@ from .metadata import Metadata + # figure out if 300 milliseconds is ok for python requests library...or 100000 class QnAMakerOptions: def __init__( @@ -10,9 +11,9 @@ def __init__( score_threshold: float = 0.0, timeout: int = 0, top: int = 0, - strict_filters: [Metadata] = [], + strict_filters: [Metadata] = None, ): self.score_threshold = score_threshold self.timeout = timeout self.top = top - self.strict_filters = strict_filters + self.strict_filters = strict_filters or [] diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_telemetry_client.py b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_telemetry_client.py index 4611edaa3..4a09a4beb 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_telemetry_client.py +++ b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker_telemetry_client.py @@ -2,9 +2,9 @@ # Licensed under the MIT License. from abc import ABC, abstractmethod +from typing import Dict from botbuilder.core import BotTelemetryClient, TurnContext from .qnamaker_options import QnAMakerOptions -from typing import Dict class QnAMakerTelemetryClient(ABC): diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py b/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py index b2047a80a..f1a13ec0b 100644 --- a/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py +++ b/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py @@ -12,7 +12,7 @@ def __init__( score: float, metadata: [Metadata], source: str, - id: int, + id: int, # pylint: disable=invalid-name context=None, ): self.questions = (questions,) @@ -20,7 +20,7 @@ def __init__( self.score = (score,) self.metadata = (list(map(lambda meta: Metadata(**meta), metadata)),) self.source = source - self.id = id + self.id = id # pylint: disable=invalid-name # 4.4 multi-turn self.context = context diff --git a/libraries/botbuilder-ai/tests/luis/luis_application_test.py b/libraries/botbuilder-ai/tests/luis/luis_application_test.py index 7f810850a..d34ef53c0 100644 --- a/libraries/botbuilder-ai/tests/luis/luis_application_test.py +++ b/libraries/botbuilder-ai/tests/luis/luis_application_test.py @@ -30,10 +30,10 @@ def test_luis_application_construction(self) -> None: with self.assertRaises(ValueError): LuisApplication(app_id, key, LuisApplicationTest.endpoint) - luisApp = LuisApplication( + luis_app = LuisApplication( str(uuid4()), str(uuid4()), LuisApplicationTest.endpoint ) - self.assertEqual(LuisApplicationTest.endpoint, luisApp.endpoint) + self.assertEqual(LuisApplicationTest.endpoint, luis_app.endpoint) @unittest.skip("revisit") def test_luis_application_serialization(self) -> None: @@ -48,7 +48,10 @@ def test_list_application_from_luis_endpoint(self) -> None: # Arrange # Note this is NOT a real LUIS application ID nor a real LUIS subscription-key # theses are GUIDs edited to look right to the parsing and validation code. - endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" + endpoint = \ + "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" \ + "b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360" \ + "&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" # Act app = LuisApplication.from_application_endpoint(endpoint) @@ -61,8 +64,10 @@ def test_list_application_from_luis_endpoint(self) -> None: def test_list_application_from_luis_endpoint_bad_arguments(self) -> None: application_endpoint_data: List[str] = [ "this.is.not.a.uri", - "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&q=", - "https://westus.api.cognitive.microsoft.com?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=", + "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" + "b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&q=", + "https://westus.api.cognitive.microsoft.com?" + "verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=", ] for application_endpoint in application_endpoint_data: diff --git a/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py b/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py index 1705ecf93..8eb02a587 100644 --- a/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py +++ b/libraries/botbuilder-ai/tests/luis/luis_recognizer_test.py @@ -1,6 +1,8 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +# pylint: disable=protected-access + import json from os import path from typing import Dict, Tuple, Union @@ -23,7 +25,6 @@ BotTelemetryClient, IntentScore, RecognizerResult, - TopIntent, TurnContext, ) from botbuilder.core.adapters import TestAdapter @@ -54,7 +55,9 @@ def __init__(self, *args, **kwargs): def test_luis_recognizer_construction(self): # Arrange - endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" + endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" \ + "b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360" \ + "&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" # Act recognizer = LuisRecognizer(endpoint) @@ -66,7 +69,9 @@ def test_luis_recognizer_construction(self): self.assertEqual("https://westus.api.cognitive.microsoft.com", app.endpoint) def test_luis_recognizer_timeout(self): - endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" + endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" \ + "b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360" \ + "&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" expected_timeout = 300 options_with_timeout = LuisPredictionOptions(timeout=expected_timeout * 1000) @@ -431,7 +436,9 @@ def test_telemetry_construction(self): # Arrange # Note this is NOT a real LUIS application ID nor a real LUIS subscription-key # theses are GUIDs edited to look right to the parsing and validation code. - endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" + endpoint = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" \ + "b31aeaf3-3511-495b-a07f-571fc873214b?verbose=true&timezoneOffset=-360" \ + "&subscription-key=048ec46dc58e495482b0c447cfdbd291&q=" # Act recognizer = LuisRecognizer(endpoint) @@ -714,13 +721,13 @@ async def _test_json(self, response_file: str) -> None: self.assertEqual(trimmed_expected, trimmed_actual) @staticmethod - def _remove_none_property(d: Dict[str, object]) -> Dict[str, object]: - for key, value in list(d.items()): + def _remove_none_property(dictionary: Dict[str, object]) -> Dict[str, object]: + for key, value in list(dictionary.items()): if value is None: - del d[key] + del dictionary[key] elif isinstance(value, dict): LuisRecognizerTest._remove_none_property(value) - return d + return dictionary @classmethod async def _get_recognizer_result( @@ -761,8 +768,8 @@ def _get_json_for_file(cls, response_file: str) -> Dict[str, object]: curr_dir = path.dirname(path.abspath(__file__)) response_path = path.join(curr_dir, "test_data", response_file) - with open(response_path, "r", encoding="utf-8-sig") as f: - response_str = f.read() + with open(response_path, "r", encoding="utf-8-sig") as file: + response_str = file.read() response_json = json.loads(response_str) return response_json diff --git a/libraries/botbuilder-ai/tests/qna/test_qna.py b/libraries/botbuilder-ai/tests/qna/test_qna.py index 93b67dbd5..7a72b596c 100644 --- a/libraries/botbuilder-ai/tests/qna/test_qna.py +++ b/libraries/botbuilder-ai/tests/qna/test_qna.py @@ -1,16 +1,16 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +# pylint: disable=protected-access + import json -import aiounittest, unittest, requests from os import path -from requests.models import Response -from typing import List, Tuple, Dict, Union -from uuid import uuid4 -from unittest.mock import Mock, patch, MagicMock -from asyncio import Future -from aiohttp import ClientSession, ClientTimeout, ClientResponse +from typing import List, Dict +import unittest +from unittest.mock import patch +from aiohttp import ClientSession +import aiounittest from botbuilder.ai.qna import ( Metadata, QnAMakerEndpoint, @@ -22,7 +22,6 @@ from botbuilder.core import ( BotAdapter, BotTelemetryClient, - NullTelemetryClient, TurnContext, ) from botbuilder.core.adapters import TestAdapter @@ -30,7 +29,6 @@ Activity, ActivityTypes, ChannelAccount, - ResourceResponse, ConversationAccount, ) @@ -42,7 +40,7 @@ def __init__(self, request): self.on_send_activities(self.capture_sent_activities) - async def capture_sent_activities(self, context: TurnContext, activities, next): + async def capture_sent_activities(self, context: TurnContext, activities, next): # pylint: disable=unused-argument self.sent += activities context.responded = True @@ -614,7 +612,8 @@ async def test_telemetry_fill_props_override(self): log_personal_information = False # Act - Pass in properties during QnA invocation that override default properties - # In addition Override with derivation. This presents an interesting question of order of setting properties. + # In addition Override with derivation. This presents an interesting question of order of setting + # properties. # If I want to override "originalQuestion" property: # - Set in "Stock" schema # - Set in derived QnAMaker class @@ -703,8 +702,8 @@ def _get_json_for_file(cls, response_file: str) -> object: curr_dir = path.dirname(path.abspath(__file__)) response_path = path.join(curr_dir, "test_data", response_file) - with open(response_path, "r", encoding="utf-8-sig") as f: - response_str = f.read() + with open(response_path, "r", encoding="utf-8-sig") as file: + response_str = file.read() response_json = json.loads(response_str) return response_json @@ -742,7 +741,7 @@ def __init__( async def on_qna_result( self, query_results: [QueryResult], - context: TurnContext, + turn_context: TurnContext, # pylint: disable=unused-argument telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, ): @@ -782,12 +781,12 @@ def __init__( async def on_qna_result( self, query_results: [QueryResult], - context: TurnContext, + turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, telemetry_metrics: Dict[str, float] = None, ): event_data = await self.fill_qna_event( - query_results, context, telemetry_properties, telemetry_metrics + query_results, turn_context, telemetry_properties, telemetry_metrics ) # Add my property.