-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtest_async_vws.py
More file actions
731 lines (655 loc) · 22.5 KB
/
Copy pathtest_async_vws.py
File metadata and controls
731 lines (655 loc) · 22.5 KB
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
"""Tests for async helper functions for managing a Vuforia database."""
import base64
import calendar
import datetime # noqa: TC003
import io # noqa: TC003
import time
import uuid
from http import HTTPStatus
from typing import BinaryIO
import pytest
from mock_vws import MockVWS
from mock_vws.database import CloudDatabase
from vws import AsyncCloudRecoService, AsyncVuMarkService, AsyncVWS
from vws.exceptions.custom_exceptions import (
DatabaseIdNotSetError,
RecoCountsReportDownloadError,
RecoCountsReportNotReadyError,
RecoCountsReportTimeoutError,
TargetProcessingTimeoutError,
)
from vws.exceptions.vws_exceptions import (
AuthenticationFailureError,
FailError,
)
from vws.reports import (
DatabaseSummaryReport,
TargetRecord,
TargetStatuses,
)
from vws.response import Response
from vws.vumark_accept import VuMarkAccept
class TestAddTarget:
"""Tests for adding a target."""
@staticmethod
@pytest.mark.asyncio
@pytest.mark.parametrize(
argnames="application_metadata",
argvalues=[None, b"a"],
)
@pytest.mark.parametrize(
argnames="active_flag",
argvalues=[True, False],
)
async def test_add_target(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
application_metadata: bytes | None,
async_cloud_reco_client: AsyncCloudRecoService,
active_flag: bool,
) -> None:
"""No exception is raised when adding one target."""
name = "x"
width = 1
if application_metadata is None:
encoded_metadata = None
else:
encoded_metadata_bytes = base64.b64encode(
s=application_metadata,
)
encoded_metadata = encoded_metadata_bytes.decode(
encoding="utf-8",
)
target_id = await async_vws_client.add_target(
name=name,
width=width,
image=image,
application_metadata=encoded_metadata,
active_flag=active_flag,
)
target_record = (
await async_vws_client.get_target_record(
target_id=target_id,
)
).target_record
assert target_record.name == name
assert target_record.width == width
assert target_record.active_flag is active_flag
await async_vws_client.wait_for_target_processed(
target_id=target_id,
)
matching_targets = await async_cloud_reco_client.query(
image=image,
)
if active_flag:
[matching_target] = matching_targets
assert matching_target.target_id == target_id
assert matching_target.target_data is not None
query_metadata = matching_target.target_data.application_metadata
assert query_metadata == encoded_metadata
else:
assert matching_targets == []
@staticmethod
@pytest.mark.asyncio
async def test_add_two_targets(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""No exception is raised when adding two targets with
different names.
This demonstrates that the image seek position is not
changed.
"""
for name in ("a", "b"):
await async_vws_client.add_target(
name=name,
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
class TestCustomBaseVWSURL:
"""Tests for using a custom base VWS URL."""
@staticmethod
@pytest.mark.asyncio
async def test_custom_base_url(
image: io.BytesIO | BinaryIO,
) -> None:
"""It is possible to add a target to a database under a
custom VWS URL.
"""
base_vws_url = "http://example.com"
with MockVWS(base_vws_url=base_vws_url) as mock:
database = CloudDatabase()
mock.add_cloud_database(cloud_database=database)
async_vws_client = AsyncVWS(
server_access_key=database.server_access_key,
server_secret_key=database.server_secret_key,
base_vws_url=base_vws_url,
)
await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
class TestListTargets:
"""Tests for listing targets."""
@staticmethod
@pytest.mark.asyncio
async def test_list_targets(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""It is possible to get a list of target IDs."""
id_1 = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
id_2 = await async_vws_client.add_target(
name="a",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
targets = await async_vws_client.list_targets()
assert sorted(targets) == sorted([id_1, id_2])
class TestDelete:
"""Test for deleting a target."""
@staticmethod
@pytest.mark.asyncio
async def test_delete_target(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""It is possible to delete a target."""
target_id = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
await async_vws_client.wait_for_target_processed(
target_id=target_id,
)
targets = await async_vws_client.list_targets()
assert target_id in targets
await async_vws_client.delete_target(
target_id=target_id,
)
targets = await async_vws_client.list_targets()
assert target_id not in targets
class TestGetTargetSummaryReport:
"""Tests for getting a summary report for a target."""
@staticmethod
@pytest.mark.asyncio
async def test_get_target_summary_report(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""Details of a target are returned by
``get_target_summary_report``.
"""
target_name = uuid.uuid4().hex
target_id = await async_vws_client.add_target(
name=target_name,
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
report = await async_vws_client.get_target_summary_report(
target_id=target_id,
)
assert report.target_name == target_name
assert report.active_flag is True
assert report.total_recos == 0
class TestGetDatabaseSummaryReport:
"""Tests for getting a summary report for a database."""
@staticmethod
@pytest.mark.asyncio
async def test_get_target(
async_vws_client: AsyncVWS,
) -> None:
"""Details of a database are returned by
``get_database_summary_report``.
"""
report = await async_vws_client.get_database_summary_report()
assert isinstance(report, DatabaseSummaryReport)
assert report.active_images == 0
class TestGetTargetRecord:
"""Tests for getting a record of a target."""
@staticmethod
@pytest.mark.asyncio
async def test_get_target_record(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""Details of a target are returned by
``get_target_record``.
"""
target_id = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
result = await async_vws_client.get_target_record(
target_id=target_id,
)
expected_target_record = TargetRecord(
target_id=target_id,
active_flag=True,
name="x",
width=1,
tracking_rating=-1,
reco_rating="",
)
assert result.target_record == expected_target_record
assert result.status == TargetStatuses.PROCESSING
class TestWaitForTargetProcessed:
"""Tests for waiting for a target to be processed."""
@staticmethod
@pytest.mark.asyncio
async def test_wait_for_target_processed(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""It is possible to wait until a target is processed."""
target_id = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
report = await async_vws_client.get_target_summary_report(
target_id=target_id,
)
assert report.status == TargetStatuses.PROCESSING
await async_vws_client.wait_for_target_processed(
target_id=target_id,
)
report = await async_vws_client.get_target_summary_report(
target_id=target_id,
)
assert report.status != TargetStatuses.PROCESSING
@staticmethod
@pytest.mark.asyncio
async def test_custom_timeout(
image: io.BytesIO | BinaryIO,
) -> None:
"""It is possible to set a maximum timeout."""
with MockVWS(processing_time_seconds=0.5) as mock:
database = CloudDatabase()
mock.add_cloud_database(cloud_database=database)
async_vws_client = AsyncVWS(
server_access_key=database.server_access_key,
server_secret_key=database.server_secret_key,
)
target_id = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
with pytest.raises(
expected_exception=(TargetProcessingTimeoutError),
):
await async_vws_client.wait_for_target_processed(
target_id=target_id,
timeout_seconds=0.1,
)
class TestGetDuplicateTargets:
"""Tests for getting duplicate targets."""
@staticmethod
@pytest.mark.asyncio
async def test_get_duplicate_targets(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""It is possible to get the IDs of similar targets."""
target_id = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
similar_target_id = await async_vws_client.add_target(
name="a",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
await async_vws_client.wait_for_target_processed(
target_id=target_id,
)
await async_vws_client.wait_for_target_processed(
target_id=similar_target_id,
)
duplicates = await async_vws_client.get_duplicate_targets(
target_id=target_id,
)
assert duplicates == [similar_target_id]
class TestUpdateTarget:
"""Tests for updating a target."""
@staticmethod
@pytest.mark.asyncio
async def test_update_target(
*,
async_vws_client: AsyncVWS,
async_cloud_reco_client: AsyncCloudRecoService,
image: io.BytesIO | BinaryIO,
different_high_quality_image: io.BytesIO,
) -> None:
"""It is possible to update a target."""
target_id = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
await async_vws_client.wait_for_target_processed(
target_id=target_id,
)
[matching_target] = await async_cloud_reco_client.query(
image=image,
)
assert matching_target.target_id == target_id
query_target_data = matching_target.target_data
assert query_target_data is not None
assert query_target_data.application_metadata is None
new_name = uuid.uuid4().hex
new_width = 2.0
new_application_metadata = base64.b64encode(
s=b"a",
).decode(encoding="ascii")
await async_vws_client.update_target(
target_id=target_id,
name=new_name,
width=new_width,
active_flag=True,
image=different_high_quality_image,
application_metadata=new_application_metadata,
)
await async_vws_client.wait_for_target_processed(
target_id=target_id,
)
target_details = await async_vws_client.get_target_record(
target_id=target_id,
)
assert target_details.target_record.name == new_name
assert target_details.target_record.active_flag
@staticmethod
@pytest.mark.asyncio
async def test_no_fields_given(
*,
async_vws_client: AsyncVWS,
image: io.BytesIO | BinaryIO,
) -> None:
"""It is possible to give no update fields."""
target_id = await async_vws_client.add_target(
name="x",
width=1,
image=image,
active_flag=True,
application_metadata=None,
)
await async_vws_client.wait_for_target_processed(
target_id=target_id,
)
await async_vws_client.update_target(
target_id=target_id,
)
class _ForbiddenDownloadTransport:
"""An async transport which refuses to serve a report, as an expired
URL would.
"""
async def aclose(self) -> None:
"""Close the transport."""
async def __call__(
self,
*,
method: str,
url: str,
headers: dict[str, str],
data: bytes,
request_timeout: float | tuple[float, float],
) -> Response:
"""Return a "forbidden" response."""
del method, headers, request_timeout
body = "<Error><Code>AccessDenied</Code></Error>"
return Response(
text=body,
url=url,
status_code=HTTPStatus.FORBIDDEN,
headers={},
request_body=data,
tell_position=0,
content=body.encode(encoding="utf-8"),
)
class TestRecoCountsReport:
"""Tests for database reco counts reports."""
@staticmethod
@pytest.mark.asyncio
async def test_reco_counts_report(
*,
async_vws_client: AsyncVWS,
report_month: datetime.date,
) -> None:
"""A report can be requested, waited for and downloaded."""
client = async_vws_client
report_request = await client.request_database_reco_counts_report(
year=report_month.year,
month=calendar.Month(value=report_month.month),
)
assert report_request.transaction_id
assert report_request.presigned_url
report = await client.wait_for_reco_counts_report(
presigned_url=report_request.presigned_url,
)
# No targets have been recognized, so the report has no rows.
assert not report.reco_counts
assert report.raw_csv.startswith(b"target_id,reco_count")
@staticmethod
@pytest.mark.asyncio
async def test_not_ready(*, current_month: datetime.date) -> None:
"""Downloading a report before Vuforia has generated it raises an
error.
"""
with MockVWS(processing_time_seconds=60) as mock:
database = CloudDatabase()
mock.add_cloud_database(cloud_database=database)
async with AsyncVWS(
server_access_key=database.server_access_key,
server_secret_key=database.server_secret_key,
database_id=database.database_id,
) as client:
report_request = (
await client.request_database_reco_counts_report(
year=current_month.year,
month=calendar.Month(value=current_month.month),
)
)
with pytest.raises(
expected_exception=RecoCountsReportNotReadyError,
) as exc:
await client.download_reco_counts_report(
presigned_url=report_request.presigned_url,
)
assert exc.value.response.status_code == HTTPStatus.NOT_FOUND
@staticmethod
@pytest.mark.asyncio
async def test_wait_timeout(*, current_month: datetime.date) -> None:
"""Waiting for a report which is not generated in time raises an
error.
"""
with MockVWS(processing_time_seconds=60) as mock:
database = CloudDatabase()
mock.add_cloud_database(cloud_database=database)
async with AsyncVWS(
server_access_key=database.server_access_key,
server_secret_key=database.server_secret_key,
database_id=database.database_id,
) as client:
report_request = (
await client.request_database_reco_counts_report(
year=current_month.year,
month=calendar.Month(value=current_month.month),
)
)
maximum_wait_seconds = 5
start_time = time.monotonic()
with pytest.raises(
expected_exception=RecoCountsReportTimeoutError,
):
await client.wait_for_reco_counts_report(
presigned_url=report_request.presigned_url,
seconds_between_requests=0.01,
timeout_seconds=0.05,
)
elapsed_time = time.monotonic() - start_time
assert elapsed_time < maximum_wait_seconds
@staticmethod
@pytest.mark.asyncio
@pytest.mark.parametrize(
argnames=("year", "month"),
argvalues=[
pytest.param(1999, calendar.Month.JANUARY, id="year-in-the-past"),
pytest.param(
1999,
calendar.Month.DECEMBER,
id="year-in-the-past-december",
),
],
)
async def test_month_not_accepted(
*,
async_vws_client: AsyncVWS,
year: int,
month: calendar.Month,
) -> None:
"""Months other than the current and previous month are
rejected.
"""
with pytest.raises(expected_exception=FailError) as exc:
await async_vws_client.request_database_reco_counts_report(
year=year,
month=month,
)
assert exc.value.response.status_code == HTTPStatus.BAD_REQUEST
@staticmethod
@pytest.mark.asyncio
async def test_database_id_does_not_match_keys(
*,
current_month: datetime.date,
) -> None:
"""A database ID which does not match the given keys is
rejected.
"""
with MockVWS() as mock:
database = CloudDatabase()
mock.add_cloud_database(cloud_database=database)
async with AsyncVWS(
server_access_key=database.server_access_key,
server_secret_key=database.server_secret_key,
database_id=uuid.uuid4().hex,
) as client:
with pytest.raises(
expected_exception=AuthenticationFailureError,
) as exc:
await client.request_database_reco_counts_report(
year=current_month.year,
month=calendar.Month(value=current_month.month),
)
assert (
exc.value.response.status_code == HTTPStatus.UNAUTHORIZED
)
@staticmethod
@pytest.mark.asyncio
async def test_download_error() -> None:
"""An error response from the report's URL raises an error."""
async with AsyncVWS(
server_access_key=uuid.uuid4().hex,
server_secret_key=uuid.uuid4().hex,
transport=_ForbiddenDownloadTransport(),
) as client:
with pytest.raises(
expected_exception=RecoCountsReportDownloadError,
) as exc:
await client.download_reco_counts_report(
presigned_url="https://example.com/reports/recoCounts/x",
)
assert exc.value.response.status_code == HTTPStatus.FORBIDDEN
@staticmethod
@pytest.mark.asyncio
async def test_no_database_id(*, current_month: datetime.date) -> None:
"""A client which was given no database ID cannot request a
report.
"""
async with AsyncVWS(
server_access_key=uuid.uuid4().hex,
server_secret_key=uuid.uuid4().hex,
) as client:
with pytest.raises(expected_exception=DatabaseIdNotSetError):
await client.request_database_reco_counts_report(
year=current_month.year,
month=calendar.Month(value=current_month.month),
)
class TestGenerateVumarkInstance:
"""Tests for generating VuMark instances."""
@staticmethod
@pytest.mark.asyncio
@pytest.mark.parametrize(
argnames=("accept", "expected_prefix"),
argvalues=[
pytest.param(
VuMarkAccept.PNG,
b"\x89PNG\r\n\x1a\n",
id="png",
),
pytest.param(
VuMarkAccept.SVG,
b"<",
id="svg",
),
pytest.param(
VuMarkAccept.PDF,
b"%PDF",
id="pdf",
),
],
)
async def test_generate_vumark_instance(
*,
async_vumark_service_client: AsyncVuMarkService,
vumark_target_id: str,
accept: VuMarkAccept,
expected_prefix: bytes,
) -> None:
"""The returned bytes match the requested format."""
result = await async_vumark_service_client.generate_vumark_instance(
target_id=vumark_target_id,
instance_id="12345",
accept=accept,
)
assert result.startswith(expected_prefix)