File size: 32,032 Bytes
7931de6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import gc
import logging
import threading
import unittest
from unittest.mock import ANY

import numpy as np
import pytest
from tritonclient.grpc.aio import InferenceServerClient as AsyncioGrpcInferenceServerClient
from tritonclient.http.aio import InferenceServerClient as AsyncioHttpInferenceServerClient

from pytriton.client import AsyncioModelClient
from pytriton.client.asyncio_utils import asyncio_wait_for_model_ready
from pytriton.client.exceptions import (
    PyTritonClientInvalidUrlError,
    PyTritonClientModelDoesntSupportBatchingError,
    PyTritonClientTimeoutError,
    PyTritonClientValueError,
)

from .client_common import (
    ADD_SUB_WITH_BATCHING_MODEL_CONFIG,
    ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG,
    EXPECTED_KWARGS_DEFAULT,
    GRPC_LOCALHOST_URL,
    HTTP_LOCALHOST_URL,
    HTTP_LOCALHOST_URL_NO_SCHEME,
    patch_client__server_up_and_ready,
    patch_grpc_client__model_up_and_ready,
    patch_http_client__model_up_and_ready,
)
from .utils import (
    extract_array_from_http_infer_input,
    verify_equalness_of_dicts_with_ndarray,
    wrap_to_http_infer_result,
)

_LOGGER = logging.getLogger(__name__)

