-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathunit_test.py
1166 lines (1050 loc) · 42.5 KB
/
unit_test.py
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import calendar
import copy
import re
from datetime import datetime
from unittest.mock import Mock, patch
from urllib.parse import parse_qsl, urlparse
import freezegun
import pendulum
import pytest
import pytz
import requests
from airbyte_cdk import AirbyteLogger
from airbyte_protocol.models import SyncMode
from source_zendesk_support.source import BasicApiTokenAuthenticator, SourceZendeskSupport
from source_zendesk_support.streams import (
DATETIME_FORMAT,
END_OF_STREAM_KEY,
LAST_END_TIME_KEY,
AccountAttributes,
ArticleComments,
ArticleCommentVotes,
Articles,
ArticleVotes,
AttributeDefinitions,
AuditLogs,
BaseZendeskSupportStream,
Brands,
CustomRoles,
GroupMemberships,
Groups,
Macros,
OrganizationMemberships,
Organizations,
PostCommentVotes,
Posts,
PostVotes,
SatisfactionRatings,
Schedules,
SlaPolicies,
SourceZendeskIncrementalExportStream,
Tags,
TicketAudits,
TicketComments,
TicketFields,
TicketForms,
TicketMetricEvents,
TicketMetrics,
Tickets,
TicketSkips,
TicketSubstream,
Topics,
UserFields,
Users,
UserSettingsStream,
)
from test_data.data import TICKET_EVENTS_STREAM_RESPONSE
from utils import read_full_refresh
TICKET_SUBSTREAMS = [TicketSubstream, TicketMetrics]
# prepared config
STREAM_ARGS = {
"subdomain": "sandbox",
"start_date": "2021-06-01T00:00:00Z",
"authenticator": BasicApiTokenAuthenticator("[email protected]", "api_token"),
}
# raw config
TEST_CONFIG = {
"subdomain": "sandbox",
"start_date": "2021-06-01T00:00:00Z",
"credentials": {"credentials": "api_token", "email": "[email protected]", "api_token": "api_token"},
}
# raw old config
TEST_OLD_CONFIG = {
"auth_method": {"auth_method": "api_token", "email": "[email protected]", "api_token": "api_token"},
"subdomain": "sandbox",
"start_date": "2021-06-01T00:00:00Z",
}
TEST_CONFIG_WITHOUT_START_DATE = {
"subdomain": "sandbox",
"credentials": {"credentials": "api_token", "email": "[email protected]", "api_token": "api_token"},
}
# raw config oauth
TEST_CONFIG_OAUTH = {
"subdomain": "sandbox",
"start_date": "2021-06-01T00:00:00Z",
"credentials": {"credentials": "oauth2.0", "access_token": "test_access_token"},
}
DATETIME_STR = "2021-07-22T06:55:55Z"
DATETIME_FROM_STR = datetime.strptime(DATETIME_STR, DATETIME_FORMAT)
STREAM_URL = "https://subdomain.zendesk.com/api/v2/stream.json?&start_time=1647532987&page=1"
URL_BASE = "https://sandbox.zendesk.com/api/v2/"
def snake_case(name):
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def get_stream_instance(stream_class, args):
if stream_class in TICKET_SUBSTREAMS:
parent = Tickets(**args)
return stream_class(parent=parent, **args)
return stream_class(**args)
def test_date_time_format():
assert DATETIME_FORMAT == "%Y-%m-%dT%H:%M:%SZ"
def test_last_end_time_key():
assert LAST_END_TIME_KEY == "_last_end_time"
def test_end_of_stream_key():
assert END_OF_STREAM_KEY == "end_of_stream"
def test_token_authenticator():
# we expect base64 from creds input
expected = "dGVzdEBhaXJieXRlLmlvL3Rva2VuOmFwaV90b2tlbg=="
result = BasicApiTokenAuthenticator("[email protected]", "api_token")
assert result._token == expected
@pytest.mark.parametrize(
"config",
[(TEST_CONFIG), (TEST_CONFIG_OAUTH)],
ids=["api_token", "oauth"],
)
def test_convert_config2stream_args(config):
result = SourceZendeskSupport().convert_config2stream_args(config)
assert "authenticator" in result
@freezegun.freeze_time("2022-01-01")
def test_default_start_date():
result = SourceZendeskSupport().convert_config2stream_args(TEST_CONFIG_WITHOUT_START_DATE)
assert result["start_date"] == "2020-01-01T00:00:00Z"
@pytest.mark.parametrize(
"config, expected",
[
(TEST_CONFIG, "aW50ZWdyYXRpb24tdGVzdEBhaXJieXRlLmlvL3Rva2VuOmFwaV90b2tlbg=="),
(TEST_CONFIG_OAUTH, "test_access_token"),
(TEST_OLD_CONFIG, "aW50ZWdyYXRpb24tdGVzdEBhaXJieXRlLmlvL3Rva2VuOmFwaV90b2tlbg=="),
],
ids=["api_token", "oauth", "old_config"],
)
def test_get_authenticator(config, expected):
# we expect base64 from creds input
result = SourceZendeskSupport().get_authenticator(config=config)
assert result._token == expected
@pytest.mark.parametrize(
"response, start_date, check_passed",
[({"active_features": {"organization_access_enabled": True}}, "2020-01-01T00:00:00Z", True), ({}, "2020-01-00T00:00:00Z", False)],
ids=["check_successful", "invalid_start_date"],
)
def test_check(response, start_date, check_passed):
config = copy.deepcopy(TEST_CONFIG)
config["start_date"] = start_date
with patch.object(UserSettingsStream, "get_settings", return_value=response) as mock_method:
ok, _ = SourceZendeskSupport().check_connection(logger=AirbyteLogger, config=config)
assert check_passed == ok
if ok:
mock_method.assert_called()
@pytest.mark.parametrize(
"ticket_forms_response, status_code, expected_n_streams, expected_warnings, reason",
[
('{"ticket_forms": [{"id": 1, "updated_at": "2021-07-08T00:05:45Z"}]}', 200, 35, [], None),
(
'{"error": "Not sufficient permissions"}',
403,
32,
[
"An exception occurred while trying to access TicketForms stream: Request to https://sandbox.zendesk.com/api/v2/ticket_forms failed with status code 403 and error message Not sufficient permissions. Skipping this stream."
],
None,
),
(
"",
404,
32,
[
"An exception occurred while trying to access TicketForms stream: Request to https://sandbox.zendesk.com/api/v2/ticket_forms failed with status code 404 and error message None. Skipping this stream."
],
"Not Found",
),
],
ids=["forms_accessible", "forms_inaccessible", "forms_not_exists"],
)
def test_full_access_streams(caplog, requests_mock, ticket_forms_response, status_code, expected_n_streams, expected_warnings, reason):
requests_mock.get("/api/v2/ticket_forms", status_code=status_code, text=ticket_forms_response, reason=reason)
result = SourceZendeskSupport().streams(config=TEST_CONFIG)
assert len(result) == expected_n_streams
logged_warnings = (record for record in caplog.records if record.levelname == "WARNING")
for msg in expected_warnings:
assert msg in next(logged_warnings).message
@pytest.fixture(autouse=True)
def time_sleep_mock(mocker):
time_mock = mocker.patch("time.sleep", lambda x: None)
yield time_mock
def test_str2datetime():
expected = datetime.strptime(DATETIME_STR, DATETIME_FORMAT)
output = BaseZendeskSupportStream.str2datetime(DATETIME_STR)
assert output == expected
def test_datetime2str():
expected = datetime.strftime(DATETIME_FROM_STR.replace(tzinfo=pytz.UTC), DATETIME_FORMAT)
output = BaseZendeskSupportStream.datetime2str(DATETIME_FROM_STR)
assert output == expected
def test_str2unixtime():
expected = calendar.timegm(DATETIME_FROM_STR.utctimetuple())
output = BaseZendeskSupportStream.str2unixtime(DATETIME_STR)
assert output == expected
def test_check_start_time_param():
expected = 1626936955
start_time = calendar.timegm(pendulum.parse(DATETIME_STR).utctimetuple())
output = SourceZendeskIncrementalExportStream.validate_start_time(start_time)
assert output == expected
@pytest.mark.parametrize(
"stream_state, expected",
[
# valid state, expect the value of the state
({"generated_timestamp": 1648771200}, 1648771200),
(None, 1622505600),
],
ids=["state present", "state is None"],
)
def test_check_stream_state(stream_state, expected):
result = Tickets(**STREAM_ARGS).get_stream_state_value(stream_state)
assert result == expected
def test_parse_response_from_empty_json(requests_mock):
requests_mock.get(STREAM_URL, text="", status_code=403)
test_response = requests.get(STREAM_URL)
output = Schedules(**STREAM_ARGS).parse_response(test_response, {})
assert list(output) == []
def test_parse_response(requests_mock):
requests_mock.get(STREAM_URL, json=TICKET_EVENTS_STREAM_RESPONSE)
test_response = requests.get(STREAM_URL)
output = TicketComments(**STREAM_ARGS).parse_response(test_response)
# get the first parsed element from generator
parsed_output = list(output)[0]
# check, if we have all transformations correctly
for entity in TicketComments.list_entities_from_event:
assert True if entity in parsed_output else False
class TestAllStreams:
def test_ticket_forms_exception_stream(self):
with patch.object(TicketForms, "read_records", return_value=[{}]) as mocked_records:
mocked_records.side_effect = Exception("The error")
streams = SourceZendeskSupport().streams(TEST_CONFIG)
assert not any([isinstance(stream, TicketForms) for stream in streams])
@pytest.mark.parametrize(
"stream_cls, expected",
[
(AuditLogs, "audit_logs"),
(GroupMemberships, "group_memberships"),
(Groups, "groups"),
(Macros, "macros"),
(Organizations, "incremental/organizations.json"),
(Posts, "community/posts"),
(OrganizationMemberships, "organization_memberships"),
(SatisfactionRatings, "satisfaction_ratings"),
(SlaPolicies, "slas/policies.json"),
(Tags, "tags"),
(TicketAudits, "ticket_audits"),
(TicketComments, "incremental/ticket_events.json"),
(TicketFields, "ticket_fields"),
(TicketForms, "ticket_forms"),
(TicketMetrics, "tickets/13/metrics"),
(TicketSkips, "skips.json"),
(TicketMetricEvents, "incremental/ticket_metric_events"),
(Tickets, "incremental/tickets/cursor.json"),
(Users, "incremental/users/cursor.json"),
(Topics, "community/topics"),
(Brands, "brands"),
(CustomRoles, "custom_roles"),
(Schedules, "business_hours/schedules.json"),
(AccountAttributes, "routing/attributes"),
(AttributeDefinitions, "routing/attributes/definitions"),
(UserFields, "user_fields"),
],
ids=[
"AuditLogs",
"GroupMemberships",
"Groups",
"Macros",
"Organizations",
"Posts",
"OrganizationMemberships",
"SatisfactionRatings",
"SlaPolicies",
"Tags",
"TicketAudits",
"TicketComments",
"TicketFields",
"TicketForms",
"TicketMetrics",
"TicketSkips",
"TicketMetricEvents",
"Tickets",
"Topics",
"Users",
"Brands",
"CustomRoles",
"Schedules",
"AccountAttributes",
"AttributeDefinitions",
"UserFields",
],
)
def test_path(self, stream_cls, expected):
stream = get_stream_instance(stream_cls, STREAM_ARGS)
result = stream.path(stream_slice={"ticket_id": "13"})
assert result == expected
class TestSourceZendeskSupportStream:
@pytest.mark.parametrize(
"stream_cls",
[(Macros), (Posts), (Groups), (SatisfactionRatings), (TicketFields), (TicketMetrics), (Topics)],
ids=["Macros", "Posts", "Groups", "SatisfactionRatings", "TicketFields", "TicketMetrics", "Topics"],
)
def test_parse_response(self, requests_mock, stream_cls):
if stream_cls in TICKET_SUBSTREAMS:
parent = Tickets(**STREAM_ARGS)
stream = stream_cls(parent=parent, **STREAM_ARGS)
expected = {"updated_at": "2022-03-17T16:03:07Z"}
response_field = stream.response_list_name
else:
stream = stream_cls(**STREAM_ARGS)
expected = [{"updated_at": "2022-03-17T16:03:07Z"}]
response_field = stream.name
requests_mock.get(STREAM_URL, json={response_field: expected})
test_response = requests.get(STREAM_URL)
output = list(stream.parse_response(test_response, None))
expected = expected if isinstance(expected, list) else [expected]
assert expected == output
def test_attribute_definition_parse_response(self, requests_mock):
stream = AttributeDefinitions(**STREAM_ARGS)
conditions_all = {"subject": "number_of_incidents", "title": "Number of incidents"}
conditions_any = {"subject": "brand", "title": "Brand"}
response_json = {"definitions": {"conditions_all": [conditions_all], "conditions_any": [conditions_any]}}
requests_mock.get(STREAM_URL, json=response_json)
test_response = requests.get(STREAM_URL)
output = list(stream.parse_response(test_response, None))
expected_records = [
{"condition": "all", "subject": "number_of_incidents", "title": "Number of incidents"},
{"condition": "any", "subject": "brand", "title": "Brand"},
]
assert expected_records == output
@pytest.mark.parametrize(
"stream_cls",
[(Macros), (Organizations), (Posts), (Groups), (SatisfactionRatings), (TicketFields), (TicketMetrics), (Topics)],
ids=["Macros", "Organizations", "Posts", "Groups", "SatisfactionRatings", "TicketFields", "TicketMetrics", "Topics"],
)
def test_url_base(self, stream_cls):
stream = get_stream_instance(stream_cls, STREAM_ARGS)
result = stream.url_base
assert result == URL_BASE
@pytest.mark.parametrize(
"stream_cls, current_state, last_record, expected",
[
(Macros, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
(Posts, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
(
Organizations,
{"updated_at": "2022-03-17T16:03:07Z"},
{"updated_at": "2023-03-17T16:03:07Z"},
{"updated_at": "2023-03-17T16:03:07Z"},
),
(Groups, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
(SatisfactionRatings, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
(TicketFields, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
(TicketMetrics, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
(Topics, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
],
ids=["Macros", "Posts", "Organizations", "Groups", "SatisfactionRatings", "TicketFields", "TicketMetrics", "Topics"],
)
def test_get_updated_state(self, stream_cls, current_state, last_record, expected):
stream = get_stream_instance(stream_cls, STREAM_ARGS)
result = stream.get_updated_state(current_state, last_record)
assert expected == result
@pytest.mark.parametrize(
"stream_cls, expected",
[
(Macros, None),
(Posts, None),
(Organizations, {}),
(Groups, None),
(TicketFields, None),
],
ids=[
"Macros",
"Posts",
"Organizations",
"Groups",
"TicketFields",
],
)
def test_next_page_token(self, stream_cls, expected, mocker):
stream = stream_cls(**STREAM_ARGS)
posts_response = mocker.Mock()
posts_response.json.return_value = {"next_page": None}
result = stream.next_page_token(response=posts_response)
assert expected == result
@pytest.mark.parametrize(
"stream_cls, expected",
[
(Macros, {"start_time": 1622505600}),
(Organizations, {"start_time": 1622505600}),
(Groups, {"start_time": 1622505600}),
(TicketFields, {"start_time": 1622505600}),
],
ids=[
"Macros",
"Organizations",
"Groups",
"TicketFields",
],
)
def test_request_params(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.request_params(stream_state={})
assert expected == result
class TestSourceZendeskSupportFullRefreshStream:
@pytest.mark.parametrize(
"stream_cls",
[(Tags), (SlaPolicies), (Brands), (CustomRoles), (Schedules), (UserSettingsStream), (AccountAttributes), (AttributeDefinitions)],
ids=[
"Tags",
"SlaPolicies",
"Brands",
"CustomRoles",
"Schedules",
"UserSettingsStream",
"AccountAttributes",
"AttributeDefinitions",
],
)
def test_url_base(self, stream_cls):
stream = stream_cls(**STREAM_ARGS)
result = stream.url_base
assert result == URL_BASE
@pytest.mark.parametrize(
"stream_cls",
[
(Tags),
(SlaPolicies),
(Brands),
(CustomRoles),
(Schedules),
(UserSettingsStream),
(AccountAttributes),
(AttributeDefinitions),
],
ids=[
"Tags",
"SlaPolicies",
"Brands",
"CustomRoles",
"Schedules",
"UserSettingsStream",
"AccountAttributes",
"AttributeDefinitions",
],
)
def test_next_page_token(self, requests_mock, stream_cls):
stream = stream_cls(**STREAM_ARGS)
stream_name = snake_case(stream.__class__.__name__)
requests_mock.get(STREAM_URL, json={stream_name: {}})
test_response = requests.get(STREAM_URL)
output = stream.next_page_token(test_response)
assert output is None
@pytest.mark.parametrize(
"stream_cls, expected_params",
[
(Tags, {"page[size]": 100}),
(SlaPolicies, {}),
(Brands, {"page[size]": 100}),
(CustomRoles, {}),
(Schedules, {"page[size]": 100}),
(UserSettingsStream, {}),
(AccountAttributes, {}),
(AttributeDefinitions, {}),
],
ids=[
"Tags",
"SlaPolicies",
"Brands",
"CustomRoles",
"Schedules",
"UserSettingsStream",
"AccountAttributes",
"AttributeDefinitions",
],
)
def test_request_params(self, stream_cls, expected_params):
stream = stream_cls(**STREAM_ARGS)
result = stream.request_params(next_page_token=None, stream_state=None)
assert expected_params == result
class TestSourceZendeskSupportCursorPaginationStream:
@pytest.mark.parametrize(
"stream_cls, current_state, last_record, expected",
[
(GroupMemberships, {}, {"updated_at": "2022-03-17T16:03:07Z"}, {"updated_at": "2022-03-17T16:03:07Z"}),
(TicketForms, {}, {"updated_at": "2023-03-17T16:03:07Z"}, {"updated_at": "2023-03-17T16:03:07Z"}),
(TicketMetricEvents, {}, {"time": "2024-03-17T16:03:07Z"}, {"time": "2024-03-17T16:03:07Z"}),
(TicketAudits, {}, {"created_at": "2025-03-17T16:03:07Z"}, {"created_at": "2025-03-17T16:03:07Z"}),
(OrganizationMemberships, {}, {"updated_at": "2025-03-17T16:03:07Z"}, {"updated_at": "2025-03-17T16:03:07Z"}),
(TicketSkips, {}, {"updated_at": "2025-03-17T16:03:07Z"}, {"updated_at": "2025-03-17T16:03:07Z"}),
],
ids=[
"GroupMemberships",
"TicketForms",
"TicketMetricEvents",
"TicketAudits",
"OrganizationMemberships",
"TicketSkips",
],
)
def test_get_updated_state(self, stream_cls, current_state, last_record, expected):
stream = get_stream_instance(stream_cls, STREAM_ARGS)
result = stream.get_updated_state(current_state, last_record)
assert expected == result
@pytest.mark.parametrize(
"stream_cls, response, expected",
[
(GroupMemberships, {}, None),
(TicketForms, {}, None),
(
TicketMetricEvents,
{
"meta": {"has_more": True, "after_cursor": "<after_cursor>", "before_cursor": "<before_cursor>"},
"links": {
"prev": "https://subdomain.zendesk.com/api/v2/ticket_metrics.json?page%5Bbefore%5D=<before_cursor>%3D&page%5Bsize%5D=2",
"next": "https://subdomain.zendesk.com/api/v2/ticket_metrics.json?page%5Bafter%5D=<after_cursor>%3D&page%5Bsize%5D=2",
},
},
{"page[after]": "<after_cursor>"},
),
(TicketAudits, {}, None),
(SatisfactionRatings, {}, None),
(
OrganizationMemberships,
{
"meta": {"has_more": True, "after_cursor": "<after_cursor>", "before_cursor": "<before_cursor>"},
"links": {
"prev": "https://subdomain.zendesk.com/api/v2/ticket_metrics.json?page%5Bbefore%5D=<before_cursor>%3D&page%5Bsize%5D=2",
"next": "https://subdomain.zendesk.com/api/v2/ticket_metrics.json?page%5Bafter%5D=<after_cursor>%3D&page%5Bsize%5D=2",
},
},
{"page[after]": "<after_cursor>"},
),
(
TicketSkips,
{
"meta": {"has_more": True, "after_cursor": "<after_cursor>", "before_cursor": "<before_cursor>"},
"links": {
"prev": "https://subdomain.zendesk.com/api/v2/ticket_metrics.json?page%5Bbefore%5D=<before_cursor>%3D&page%5Bsize%5D=2",
"next": "https://subdomain.zendesk.com/api/v2/ticket_metrics.json?page%5Bafter%5D=<after_cursor>%3D&page%5Bsize%5D=2",
},
},
{"page[after]": "<after_cursor>"},
),
],
ids=[
"GroupMemberships",
"TicketForms",
"TicketMetricEvents",
"TicketAudits",
"SatisfactionRatings",
"OrganizationMemberships",
"TicketSkips",
],
)
def test_next_page_token(self, requests_mock, stream_cls, response, expected):
stream = stream_cls(**STREAM_ARGS)
requests_mock.get(STREAM_URL, json=response)
test_response = requests.get(STREAM_URL)
output = stream.next_page_token(test_response)
assert output == expected
@pytest.mark.parametrize(
"stream_cls, expected",
[
(GroupMemberships, 1622505600),
(TicketForms, 1622505600),
(TicketMetricEvents, 1622505600),
(TicketAudits, 1622505600),
(OrganizationMemberships, 1622505600),
(TicketSkips, 1622505600),
],
ids=["GroupMemberships", "TicketForms", "TicketMetricEvents", "TicketAudits", "OrganizationMemberships", "TicketSkips"],
)
def test_check_stream_state(self, stream_cls, expected):
stream = get_stream_instance(stream_cls, STREAM_ARGS)
result = stream.get_stream_state_value()
assert result == expected
@pytest.mark.parametrize(
"stream_cls, expected",
[
(GroupMemberships, {"page[size]": 100, "sort_by": "asc", "start_time": 1622505600}),
(TicketForms, {"start_time": 1622505600}),
(TicketMetricEvents, {"page[size]": 100, "start_time": 1622505600}),
(TicketAudits, {"sort_by": "created_at", "sort_order": "desc", "limit": 200}),
(SatisfactionRatings, {"page[size]": 100, "sort_by": "created_at", "start_time": 1622505600}),
(OrganizationMemberships, {"page[size]": 100, "start_time": 1622505600}),
(TicketSkips, {"page[size]": 100, "start_time": 1622505600}),
],
ids=[
"GroupMemberships",
"TicketForms",
"TicketMetricEvents",
"TicketAudits",
"SatisfactionRatings",
"OrganizationMemberships",
"TicketSkips",
],
)
def test_request_params(self, stream_cls, expected):
stream = get_stream_instance(stream_cls, STREAM_ARGS)
result = stream.request_params(stream_state=None, next_page_token=None)
assert expected == result
class TestSourceZendeskIncrementalExportStream:
@pytest.mark.parametrize(
"stream_cls",
[
(Users),
(Tickets),
],
ids=[
"Users",
"Tickets",
],
)
def test_check_start_time_param(self, stream_cls):
expected = int(dict(parse_qsl(urlparse(STREAM_URL).query)).get("start_time"))
stream = stream_cls(**STREAM_ARGS)
result = stream.validate_start_time(expected)
assert result == expected
@pytest.mark.parametrize(
"stream_cls",
[
(Users),
(Tickets),
],
ids=[
"Users",
"Tickets",
],
)
def test_next_page_token(self, requests_mock, stream_cls):
stream = stream_cls(**STREAM_ARGS)
stream_name = snake_case(stream.__class__.__name__)
requests_mock.get(STREAM_URL, json={stream_name: {}})
test_response = requests.get(STREAM_URL)
output = stream.next_page_token(test_response)
assert output == {}
@pytest.mark.parametrize(
"stream_cls, expected",
[
(Users, {"start_time": 1622505600}),
(Tickets, {"start_time": 1622505600}),
(Articles, {"sort_by": "updated_at", "sort_order": "asc", "start_time": 1622505600}),
],
ids=[
"Users",
"Tickets",
"Articles",
],
)
def test_request_params(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.request_params(next_page_token=None, stream_state=None)
assert expected == result
@pytest.mark.parametrize(
"stream_cls",
[
(Users),
(Tickets),
],
ids=[
"Users",
"Tickets",
],
)
def test_parse_response(self, requests_mock, stream_cls):
stream = stream_cls(**STREAM_ARGS)
stream_name = snake_case(stream.__class__.__name__)
expected = [{"updated_at": "2022-03-17T16:03:07Z"}]
requests_mock.get(STREAM_URL, json={stream_name: expected})
test_response = requests.get(STREAM_URL)
output = list(stream.parse_response(test_response))
assert expected == output
@pytest.mark.parametrize(
"stream_cls, stream_slice, expected_path",
[
(ArticleVotes, {"parent": {"id": 1}}, "help_center/articles/1/votes"),
(ArticleComments, {"parent": {"id": 1}}, "help_center/articles/1/comments"),
(ArticleCommentVotes, {"parent": {"id": 1, "source_id": 1}}, "help_center/articles/1/comments/1/votes"),
],
ids=[
"ArticleVotes_path",
"ArticleComments_path",
"ArticleCommentVotes_path",
],
)
def test_path(self, stream_cls, stream_slice, expected_path):
stream = stream_cls(**STREAM_ARGS)
assert stream.path(stream_slice=stream_slice) == expected_path
class TestSourceZendeskSupportTicketEventsExportStream:
@pytest.mark.parametrize(
"stream_cls, expected",
[
(TicketComments, True),
],
ids=[
"TicketComments",
],
)
def test_update_event_from_record(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.update_event_from_record
assert result == expected
@pytest.mark.parametrize(
"stream_cls",
[
(TicketComments),
],
ids=[
"TicketComments",
],
)
def test_parse_response(self, requests_mock, stream_cls):
stream = stream_cls(**STREAM_ARGS)
stream_name = snake_case(stream.__class__.__name__)
requests_mock.get(STREAM_URL, json={stream_name: []})
test_response = requests.get(STREAM_URL)
output = list(stream.parse_response(test_response))
assert output == []
@pytest.mark.parametrize(
"stream_cls, expected",
[
(TicketComments, "created_at"),
],
ids=[
"TicketComments",
],
)
def test_cursor_field(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.cursor_field
assert result == expected
@pytest.mark.parametrize(
"stream_cls, expected",
[
(TicketComments, "ticket_events"),
],
ids=[
"TicketComments",
],
)
def test_response_list_name(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.response_list_name
assert result == expected
@pytest.mark.parametrize(
"stream_cls, expected",
[
(TicketComments, "child_events"),
],
ids=[
"TicketComments",
],
)
def test_response_target_entity(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.response_target_entity
assert result == expected
@pytest.mark.parametrize(
"stream_cls, expected",
[
(TicketComments, ["via_reference_id", "ticket_id", "timestamp"]),
],
ids=[
"TicketComments",
],
)
def test_list_entities_from_event(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.list_entities_from_event
assert result == expected
@pytest.mark.parametrize(
"stream_cls, expected",
[
(TicketComments, "Comment"),
],
ids=[
"TicketComments",
],
)
def test_event_type(self, stream_cls, expected):
stream = stream_cls(**STREAM_ARGS)
result = stream.event_type
assert result == expected
def test_read_tickets_stream(requests_mock):
requests_mock.get(
"https://subdomain.zendesk.com/api/v2/incremental/tickets/cursor.json",
json={
"tickets": [
{"custom_fields": []},
{},
{
"custom_fields": [
{"id": 360023382300, "value": None},
{"id": 360004841380, "value": "customer_tickets"},
{"id": 360022469240, "value": "5"},
{"id": 360023712840, "value": False},
]
},
],
"end_of_stream": True,
},
)
stream = Tickets(subdomain="subdomain", start_date="2020-01-01T00:00:00Z")
records = read_full_refresh(stream)
assert records == [
{"custom_fields": []},
{},
{
"custom_fields": [
{"id": 360023382300, "value": None},
{"id": 360004841380, "value": "customer_tickets"},
{"id": 360022469240, "value": "5"},
{"id": 360023712840, "value": "False"},
]
},
]
def test_read_post_votes_stream(requests_mock):
post_response = {
"posts": [{"id": 7253375870607, "title": "Test_post", "created_at": "2023-01-01T00:00:00Z", "updated_at": "2023-01-01T00:00:00Z"}]
}
requests_mock.get("https://subdomain.zendesk.com/api/v2/community/posts", json=post_response)
post_votes_response = {
"votes": [
{
"author_id": 89567,
"body": "Test_comment for Test_post",
"id": 35467,
"post_id": 7253375870607,
"updated_at": "2023-01-02T00:00:00Z",
}
]
}
requests_mock.get("https://subdomain.zendesk.com/api/v2/community/posts/7253375870607/votes", json=post_votes_response)
stream = PostVotes(subdomain="subdomain", start_date="2020-01-01T00:00:00Z")
records = read_full_refresh(stream)
assert records == post_votes_response.get("votes")
def test_read_post_comment_votes_stream(requests_mock):
post_response = {
"posts": [{"id": 7253375870607, "title": "Test_post", "created_at": "2023-01-01T00:00:00Z", "updated_at": "2023-01-01T00:00:00Z"}]
}
requests_mock.get("https://subdomain.zendesk.com/api/v2/community/posts", json=post_response)
post_comments_response = {
"comments": [
{
"author_id": 89567,
"body": "Test_comment for Test_post",
"id": 35467,
"post_id": 7253375870607,
"updated_at": "2023-01-02T00:00:00Z",
}
]
}
requests_mock.get("https://subdomain.zendesk.com/api/v2/community/posts/7253375870607/comments", json=post_comments_response)
votes = [{"id": 35467, "user_id": 888887, "value": -1, "updated_at": "2023-01-03T00:00:00Z"}]
requests_mock.get("https://subdomain.zendesk.com/api/v2/community/posts/7253375870607/comments/35467/votes", json={"votes": votes})
stream = PostCommentVotes(subdomain="subdomain", start_date="2020-01-01T00:00:00Z")
records = read_full_refresh(stream)
assert records == votes
def test_read_ticket_metric_events_request_params(requests_mock):
first_page_response = {
"ticket_metric_events": [
{"id": 1, "ticket_id": 123, "metric": "agent_work_time", "instance_id": 0, "type": "measure", "time": "2020-01-01T01:00:00Z"},
{
"id": 2,
"ticket_id": 123,
"metric": "pausable_update_time",
"instance_id": 0,
"type": "measure",
"time": "2020-01-01T01:00:00Z",
},
{"id": 3, "ticket_id": 123, "metric": "reply_time", "instance_id": 0, "type": "measure", "time": "2020-01-01T01:00:00Z"},
{
"id": 4,
"ticket_id": 123,
"metric": "requester_wait_time",
"instance_id": 1,
"type": "activate",
"time": "2020-01-01T01:00:00Z",
},
],
"meta": {"has_more": True, "after_cursor": "<after_cursor>", "before_cursor": "<before_cursor>"},
"links": {
"prev": "https://subdomain.zendesk.com/api/v2/incremental/ticket_metric_events.json?page%5Bbefore%5D=<before_cursor>&page%5Bsize%5D=100&start_time=1577836800",
"next": "https://subdomain.zendesk.com/api/v2/incremental/ticket_metric_events.json?page%5Bafter%5D=<after_cursor>&page%5Bsize%5D=100&start_time=1577836800",
},
"end_of_stream": False,
}
second_page_response = {
"ticket_metric_events": [
{
"id": 5163373143183,
"ticket_id": 130,
"metric": "reply_time",
"instance_id": 1,
"type": "fulfill",
"time": "2022-07-18T16:39:48Z",
},
{