def test_context_local_context(self, err_mock): self.assertIsNone(request.context) err_mock.assert_called_with( "Accessing request local object outside of the request-response cycle." ) req = create_request("TELEKOM_Demo_Intent", session={ "key-1": "value-1", "key-2": "value-2" }) with RequestContextVar(request=req): self.assertEqual(request.context.intent, "TELEKOM_Demo_Intent") self.assertEqual( { "id": "123", "attributes": { "key-1": "value-1", "key-2": "value-2" }, "new": True, }, request.session.dict(), ) with RequestContextVar(request=req.with_translation(Translations())): self.assertEqual("HELLO", request.context._("HELLO")) self.assertEqual("HELLO", request.context._n("HELLO", "HOLA", 1)) self.assertEqual(["HELLO"], request.context._a("HELLO"))
class TestAttributesV2(unittest.TestCase): attr_v2 = {"id": 1, "value": "value", "nestedIn": [], "overlapsWith": []} request = create_request("TEST_CONTEXT", attr=attr_v2) def test_attributesV2(self): """Test conversions to AttributesV2""" @intent_handler def attr_v2_test(attr: AttributeV2): return attr self.assertEqual(attr_v2_test(self.request), AttributeV2(self.attr_v2)) def test_attributesV2_list(self): """Test conversions to List of AttributesV2""" @intent_handler def attr_v2_test(attr: [AttributeV2]): return attr[0] self.assertEqual(attr_v2_test(self.request), AttributeV2(self.attr_v2)) @intent_handler def attr_v2_test(attr: List[AttributeV2]): return attr[0] self.assertEqual(attr_v2_test(self.request), AttributeV2(self.attr_v2)) def test_attributesV2_subtypes(self): # Test conversions of AttributesV2 with subtypes attr_v2 = { "id": 1, "value": "123456", "nestedIn": [], "overlapsWith": [] } context = create_request("TEST_CONTEXT", attr=attr_v2) @intent_handler def attr_v2_test(attr: AttributeV2[int]): return attr self.assertEqual(attr_v2_test(context), AttributeV2(attr_v2, int)) def test_attributesV2_list_subtypes(self): # Test conversion of List of AttributesV2 with subtypes attr_v2 = { "id": 1, "value": "123456", "nestedIn": [], "overlapsWith": [] } context = create_request("TEST_CONTEXT", attr=attr_v2) @intent_handler def attr_v2_test(attr: List[AttributeV2[int]]): return attr result = attr_v2_test(context) self.assertEqual(result, [AttributeV2(attr_v2, int)])
def test_invoke_intent_not_found(self): response = self.client.post( ENDPOINT, data=create_request("Test_Intent").json(), headers=self.auth, ) assert response.status_code == 404 assert response.json() == {"code": 1, "text": "Intent not found!"}
def test_stacked_decorators(self): import functools m = unittest.mock.MagicMock() @intent_handler @functools.lru_cache(2) def test(date: datetime.date): m(date) r = create_request("TEST_CONTEXT", date=["2012-12-12"]) test(r) test(r) r = create_request("TEST_CONTEXT", date=["2012-12-14"]) test(r) test(r) self.assertEqual(m.call_count, 2)
def test_handler_fail_silent(self): """ Test date conversion of invalid date in "silent" mode """ @intent_handler def date_test(date: datetime.date): return date r = create_request("TEST_CONTEXT", date=["not a date"]) result = date_test(r) self.assertIsInstance(result, EntityValueException) @intent_handler def int_test(integer: int): return integer r = create_request("TEST_CONTEXT", integer=["not a number"]) result = int_test(r) self.assertIsInstance(result, EntityValueException)
def test_handler_context(self): @intent_handler def decorated_test(context: Context, timezone: str): return context, timezone r = create_request("TEST_CONTEXT") result = decorated_test(r) self.assertEqual(result, (r.context, "Europe/Berlin"))
def test_handler_date_fail(self): """ Test date conversion of invalid date """ @intent_handler(False) def decorated_test(date: datetime.date): return date r = create_request("TEST_CONTEXT", date=["not a date"]) with self.assertRaises(EntityValueException): result = decorated_test(r)
def test_invoke_response(self): self.app.include("Test_Intent", handler=lambda: "Hola") response = self.client.post( ENDPOINT, data=create_request("Test_Intent").json(), headers=self.auth, ) assert response.status_code == 200 assert response.json() == {"text": "Hola", "type": "TELL"}
def test_with_error_handler(self): """ Test conversion failure if error_handler supplied """ def error_handler(name, exception): return name, exception.value, str(exception.__cause__) @intent_handler(error_handler=error_handler) def date_test(date: datetime.date): return None result = date_test(create_request("TEST_CONTEXT", date=["not a date"])) self.assertEqual( result, ( "date", "not a date", str(ValueError("Unknown string format: not a date")), ), ) self.assertIsNone(date_test(create_request("TEST_CONTEXT", date=[])))
def test_context_local_now(self): req = create_request("TELEKOM_Demo_Intent", timezone=["Europe/Athens"]) next_day = datetime.datetime(year=2100, month=12, day=20, hour=0, minute=0) with RequestContextVar(request=req): self.assertEqual(request.context.today().timestamp(), next_day.timestamp()) self.assertEqual(request.context.now().timestamp(), self.now.timestamp())
async def test_context_local_session(): from skill_sdk.intents.handlers import ContextVarExecutor def one(_): with RequestContextVar(request=_): del request.session["key-1"] del request.session["key-2"] assert request.session.dict() == { "id": "123", "attributes": {}, "new": True, } def init(_): with RequestContextVar(request=_): with pytest.raises(TypeError): request.context.locale = "de" # noqa: attempt to modify "read-only" context (to raise TypeError) assert request.session.dict() == { "id": "123", "attributes": { "key-1": "value-1", "key-2": "value-2" }, "new": True, } def two(_): with RequestContextVar(request=_): request.session["key-1"] = "value-12" request.session["key-2"] = "value-22" assert request.session.dict() == { "id": "123", "attributes": { "key-1": "value-12", "key-2": "value-22" }, "new": True, } req = create_request("TELEKOM_Demo_Intent", session={ "key-1": "value-1", "key-2": "value-2" }) loop = asyncio.get_running_loop() await loop.run_in_executor(ContextVarExecutor(), init, req) await loop.run_in_executor(ContextVarExecutor(), one, req) await loop.run_in_executor(ContextVarExecutor(), init, req) await loop.run_in_executor(ContextVarExecutor(), two, req)
def test_attributesV2_subtypes(self): # Test conversions of AttributesV2 with subtypes attr_v2 = { "id": 1, "value": "123456", "nestedIn": [], "overlapsWith": [] } context = create_request("TEST_CONTEXT", attr=attr_v2) @intent_handler def attr_v2_test(attr: AttributeV2[int]): return attr self.assertEqual(attr_v2_test(context), AttributeV2(attr_v2, int))
def test_make_lazy_translation(self): from skill_sdk.intents import RequestContextVar tr = Translations("de.mo") request = util.create_request("Test__Intent") tr._catalog["KEY"] = "VALUE" tr._catalog[("KEY", 1)] = "VALUES" tr._catalog["KEY_PLURAL"] = "VALUES" self.assertEqual(_("KEY"), "KEY") self.assertEqual(_n("KEY", "KEY_PLURAL", 1), "KEY") self.assertEqual(_n("KEY", "KEY_PLURAL", 2), "KEY_PLURAL") self.assertEqual(_a("KEY"), ["KEY"]) with RequestContextVar(request=request.with_translation(tr)): self.assertEqual(_("KEY"), "VALUE") self.assertEqual(_n("KEY", "KEY_PLURAL", 2), "VALUES") self.assertEqual(_a("KEY"), ["KEY"])
def setUp(self): req = create_request("TELEKOM_Demo_Intent", timezone=["Europe/Berlin"]) @mock_datetime_now(self.now, datetime) def run(): now = self.now.astimezone( datetime.timezone(datetime.timedelta(hours=1))) with RequestContextVar(request=req): self.assertEqual( request.context.today().timestamp(), now.replace(hour=0, minute=0, tzinfo=None).timestamp(), ) self.assertEqual(request.context.now().timestamp(), self.now.timestamp()) run_thread(run)
def test_multiple_date_values(self): """ Improve LUIS weekday parsing """ from dateutil.tz import tzutc @intent_handler def date_test(date: [datetime.datetime]): return tuple(date) r = create_request("TEST_CONTEXT", date=["2100-12-31", "T13:00:00Z"]) self.assertEqual( ( datetime.datetime(2100, 12, 31, 0, 0), datetime.datetime(2100, 12, 31, 13, 0, tzinfo=tzutc()), ), date_test(r), )
async def test_handler_array_async(): @intent_handler def decorated_test(arr: List[str]): return arr r = create_request( "TEST_CONTEXT", arr=[ "31-12-2001", "31-12-1001", ], ) result = decorated_test(r) assert result == [ "31-12-2001", "31-12-1001", ]
def test_handler_date_array(self): """ Check usage with date array """ @intent_handler def decorated_test(date_arr: [datetime.date]): return date_arr r = create_request( "TEST_CONTEXT", date_arr=[ "2001-12-31", "1001-12-31", ], ) result = decorated_test(r) self.assertEqual( result, [datetime.date(2001, 12, 31), datetime.date(1001, 12, 31)])
def test_handler_dates(self): """ Check handler usage with date conversion """ @intent_handler def decorated_test(date_str: str = None, date_date: datetime.date = None): return date_str, date_date r = create_request( "TEST_CONTEXT", date_str=[ "2001-12-31", "2001-12-31", ], date_date=[ "2001-12-31", "1001-12-31", ], ) result = decorated_test(r) self.assertEqual(result, ("2001-12-31", datetime.date(2001, 12, 31)))
def test_handler_array(self): """ Check simple usage with no conversion """ @intent_handler def decorated_test(arr: List[str]): return arr r = create_request( "TEST_CONTEXT", arr=[ "31-12-2001", "31-12-1001", ], ) result = decorated_test(r) self.assertEqual( result, [ "31-12-2001", "31-12-1001", ], )