_MAX_TEST_TIME = 10.0


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_utils_asyncio_wait_for_model_ready_http_client_not_ready_server(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient, ready_server=False)

    triton_client = AsyncioHttpInferenceServerClient(url=HTTP_LOCALHOST_URL_NO_SCHEME, verbose=False)
    try:
        with pytest.raises(PyTritonClientTimeoutError):
            await asyncio_wait_for_model_ready(
                asyncio_client=triton_client,
                model_name=ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name,
                model_version=str(ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_version),
                timeout_s=1,
            )
    finally:
        await triton_client.close()


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_utils_asyncio_wait_for_model_ready_http_client_not_live_server(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient, live_server=False)

    triton_client = AsyncioHttpInferenceServerClient(url=HTTP_LOCALHOST_URL_NO_SCHEME, verbose=False)
    try:
        with pytest.raises(PyTritonClientTimeoutError):
            await asyncio_wait_for_model_ready(
                asyncio_client=triton_client,
                model_name=ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name,
                model_version=str(ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_version),
                timeout_s=1,
            )
    finally:
        await triton_client.close()


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_utils_asyncio_wait_for_model_ready_http_client_model_not_ready(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient, ready=False
    )

    triton_client = AsyncioHttpInferenceServerClient(url=HTTP_LOCALHOST_URL_NO_SCHEME, verbose=False)
    try:
        with pytest.raises(PyTritonClientTimeoutError):
            await asyncio_wait_for_model_ready(
                asyncio_client=triton_client,
                model_name=ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name,
                model_version=str(ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_version),
                timeout_s=1,
            )
    finally:
        await triton_client.close()


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_utils_asyncio_wait_for_model_ready_http_client_success(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient
    )

    triton_client = AsyncioHttpInferenceServerClient(url=HTTP_LOCALHOST_URL_NO_SCHEME, verbose=False)
    await asyncio_wait_for_model_ready(
        asyncio_client=triton_client,
        model_name=ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name,
        model_version=str(ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_version),
        timeout_s=1,
    )
    await triton_client.close()


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_client_init_raises_error_when_invalid_url_provided(mocker):
    with pytest.raises(PyTritonClientInvalidUrlError):
        async with AsyncioModelClient(["localhost:8001"], "dummy") as _:  # pytype: disable=wrong-arg-types
            pass


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_init_raises_error_when_use_non_lazy_init_on_non_responding_server():
    with pytest.raises(PyTritonClientTimeoutError):
        async with AsyncioModelClient("dummy:43299", "dummy", lazy_init=False, init_timeout_s=1) as _:
            pass


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_init_obtain_expected_model_config_when_lazy_init_is_disabled(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(mocker, ADD_SUB_WITH_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient)

    spy_client_init = mocker.spy(AsyncioHttpInferenceServerClient, AsyncioHttpInferenceServerClient.__init__.__name__)
    client = AsyncioModelClient("http://localhost:8000", ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name, lazy_init=False)
    await client.__aenter__()
    # Exit sets some clients to none
    general_client = client._general_client
    infer_client = client._infer_client
    await client.__aexit__(None, None, None)
    assert spy_client_init.mock_calls == [
        unittest.mock.call(general_client, "localhost:8000", conn_timeout=60.0),
        unittest.mock.call(infer_client, "localhost:8000", conn_timeout=60.0),
    ]
    assert await client.model_config == ADD_SUB_WITH_BATCHING_MODEL_CONFIG


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_model_config_raises_error_when_requested_unavailable_model(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)

    mocker.patch.object(
        AsyncioHttpInferenceServerClient, AsyncioHttpInferenceServerClient.is_model_ready.__name__
    ).return_value = False

    with pytest.raises(PyTritonClientTimeoutError, match="Timeout while waiting for model"):
        async with AsyncioModelClient(HTTP_LOCALHOST_URL, "NonExistentModel", init_timeout_s=1) as client:
            _ = await client.model_config

    with pytest.raises(PyTritonClientTimeoutError, match="Timeout while waiting for model"):
        async with AsyncioModelClient(HTTP_LOCALHOST_URL, "OtherName", "2", init_timeout_s=1) as client:
            _ = await client.model_config


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_raises_error_when_requested_unavailable_model(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    mocker.patch.object(
        AsyncioHttpInferenceServerClient, AsyncioHttpInferenceServerClient.is_model_ready.__name__
    ).return_value = False
    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)

    with pytest.raises(PyTritonClientTimeoutError, match="Timeout while waiting for model"):
        async with AsyncioModelClient(HTTP_LOCALHOST_URL, "NonExistentModel", init_timeout_s=1) as client:
            _ = await client.infer_sample(a, b)

    with pytest.raises(PyTritonClientTimeoutError, match="Timeout while waiting for model"):
        async with AsyncioModelClient(HTTP_LOCALHOST_URL, "NonExistentModel", init_timeout_s=1) as client:
            _ = await client.infer_batch(a, b)

    with pytest.raises(PyTritonClientTimeoutError, match="Timeout while waiting for model"):
        async with AsyncioModelClient(HTTP_LOCALHOST_URL, "OtherName", "2", init_timeout_s=1) as client:
            _ = await client.infer_sample(a, b)

    with pytest.raises(PyTritonClientTimeoutError, match="Timeout while waiting for model"):
        async with AsyncioModelClient(HTTP_LOCALHOST_URL, "OtherName", "2", init_timeout_s=1) as client:
            _ = await client.infer_batch(a, b)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_sample_returns_expected_result_when_infer_on_model_with_batching(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(mocker, ADD_SUB_WITH_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient)

    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)
    expected_result = {"add": a + b, "sub": a - b}
    # server will return data with additional axis
    server_result = {name: data[np.newaxis, ...] for name, data in expected_result.items()}

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        mock_infer = mocker.patch.object(client._infer_client, "infer")
        mock_infer.return_value = wrap_to_http_infer_result(ADD_SUB_WITH_BATCHING_MODEL_CONFIG, "0", server_result)
        result = await client.infer_sample(a, b)

        called_kwargs = mock_infer.call_args.kwargs
        expected_kwargs = dict(EXPECTED_KWARGS_DEFAULT)
        expected_kwargs.update(
            {
                # expect to send data with additional batch axis
                "inputs": {"a": a[np.newaxis, ...], "b": b[np.newaxis, ...]},
                "outputs": list(expected_result),
            }
        )
        assert all(
            called_kwargs.get(arg_name) == arg_value
            for arg_name, arg_value in expected_kwargs.items()
            if arg_name not in ["inputs", "outputs"]  # inputs and outputs requires manual verification
        )
        assert not [key for key in called_kwargs if key not in list(expected_kwargs)]
        assert [output.name() for output in called_kwargs.get("outputs")] == list(expected_kwargs["outputs"])
        inputs_called_arg = {i.name(): extract_array_from_http_infer_input(i) for i in called_kwargs.get("inputs")}
        verify_equalness_of_dicts_with_ndarray(inputs_called_arg, expected_kwargs["inputs"])

        verify_equalness_of_dicts_with_ndarray(expected_result, result)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_sample_returns_expected_result_when_infer_on_model_with_batching_created_from_existing(
    mocker,
):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(mocker, ADD_SUB_WITH_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient)

    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)
    expected_result = {"add": a + b, "sub": a - b}
    # server will return data with additional axis
    server_result = {name: data[np.newaxis, ...] for name, data in expected_result.items()}

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        mock_infer = mocker.patch.object(client._infer_client, "infer")
        mock_infer.return_value = wrap_to_http_infer_result(ADD_SUB_WITH_BATCHING_MODEL_CONFIG, "0", server_result)
        await client.infer_sample(a, b)

        async with AsyncioModelClient.from_existing_client(client) as client_from_existing:
            mock_infer_from_existing = mocker.patch.object(client_from_existing._infer_client, "infer")
            mock_infer_from_existing.return_value = wrap_to_http_infer_result(
                ADD_SUB_WITH_BATCHING_MODEL_CONFIG, "0", server_result
            )
            result = await client.infer_sample(a, b)
            verify_equalness_of_dicts_with_ndarray(expected_result, result)
        async with AsyncioModelClient(
            HTTP_LOCALHOST_URL,
            ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name,
            model_config=await client.model_config,
            ensure_model_is_ready=False,
        ) as client_from_existing:
            mock_infer_from_existing = mocker.patch.object(client_from_existing._infer_client, "infer")
            mock_infer_from_existing.return_value = wrap_to_http_infer_result(
                ADD_SUB_WITH_BATCHING_MODEL_CONFIG, "0", server_result
            )
            result = await client.infer_sample(a, b)
            verify_equalness_of_dicts_with_ndarray(expected_result, result)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_sample_returns_expected_result_when_positional_args_are_used(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient
    )

    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)
    expected_result = {"add": a + b, "sub": a - b}
    server_result = expected_result

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name) as client:
        mock_infer = mocker.patch.object(client._infer_client, "infer")
        mock_infer.return_value = wrap_to_http_infer_result(ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, "0", server_result)
        result = await client.infer_sample(a, b)

        called_kwargs = mock_infer.call_args.kwargs
        expected_kwargs = dict(EXPECTED_KWARGS_DEFAULT)
        expected_kwargs.update(
            {
                "model_name": ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name,
                "inputs": {"a": a, "b": b},
                "outputs": list(expected_result),
            }
        )
        assert all(
            called_kwargs.get(arg_name) == arg_value
            for arg_name, arg_value in expected_kwargs.items()
            if arg_name not in ["inputs", "outputs"]  # inputs and outputs requires manual verification
        )
        assert not [key for key in called_kwargs if key not in list(expected_kwargs)]
        assert [output.name() for output in called_kwargs.get("outputs")] == list(expected_kwargs["outputs"])
        inputs_called_arg = {i.name(): extract_array_from_http_infer_input(i) for i in called_kwargs.get("inputs")}
        verify_equalness_of_dicts_with_ndarray(inputs_called_arg, expected_kwargs["inputs"])

        verify_equalness_of_dicts_with_ndarray(expected_result, result)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_batch_returns_expected_result_when_positional_args_are_used(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(mocker, ADD_SUB_WITH_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient)

    a = np.array([[1], [1]], dtype=np.float32)
    b = np.array([[1], [1]], dtype=np.float32)
    expected_result = {"add": a + b, "sub": a - b}
    server_result = expected_result

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        mock_infer = mocker.patch.object(client._infer_client, "infer")
        mock_infer.return_value = wrap_to_http_infer_result(ADD_SUB_WITH_BATCHING_MODEL_CONFIG, "0", server_result)
        result = await client.infer_batch(a, b)

        called_kwargs = mock_infer.call_args.kwargs
        expected_kwargs = dict(EXPECTED_KWARGS_DEFAULT)
        expected_kwargs.update(
            {
                "inputs": {"a": a, "b": b},
                "outputs": list(expected_result),
            }
        )
        assert all(
            called_kwargs.get(arg_name) == arg_value
            for arg_name, arg_value in expected_kwargs.items()
            if arg_name not in ["inputs", "outputs"]  # inputs and outputs requires manual verification
        )
        assert not [key for key in called_kwargs if key not in list(expected_kwargs)]
        assert [output.name() for output in called_kwargs.get("outputs")] == list(expected_kwargs["outputs"])
        inputs_called_arg = {i.name(): extract_array_from_http_infer_input(i) for i in called_kwargs.get("inputs")}
        verify_equalness_of_dicts_with_ndarray(inputs_called_arg, expected_kwargs["inputs"])

        verify_equalness_of_dicts_with_ndarray(expected_result, result)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_sample_returns_expected_result_when_named_args_are_used(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient
    )

    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)
    expected_result = {"add": a + b, "sub": a - b}
    server_result = {"add": a + b, "sub": a - b}

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name) as client:
        mock_infer = mocker.patch.object(client._infer_client, "infer")
        mock_infer.return_value = wrap_to_http_infer_result(ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, "0", server_result)

        inputs_dict = {"a": a, "b": b}
        result = await client.infer_sample(**inputs_dict)

        called_kwargs = mock_infer.call_args.kwargs
        expected_kwargs = dict(EXPECTED_KWARGS_DEFAULT)
        expected_kwargs.update(
            {
                "model_name": ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name,
                "inputs": inputs_dict,
                "outputs": list(expected_result),
            }
        )
        assert all(
            called_kwargs.get(arg_name) == arg_value
            for arg_name, arg_value in expected_kwargs.items()
            if arg_name not in ["inputs", "outputs"]  # inputs and outputs requires manual verification
        )
        assert not [key for key in called_kwargs if key not in list(expected_kwargs)]
        assert [output.name() for output in called_kwargs.get("outputs")] == list(expected_kwargs["outputs"])
        inputs_called_arg = {i.name(): extract_array_from_http_infer_input(i) for i in called_kwargs.get("inputs")}
        verify_equalness_of_dicts_with_ndarray(inputs_called_arg, expected_kwargs["inputs"])

        verify_equalness_of_dicts_with_ndarray(expected_result, result)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_batch_returns_expected_result_when_named_args_are_used(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(mocker, ADD_SUB_WITH_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient)

    a = np.array([[1], [1]], dtype=np.float32)
    b = np.array([[1], [1]], dtype=np.float32)
    expected_result = {"add": a + b, "sub": a - b}
    server_result = expected_result

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        mock_infer = mocker.patch.object(client._infer_client, "infer")
        mock_infer.return_value = wrap_to_http_infer_result(ADD_SUB_WITH_BATCHING_MODEL_CONFIG, "0", server_result)

        inputs_dict = {"a": a, "b": b}
        result = await client.infer_batch(**inputs_dict)

        called_kwargs = mock_infer.call_args.kwargs
        expected_kwargs = dict(EXPECTED_KWARGS_DEFAULT)
        expected_kwargs.update(
            {
                "inputs": inputs_dict,
                "outputs": list(expected_result),
            }
        )
        assert all(
            called_kwargs.get(arg_name) == arg_value
            for arg_name, arg_value in expected_kwargs.items()
            if arg_name not in ["inputs", "outputs"]  # inputs and outputs requires manual verification
        )
        assert not [key for key in called_kwargs if key not in list(expected_kwargs)]
        assert [output.name() for output in called_kwargs.get("outputs")] == list(expected_kwargs["outputs"])
        inputs_called_arg = {i.name(): extract_array_from_http_infer_input(i) for i in called_kwargs.get("inputs")}
        verify_equalness_of_dicts_with_ndarray(inputs_called_arg, expected_kwargs["inputs"])

        verify_equalness_of_dicts_with_ndarray(expected_result, result)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_batch_raises_error_when_model_doesnt_support_batching(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient
    )

    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG.model_name) as client:
        with pytest.raises(PyTritonClientModelDoesntSupportBatchingError):
            await client.infer_batch(a, b)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_raises_error_when_mixed_args_convention_used(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient
    )

    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        with pytest.raises(
            PyTritonClientValueError,
            match="Use either positional either keyword method arguments convention",
        ):
            await client.infer_sample(a, b=b)

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        with pytest.raises(
            PyTritonClientValueError,
            match="Use either positional either keyword method arguments convention",
        ):
            await client.infer_batch(a, b=b)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_client_infer_raises_error_when_no_args_provided(mocker):
    patch_client__server_up_and_ready(mocker, AsyncioHttpInferenceServerClient)
    patch_http_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioHttpInferenceServerClient
    )

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        with pytest.raises(PyTritonClientValueError, match="Provide input data"):
            await client.infer_sample()

    async with AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name) as client:
        with pytest.raises(PyTritonClientValueError, match="Provide input data"):
            await client.infer_batch()


