File: test_exception_policy_async.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (470 lines) | stat: -rw-r--r-- 21,614 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# coding: utf-8

# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import pytest
from devtools_testutils.aio import recorded_by_proxy_async
from _router_test_case_async import AsyncRouterRecordedTestCase
from _decorators_async import RouterPreparersAsync
from _validators import ExceptionPolicyValidator
from azure.communication.jobrouter._shared.utils import parse_connection_str  # pylint:disable=protected-access
from azure.core.exceptions import ResourceNotFoundError

from azure.communication.jobrouter.aio import JobRouterAdministrationClient
from azure.communication.jobrouter.models import (
    ExceptionPolicy,
    ExceptionRule,
    QueueLengthExceptionTrigger,
    WaitTimeExceptionTrigger,
    ReclassifyExceptionAction,
    ManualReclassifyExceptionAction,
    CancelExceptionAction,
    RoundRobinMode,
    DistributionPolicy,
    RouterQueue,
    ClassificationPolicy,
)

queue_labels = {"key1": "QueueKey", "key2": 10, "key3": True, "key4": False, "key5": 10.1}


exception_triggers = [QueueLengthExceptionTrigger(threshold=1), WaitTimeExceptionTrigger(threshold_seconds=3600)]

exception_actions = [
    # ManualReclassifyExceptionAction() - is to be added to list inside every test
    # since queue will need to be created as a prerequisite
    CancelExceptionAction(),
    # ReclassifyExceptionAction() - is to be added to list inside every test
    # since classification policy will need to be created as a prerequisite
]