@pytest.mark.async_timeout(_MAX_TEST_TIME)
@pytest.mark.filterwarnings("error::pytest.PytestUnraisableExceptionWarning")
async def test_asynciodel_of_inference_client_does_not_raise_error():
    def _del(client):
        del client._general_client
        del client._infer_client

    async def _create_client_and_delete():
        client = AsyncioModelClient(HTTP_LOCALHOST_URL, ADD_SUB_WITH_BATCHING_MODEL_CONFIG.model_name)
        await client.close()
        threading.Thread(target=_del, args=(client,)).start()

    await _create_client_and_delete()
    gc.collect()


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_infer_sample_returns_expected_result_when_infer_on_model_with_batching(mocker):
    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)
    expected_result = {"add": a + b, "sub": a - b}

    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(GRPC_LOCALHOST_URL, model_config.model_name)
    _LOGGER.debug("Creating client")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient)
    patch_grpc_client__model_up_and_ready(
        mocker, ADD_SUB_WITHOUT_BATCHING_MODEL_CONFIG, AsyncioGrpcInferenceServerClient
    )
    mock_infer = mocker.patch.object(client._infer_client, "infer")
    mock_infer.return_value = wrap_to_http_infer_result(ADD_SUB_WITH_BATCHING_MODEL_CONFIG, "0", expected_result)
    _LOGGER.debug("Entering client")
    await client.__aenter__()
    _LOGGER.debug("Entered client")
    result = await client.infer_sample(a, b)
    mock_infer.assert_called_with(
        model_name=model_config.model_name,
        model_version="",
        inputs=ANY,
        request_id=ANY,
        headers=None,
        parameters=None,
        outputs=ANY,
        client_timeout=60.0,
    )
    _LOGGER.debug("Exiting client")
    await client.__aexit__(None, None, None)
    _LOGGER.debug("Exited client")

    assert result == expected_result


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_non_lazy_aenter_failure_triton_non_ready(mocker):
    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(GRPC_LOCALHOST_URL, model_config.model_name, init_timeout_s=0.1, lazy_init=False)
    _LOGGER.debug("Before patching")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient, ready_server=False)
    _LOGGER.debug("Entering client")
    with pytest.raises(PyTritonClientTimeoutError):
        await asyncio.wait_for(client.__aenter__(), 0.2)
        _LOGGER.debug("Exiting client without error")
    _LOGGER.debug("Exited client with error")


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_non_lazy_aenter_failure_triton_non_live(mocker):
    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(GRPC_LOCALHOST_URL, model_config.model_name, init_timeout_s=0.1, lazy_init=False)
    _LOGGER.debug("Before patching")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient, live_server=False)
    _LOGGER.debug("Entering client")
    with pytest.raises(PyTritonClientTimeoutError):
        await asyncio.wait_for(client.__aenter__(), 0.2)
        _LOGGER.debug("Exiting client without error")
    _LOGGER.debug("Exited client with error")


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_non_lazy_aenter_failure_model_non_ready(mocker):
    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(GRPC_LOCALHOST_URL, model_config.model_name, init_timeout_s=0.1, lazy_init=False)
    _LOGGER.debug("Before patching")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient)
    patch_grpc_client__model_up_and_ready(mocker, model_config, AsyncioGrpcInferenceServerClient, ready=False)
    _LOGGER.debug("Entering client")
    with pytest.raises(PyTritonClientTimeoutError):
        await asyncio.wait_for(client.__aenter__(), 0.2)
        _LOGGER.debug("Exiting client without error")
    _LOGGER.debug("Exited client with error")


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_non_lazy_aenter_failure_model_state_unavailable(mocker):
    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(GRPC_LOCALHOST_URL, model_config.model_name, init_timeout_s=1, lazy_init=False)
    _LOGGER.debug("Before patching")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient)
    patch_grpc_client__model_up_and_ready(mocker, model_config, AsyncioGrpcInferenceServerClient, ready=False)
    _LOGGER.debug("Entering client")
    with pytest.raises(PyTritonClientTimeoutError):
        await asyncio.wait_for(client.__aenter__(), 2)
        _LOGGER.debug("Exiting client without error")
    _LOGGER.debug("Exited client with error")


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_non_lazy_aenter_failure_model_incorrect_name(mocker):
    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(GRPC_LOCALHOST_URL, "DUMMY", init_timeout_s=1, lazy_init=False)
    _LOGGER.debug("Before patching")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient)
    patch_grpc_client__model_up_and_ready(mocker, model_config, AsyncioGrpcInferenceServerClient)
    _LOGGER.debug("Entering client")
    with pytest.raises(PyTritonClientTimeoutError):
        await asyncio.wait_for(client.__aenter__(), 2)
        _LOGGER.debug("Exiting client without error")
    _LOGGER.debug("Exited client with error")


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_non_lazy_aenter_failure_model_incorrect_version(mocker):
    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(
        GRPC_LOCALHOST_URL, model_config.model_name, model_version="2", init_timeout_s=1, lazy_init=False
    )
    _LOGGER.debug("Before patching")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient)
    patch_grpc_client__model_up_and_ready(mocker, model_config, AsyncioGrpcInferenceServerClient)
    _LOGGER.debug("Entering client")
    with pytest.raises(PyTritonClientTimeoutError):
        await asyncio.wait_for(client.__aenter__(), 2)
        _LOGGER.debug("Exiting client without error")
    _LOGGER.debug("Exited client with error")


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_client_infer_sample_fails_on_model_with_batching(mocker):
    a = np.array([1], dtype=np.float32)
    b = np.array([1], dtype=np.float32)

    model_config = ADD_SUB_WITH_BATCHING_MODEL_CONFIG

    _LOGGER.debug("Creating client")
    client = AsyncioModelClient(GRPC_LOCALHOST_URL, model_config.model_name)
    _LOGGER.debug("Creating client")
    patch_client__server_up_and_ready(mocker, AsyncioGrpcInferenceServerClient)
    patch_grpc_client__model_up_and_ready(mocker, model_config, AsyncioGrpcInferenceServerClient)
    mock_infer = mocker.patch.object(client._infer_client, "infer")

    def _model_infer_mock(*args, **kwargs):
        raise PyTritonClientValueError("Dummy exception")

    mock_infer.side_effect = _model_infer_mock

    _LOGGER.debug("Entering client")
    await client.__aenter__()
    _LOGGER.debug("Entered client")

    with pytest.raises(PyTritonClientValueError):
        await client.infer_sample(a, b)

    _LOGGER.debug("Exiting client")
    await client.__aexit__(None, None, None)
    _LOGGER.debug("Exited client")


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_http_init_passes_timeout(mocker):
    async with AsyncioModelClient(
        "http://localhost:6669", "dummy", init_timeout_s=0.2, inference_timeout_s=0.1
    ) as client:
        with pytest.raises(PyTritonClientTimeoutError):
            await client.wait_for_model(timeout_s=0.2)


@pytest.mark.async_timeout(_MAX_TEST_TIME)
async def test_async_grpc_init_passes_timeout(mocker):
    async with AsyncioModelClient(
        "grpc://localhost:6669", "dummy", init_timeout_s=0.2, inference_timeout_s=0.1
    ) as client:
        with pytest.raises(PyTritonClientTimeoutError):
            await client.wait_for_model(timeout_s=0.2)