# The test class name needs to start with "Test" to get collected by pytest
class TestExceptionPolicyAsync(AsyncRouterRecordedTestCase):
    async def clean_up(self):
        # delete in live mode
        if not self.is_playback():
            router_client: JobRouterAdministrationClient = self.create_admin_client()
            async with router_client:
                if self._testMethodName in self.classification_policy_ids and any(
                    self.classification_policy_ids[self._testMethodName]
                ):
                    for policy_id in set(self.classification_policy_ids[self._testMethodName]):
                        await router_client.delete_classification_policy(policy_id)

                if self._testMethodName in self.queue_ids and any(self.queue_ids[self._testMethodName]):
                    for policy_id in set(self.queue_ids[self._testMethodName]):
                        await router_client.delete_queue(policy_id)

                if self._testMethodName in self.distribution_policy_ids and any(
                    self.distribution_policy_ids[self._testMethodName]
                ):
                    for policy_id in set(self.distribution_policy_ids[self._testMethodName]):
                        await router_client.delete_distribution_policy(policy_id)

                if self._testMethodName in self.exception_policy_ids and any(
                    self.exception_policy_ids[self._testMethodName]
                ):
                    for policy_id in set(self.exception_policy_ids[self._testMethodName]):
                        await router_client.delete_exception_policy(policy_id)

    def get_distribution_policy_id(self):
        return self._testMethodName + "_tst_dp_async"

    async def setup_distribution_policy(self):
        client: JobRouterAdministrationClient = self.create_admin_client()

        async with client:
            distribution_policy_id = self.get_distribution_policy_id()

            policy: DistributionPolicy = DistributionPolicy(
                name=distribution_policy_id,
                offer_expires_after_seconds=10.0,
                mode=RoundRobinMode(min_concurrent_offers=1, max_concurrent_offers=1),
            )

            distribution_policy = await client.upsert_distribution_policy(distribution_policy_id, policy)

        # add for cleanup later
        if self._testMethodName in self.distribution_policy_ids:
            self.distribution_policy_ids[self._testMethodName] = self.distribution_policy_ids[
                self._testMethodName
            ].append(distribution_policy_id)
        else:
            self.distribution_policy_ids[self._testMethodName] = [distribution_policy_id]

    def get_job_queue_id(self):
        return self._testMethodName + "_tst_q_async"

    async def setup_job_queue(self):
        client: JobRouterAdministrationClient = self.create_admin_client()

        async with client:
            job_queue_id = self.get_job_queue_id()

            job_queue: RouterQueue = RouterQueue(
                name=job_queue_id, labels=queue_labels, distribution_policy_id=self.get_distribution_policy_id()
            )

            job_queue = await client.upsert_queue(job_queue_id, job_queue)

        # add for cleanup later
        if self._testMethodName in self.queue_ids:
            self.queue_ids[self._testMethodName] = self.queue_ids[self._testMethodName].append(job_queue_id)
        else:
            self.queue_ids[self._testMethodName] = [job_queue_id]

    def get_classification_policy_id(self):
        return self._testMethodName + "_tst_cp_async"

    async def setup_classification_policy(self):
        client: JobRouterAdministrationClient = self.create_admin_client()

        async with client:
            cp_id = self.get_classification_policy_id()

            classification_policy: ClassificationPolicy = ClassificationPolicy(
                name=cp_id,
                fallback_queue_id=self.get_job_queue_id(),
            )

            classification_policy = await client.upsert_classification_policy(cp_id, classification_policy)

        # add for cleanup later
        if self._testMethodName in self.classification_policy_ids:
            self.classification_policy_ids[self._testMethodName] = self.classification_policy_ids[
                self._testMethodName
            ].append(cp_id)
        else:
            self.classification_policy_ids[self._testMethodName] = [cp_id]

    @RouterPreparersAsync.router_test_decorator_async
    @recorded_by_proxy_async
    @RouterPreparersAsync.before_test_execute_async("setup_distribution_policy")
    @RouterPreparersAsync.before_test_execute_async("setup_job_queue")
    @RouterPreparersAsync.before_test_execute_async("setup_classification_policy")
    @RouterPreparersAsync.after_test_execute_async("clean_up")
    async def test_create_exception_policy(self):
        ep_identifier = "tst_create_ep_async"
        router_client: JobRouterAdministrationClient = self.create_admin_client()

        updated_exception_actions = []
        updated_exception_actions.extend(exception_actions)
        updated_exception_actions.append(
            ManualReclassifyExceptionAction(
                queue_id=self.get_job_queue_id(),
                priority=1,
            )
        )
        updated_exception_actions.append(
            (ReclassifyExceptionAction(classification_policy_id=self.get_classification_policy_id()))
        )

        async with router_client:
            for trigger in exception_triggers:
                for action in updated_exception_actions:

                    exception_rules = [ExceptionRule(id="fakeExceptionRuleId", trigger=trigger, actions=[action])]

                    exception_policy: ExceptionPolicy = ExceptionPolicy(
                        name=ep_identifier, exception_rules=exception_rules
                    )

                    exception_policy = await router_client.upsert_exception_policy(ep_identifier, exception_policy)

                    # add for cleanup
                    self.exception_policy_ids[self._testMethodName] = [ep_identifier]

                    assert exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        exception_policy, identifier=ep_identifier, name=ep_identifier, exception_rules=exception_rules
                    )

    @RouterPreparersAsync.router_test_decorator_async
    @recorded_by_proxy_async
    @RouterPreparersAsync.before_test_execute_async("setup_distribution_policy")
    @RouterPreparersAsync.before_test_execute_async("setup_job_queue")
    @RouterPreparersAsync.before_test_execute_async("setup_classification_policy")
    @RouterPreparersAsync.after_test_execute_async("clean_up")
    async def test_update_exception_policy(self):
        ep_identifier = "tst_update_ep_async"
        router_client: JobRouterAdministrationClient = self.create_admin_client()

        updated_exception_actions = []
        updated_exception_actions.extend(exception_actions)
        updated_exception_actions.append(
            ManualReclassifyExceptionAction(
                queue_id=self.get_job_queue_id(),
                priority=1,
            )
        )
        updated_exception_actions.append(
            (ReclassifyExceptionAction(classification_policy_id=self.get_classification_policy_id()))
        )

        async with router_client:
            for trigger in exception_triggers:
                for action in updated_exception_actions:
                    exception_rules = [ExceptionRule(id="fakeExceptionRuleId", trigger=trigger, actions=[action])]

                    exception_policy: ExceptionPolicy = ExceptionPolicy(
                        name=ep_identifier, exception_rules=exception_rules
                    )

                    exception_policy: ExceptionPolicy = await router_client.upsert_exception_policy(
                        ep_identifier, exception_policy
                    )

                    # add for cleanup
                    self.exception_policy_ids[self._testMethodName] = [ep_identifier]

                    assert exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        exception_policy, identifier=ep_identifier, name=ep_identifier, exception_rules=exception_rules
                    )

                    updated_exception_rules = [
                        ExceptionRule(id="fakeExceptionRuleId2", trigger=trigger, actions=[action]),
                    ]

                    exception_policy.exception_rules = updated_exception_rules

                    exception_policy = await router_client.upsert_exception_policy(ep_identifier, exception_policy)

                    assert exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        exception_policy,
                        identifier=ep_identifier,
                        name=ep_identifier,
                        exception_rules=updated_exception_rules,
                    )

    @RouterPreparersAsync.router_test_decorator_async
    @recorded_by_proxy_async
    @RouterPreparersAsync.before_test_execute_async("setup_distribution_policy")
    @RouterPreparersAsync.before_test_execute_async("setup_job_queue")
    @RouterPreparersAsync.before_test_execute_async("setup_classification_policy")
    @RouterPreparersAsync.after_test_execute_async("clean_up")
    async def test_update_exception_policy_w_kwargs(self):
        ep_identifier = "tst_update_ep_w_kwargs_async"
        router_client: JobRouterAdministrationClient = self.create_admin_client()

        updated_exception_actions = []
        updated_exception_actions.extend(exception_actions)
        updated_exception_actions.append(
            ManualReclassifyExceptionAction(
                queue_id=self.get_job_queue_id(),
                priority=1,
            )
        )
        updated_exception_actions.append(
            (ReclassifyExceptionAction(classification_policy_id=self.get_classification_policy_id()))
        )

        async with router_client:
            for trigger in exception_triggers:
                for action in updated_exception_actions:
                    exception_rules = [ExceptionRule(id="fakeExceptionRuleId", trigger=trigger, actions=[action])]

                    exception_policy: ExceptionPolicy = ExceptionPolicy(
                        name=ep_identifier, exception_rules=exception_rules
                    )

                    exception_policy = await router_client.upsert_exception_policy(ep_identifier, exception_policy)

                    # add for cleanup
                    self.exception_policy_ids[self._testMethodName] = [ep_identifier]

                    assert exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        exception_policy, identifier=ep_identifier, name=ep_identifier, exception_rules=exception_rules
                    )

                    updated_exception_rules = [
                        ExceptionRule(id="fakeExceptionRuleId2", trigger=trigger, actions=[action]),
                    ]

                    exception_policy = await router_client.upsert_exception_policy(
                        ep_identifier, name=ep_identifier, exception_rules=updated_exception_rules
                    )

                    assert exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        exception_policy,
                        identifier=ep_identifier,
                        name=ep_identifier,
                        exception_rules=updated_exception_rules,
                    )

    @RouterPreparersAsync.router_test_decorator_async
    @recorded_by_proxy_async
    @RouterPreparersAsync.before_test_execute_async("setup_distribution_policy")
    @RouterPreparersAsync.before_test_execute_async("setup_job_queue")
    @RouterPreparersAsync.before_test_execute_async("setup_classification_policy")
    @RouterPreparersAsync.after_test_execute_async("clean_up")
    async def test_get_exception_policy(self):
        ep_identifier = "tst_get_ep_async"
        router_client: JobRouterAdministrationClient = self.create_admin_client()

        updated_exception_actions = []
        updated_exception_actions.extend(exception_actions)
        updated_exception_actions.append(
            ManualReclassifyExceptionAction(
                queue_id=self.get_job_queue_id(),
                priority=1,
            )
        )
        updated_exception_actions.append(
            (ReclassifyExceptionAction(classification_policy_id=self.get_classification_policy_id()))
        )

        async with router_client:
            for trigger in exception_triggers:
                for action in updated_exception_actions:
                    exception_rules = [ExceptionRule(id="fakeExceptionRuleId", trigger=trigger, actions=[action])]

                    exception_policy: ExceptionPolicy = ExceptionPolicy(
                        name=ep_identifier, exception_rules=exception_rules
                    )

                    exception_policy = await router_client.upsert_exception_policy(ep_identifier, exception_policy)

                    # add for cleanup
                    self.exception_policy_ids[self._testMethodName] = [ep_identifier]

                    assert exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        exception_policy, identifier=ep_identifier, name=ep_identifier, exception_rules=exception_rules
                    )

                    queried_exception_policy = await router_client.get_exception_policy(ep_identifier)

                    assert queried_exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        queried_exception_policy,
                        identifier=ep_identifier,
                        name=ep_identifier,
                        exception_rules=exception_rules,
                    )

    @RouterPreparersAsync.router_test_decorator_async
    @recorded_by_proxy_async
    @RouterPreparersAsync.before_test_execute_async("setup_distribution_policy")
    @RouterPreparersAsync.before_test_execute_async("setup_job_queue")
    @RouterPreparersAsync.before_test_execute_async("setup_classification_policy")
    @RouterPreparersAsync.after_test_execute_async("clean_up")
    async def test_delete_exception_policy(self):
        ep_identifier = "tst_delete_ep_async"
        router_client: JobRouterAdministrationClient = self.create_admin_client()

        updated_exception_actions = []
        updated_exception_actions.extend(exception_actions)
        updated_exception_actions.append(
            ManualReclassifyExceptionAction(
                queue_id=self.get_job_queue_id(),
                priority=1,
            )
        )
        updated_exception_actions.append(
            (ReclassifyExceptionAction(classification_policy_id=self.get_classification_policy_id()))
        )

        async with router_client:
            for trigger in exception_triggers:
                for action in updated_exception_actions:
                    exception_rules = [ExceptionRule(id="fakeExceptionRuleId", trigger=trigger, actions=[action])]

                    exception_policy: ExceptionPolicy = ExceptionPolicy(
                        name=ep_identifier, exception_rules=exception_rules
                    )

                    exception_policy = await router_client.upsert_exception_policy(ep_identifier, exception_policy)

                    # add for cleanup
                    self.exception_policy_ids[self._testMethodName] = [ep_identifier]

                    assert exception_policy is not None
                    ExceptionPolicyValidator.validate_exception_policy(
                        exception_policy, identifier=ep_identifier, name=ep_identifier, exception_rules=exception_rules
                    )

                    await router_client.delete_exception_policy(ep_identifier)
                    with pytest.raises(ResourceNotFoundError) as nfe:
                        await router_client.get_exception_policy(ep_identifier)
                    assert nfe.value.reason == "Not Found"
                    assert nfe.value.status_code == 404

    @RouterPreparersAsync.router_test_decorator_async
    @recorded_by_proxy_async
    @RouterPreparersAsync.before_test_execute_async("setup_distribution_policy")
    @RouterPreparersAsync.before_test_execute_async("setup_job_queue")
    @RouterPreparersAsync.before_test_execute_async("setup_classification_policy")
    @RouterPreparersAsync.after_test_execute_async("clean_up")
    async def test_list_exception_policies(self):
        ep_identifiers = ["tst_list_ep_1_async", "tst_list_ep_2_async", "tst_list_ep_3_async"]
        created_ep_response = {}
        policy_count = 0
        router_client: JobRouterAdministrationClient = self.create_admin_client()
        self.exception_policy_ids[self._testMethodName] = []

        updated_exception_actions = []
        updated_exception_actions.extend(exception_actions)
        updated_exception_actions.append(
            ManualReclassifyExceptionAction(
                queue_id=self.get_job_queue_id(),
                priority=1,
            )
        )
        updated_exception_actions.append(
            (ReclassifyExceptionAction(classification_policy_id=self.get_classification_policy_id()))
        )

        async with router_client:
            for trigger in exception_triggers:
                for action in updated_exception_actions:
                    for identifier in ep_identifiers:
                        exception_rules = [ExceptionRule(id="fakeExceptionRuleId", trigger=trigger, actions=[action])]

                        exception_policy: ExceptionPolicy = ExceptionPolicy(
                            name=identifier, exception_rules=exception_rules
                        )

                        exception_policy = await router_client.upsert_exception_policy(identifier, exception_policy)

                        policy_count += 1

                        # add for cleanup
                        self.exception_policy_ids[self._testMethodName].append(identifier)

                        assert exception_policy is not None
                        ExceptionPolicyValidator.validate_exception_policy(
                            exception_policy, identifier=identifier, name=identifier, exception_rules=exception_rules
                        )

                        created_ep_response[exception_policy.id] = exception_policy

                    policies = router_client.list_exception_policies(results_per_page=2)
                    async for policy_page in policies.by_page():
                        list_of_policies = [i async for i in policy_page]
                        assert len(list_of_policies) <= 2

                        for policy_item in list_of_policies:
                            response_at_creation = created_ep_response.get(policy_item.id, None)

                            if not response_at_creation:
                                continue

                            ExceptionPolicyValidator.validate_exception_policy(
                                policy_item,
                                identifier=response_at_creation.id,
                                name=response_at_creation.name,
                                exception_rules=response_at_creation.exception_rules,
                            )
                            policy_count -= 1

                    # all policies created were listed
                    assert policy_count == 0