-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
test_source.py
663 lines (556 loc) · 23.9 KB
/
test_source.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
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import logging
from datetime import timedelta
from http import HTTPStatus
from unittest.mock import MagicMock
import mock
import pendulum
import pytest
from airbyte_cdk.models import ConfiguredAirbyteCatalog, SyncMode, Type
from source_hubspot.errors import HubspotRateLimited, InvalidStartDateConfigError
from source_hubspot.helpers import APIv3Property
from source_hubspot.source import SourceHubspot
from source_hubspot.streams import API, Companies, Deals, Engagements, MarketingEmails, Products, Stream
from .utils import read_full_refresh, read_incremental
NUMBER_OF_PROPERTIES = 2000
logger = logging.getLogger("test_client")
@pytest.fixture(autouse=True)
def time_sleep_mock(mocker):
time_mock = mocker.patch("time.sleep", lambda x: None)
yield time_mock
def test_check_connection_ok(requests_mock, config):
responses = [
{"json": [], "status_code": 200},
]
requests_mock.register_uri("GET", "/properties/v2/contact/properties", responses)
ok, error_msg = SourceHubspot().check_connection(logger, config=config)
assert ok
assert not error_msg
def test_check_connection_empty_config(config):
config = {}
with pytest.raises(KeyError):
SourceHubspot().check_connection(logger, config=config)
def test_check_connection_invalid_config(config):
config.pop("start_date")
with pytest.raises(KeyError):
SourceHubspot().check_connection(logger, config=config)
def test_check_connection_exception(config):
ok, error_msg = SourceHubspot().check_connection(logger, config=config)
assert not ok
assert error_msg
def test_check_connection_invalid_start_date_exception(config_invalid_date):
with pytest.raises(InvalidStartDateConfigError):
ok, error_msg = SourceHubspot().check_connection(logger, config=config_invalid_date)
assert not ok
assert error_msg
@mock.patch("source_hubspot.source.SourceHubspot.get_custom_object_streams")
def test_streams(requests_mock, config):
streams = SourceHubspot().streams(config)
assert len(streams) == 28
def test_check_credential_title_exception(config):
config["credentials"].pop("credentials_title")
with pytest.raises(Exception):
SourceHubspot().check_connection(logger, config=config)
def test_parse_and_handle_errors(some_credentials):
response = MagicMock()
response.status_code = HTTPStatus.TOO_MANY_REQUESTS
with pytest.raises(HubspotRateLimited):
API(some_credentials)._parse_and_handle_errors(response)
def test_convert_datetime_to_string():
pendulum_time = pendulum.now()
assert Stream._convert_datetime_to_string(pendulum_time, declared_format="date")
assert Stream._convert_datetime_to_string(pendulum_time, declared_format="date-time")
def test_cast_datetime(common_params, caplog):
field_value = pendulum.now()
field_name = "curent_time"
Companies(**common_params)._cast_datetime(field_name, field_value)
expected_warining_message = {
"type": "LOG",
"log": {
"level": "WARN",
"message": f"Couldn't parse date/datetime string in {field_name}, trying to parse timestamp... Field value: {field_value}. Ex: argument of type 'DateTime' is not iterable",
},
}
assert expected_warining_message["log"]["message"] in caplog.text
def test_check_connection_backoff_on_limit_reached(requests_mock, config):
"""Error once, check that we retry and not fail"""
responses = [
{"json": {"error": "limit reached"}, "status_code": 429, "headers": {"Retry-After": "0"}},
{"json": [], "status_code": 200},
]
requests_mock.register_uri("GET", "/properties/v2/contact/properties", responses)
source = SourceHubspot()
alive, error = source.check_connection(logger=logger, config=config)
assert alive
assert not error
def test_check_connection_backoff_on_server_error(requests_mock, config):
"""Error once, check that we retry and not fail"""
responses = [
{"json": {"error": "something bad"}, "status_code": 500},
{"json": [], "status_code": 200},
]
requests_mock.register_uri("GET", "/properties/v2/contact/properties", responses)
source = SourceHubspot()
alive, error = source.check_connection(logger=logger, config=config)
assert alive
assert not error
def test_stream_forbidden(requests_mock, config, caplog):
json = {
"status": "error",
"message": "This access_token does not have proper permissions!",
}
requests_mock.get("https://api.hubapi.com/automation/v3/workflows", json=json, status_code=403)
requests_mock.get("https://api.hubapi.com/crm/v3/schemas", json=json, status_code=403)
catalog = ConfiguredAirbyteCatalog.parse_obj(
{
"streams": [
{
"stream": {
"name": "workflows",
"json_schema": {},
"supported_sync_modes": ["full_refresh"],
},
"sync_mode": "full_refresh",
"destination_sync_mode": "overwrite",
}
]
}
)
records = list(SourceHubspot().read(logger, config, catalog, {}))
assert json["message"] in caplog.text
records = [r for r in records if r.type == Type.RECORD]
assert not records
def test_parent_stream_forbidden(requests_mock, config, caplog, fake_properties_list):
json = {
"status": "error",
"message": "This access_token does not have proper permissions!",
}
requests_mock.get("https://api.hubapi.com/marketing/v3/forms", json=json, status_code=403)
properties_response = [
{
"json": [
{"name": property_name, "type": "string", "updatedAt": 1571085954360, "createdAt": 1565059306048}
for property_name in fake_properties_list
],
"status_code": 200,
}
]
requests_mock.get("https://api.hubapi.com/properties/v2/form/properties", properties_response)
requests_mock.get("https://api.hubapi.com/crm/v3/schemas", json=json, status_code=403)
catalog = ConfiguredAirbyteCatalog.parse_obj(
{
"streams": [
{
"stream": {
"name": "form_submissions",
"json_schema": {},
"supported_sync_modes": ["full_refresh"],
},
"sync_mode": "full_refresh",
"destination_sync_mode": "overwrite",
}
]
}
)
records = list(SourceHubspot().read(logger, config, catalog, {}))
assert json["message"] in caplog.text
records = [r for r in records if r.type == Type.RECORD]
assert not records
class TestSplittingPropertiesFunctionality:
BASE_OBJECT_BODY = {
"createdAt": "2020-12-10T07:58:09.554Z",
"updatedAt": "2021-07-31T08:18:58.954Z",
"archived": False,
}
@staticmethod
def set_mock_properties(requests_mock, url, fake_properties_list):
properties_response = [
{
"json": [
{"name": property_name, "type": "string", "updatedAt": 1571085954360, "createdAt": 1565059306048}
for property_name in fake_properties_list
],
"status_code": 200,
},
]
requests_mock.register_uri("GET", url, properties_response)
# Mock the getter method that handles requests.
def get(self, url, api, params=None):
response = api._session.get(api.BASE_URL + url, params=params)
return api._parse_and_handle_errors(response)
def test_stream_with_splitting_properties(self, requests_mock, api, fake_properties_list, common_params):
"""
Check working stream `companies` with large list of properties using new functionality with splitting properties
"""
test_stream = Companies(**common_params)
parsed_properties = list(APIv3Property(fake_properties_list).split())
self.set_mock_properties(requests_mock, "/properties/v2/company/properties", fake_properties_list)
record_ids_paginated = [list(map(str, range(100))), list(map(str, range(100, 150, 1)))]
test_stream._sync_mode = SyncMode.full_refresh
test_stream_url = test_stream.url
test_stream._sync_mode = None
after_id = None
for id_list in record_ids_paginated:
for property_slice in parsed_properties:
record_responses = [
{
"json": {
"results": [
{**self.BASE_OBJECT_BODY, **{"id": id, "properties": {p: "fake_data" for p in property_slice.properties}}}
for id in id_list
],
"paging": {"next": {"after": id_list[-1]}} if len(id_list) == 100 else {},
},
"status_code": 200,
}
]
prop_key, prop_val = next(iter(property_slice.as_url_param().items()))
requests_mock.register_uri(
"GET",
f"{test_stream_url}?limit=100&{prop_key}={prop_val}{f'&after={after_id}' if after_id else ''}",
record_responses,
)
after_id = id_list[-1]
# Read preudo-output from generator object
stream_records = read_full_refresh(test_stream)
# check that we have records for all set ids, and that each record has 2000 properties (not more, and not less)
assert len(stream_records) == sum([len(ids) for ids in record_ids_paginated])
for record in stream_records:
assert len(record["properties"]) == NUMBER_OF_PROPERTIES
def test_stream_with_splitting_properties_with_pagination(self, requests_mock, common_params, api, fake_properties_list):
"""
Check working stream `products` with large list of properties using new functionality with splitting properties
"""
parsed_properties = list(APIv3Property(fake_properties_list).split())
self.set_mock_properties(requests_mock, "/properties/v2/product/properties", fake_properties_list)
test_stream = Products(**common_params)
for property_slice in parsed_properties:
record_responses = [
{
"json": {
"results": [
{**self.BASE_OBJECT_BODY, **{"id": id, "properties": {p: "fake_data" for p in property_slice.properties}}}
for id in ["6043593519", "1092593519", "1092593518", "1092593517", "1092593516"]
],
"paging": {},
},
"status_code": 200,
}
]
prop_key, prop_val = next(iter(property_slice.as_url_param().items()))
requests_mock.register_uri("GET", f"{test_stream.url}?{prop_key}={prop_val}", record_responses)
stream_records = list(test_stream.read_records(sync_mode=SyncMode.incremental))
assert len(stream_records) == 5
for record in stream_records:
assert len(record["properties"]) == NUMBER_OF_PROPERTIES
def test_stream_with_splitting_properties_with_new_record(self, requests_mock, common_params, api, fake_properties_list):
"""
Check working stream `workflows` with large list of properties using new functionality with splitting properties
"""
parsed_properties = list(APIv3Property(fake_properties_list).split())
self.set_mock_properties(requests_mock, "/properties/v2/deal/properties", fake_properties_list)
test_stream = Deals(**common_params)
ids_list = ["6043593519", "1092593519", "1092593518", "1092593517", "1092593516"]
for property_slice in parsed_properties:
record_responses = [
{
"json": {
"results": [
{**self.BASE_OBJECT_BODY, **{"id": id, "properties": {p: "fake_data" for p in property_slice.properties}}}
for id in ids_list
],
"paging": {},
},
"status_code": 200,
}
]
test_stream._sync_mode = SyncMode.full_refresh
prop_key, prop_val = next(iter(property_slice.as_url_param().items()))
requests_mock.register_uri("GET", f"{test_stream.url}?{prop_key}={prop_val}", record_responses)
test_stream._sync_mode = None
ids_list.append("1092593513")
stream_records = read_full_refresh(test_stream)
assert len(stream_records) == 6
@pytest.fixture(name="configured_catalog")
def configured_catalog_fixture():
configured_catalog = {
"streams": [
{
"stream": {
"name": "quotes",
"json_schema": {},
"supported_sync_modes": ["full_refresh", "incremental"],
"source_defined_cursor": True,
"default_cursor_field": ["updatedAt"],
},
"sync_mode": "incremental",
"cursor_field": ["updatedAt"],
"destination_sync_mode": "append",
}
]
}
return ConfiguredAirbyteCatalog.parse_obj(configured_catalog)
def test_search_based_stream_should_not_attempt_to_get_more_than_10k_records(requests_mock, common_params, fake_properties_list):
"""
If there are more than 10,000 records that would be returned by the Hubspot search endpoint,
the CRMSearchStream instance should stop at the 10Kth record
"""
responses = [
{
"json": {
"results": [{"id": f"{y}", "updatedAt": "2022-02-25T16:43:11Z"} for y in range(100)],
"paging": {
"next": {
"after": f"{x * 100}",
}
},
},
"status_code": 200,
}
for x in range(1, 101)
]
# After reaching 10K records, it performs a new search query.
responses.extend(
[
{
"json": {
"results": [{"id": f"{y}", "updatedAt": "2022-03-01T00:00:00Z"} for y in range(100)],
"paging": {
"next": {
"after": f"{x * 100}",
}
},
},
"status_code": 200,
}
for x in range(1, 10)
]
)
# Last page... it does not have paging->next->after
responses.append(
{
"json": {"results": [{"id": f"{y}", "updatedAt": "2022-03-01T00:00:00Z"} for y in range(100)], "paging": {}},
"status_code": 200,
}
)
properties_response = [
{
"json": [
{"name": property_name, "type": "string", "updatedAt": 1571085954360, "createdAt": 1565059306048}
for property_name in fake_properties_list
],
"status_code": 200,
}
]
# Create test_stream instance with some state
test_stream = Companies(**common_params)
test_stream._init_sync = pendulum.parse("2022-02-24T16:43:11Z")
test_stream.state = {"updatedAt": "2022-02-24T16:43:11Z"}
# Mocking Request
test_stream._sync_mode = SyncMode.incremental
requests_mock.register_uri("POST", test_stream.url, responses)
test_stream._sync_mode = None
requests_mock.register_uri("GET", "/properties/v2/company/properties", properties_response)
requests_mock.register_uri("POST", "/crm/v4/associations/company/contacts/batch/read", [{"status_code": 200, "json": {"results": []}}])
records, _ = read_incremental(test_stream, {})
# The stream should not attempt to get more than 10K records.
# Instead, it should use the new state to start a new search query.
assert len(records) == 11000
assert test_stream.state["updatedAt"] == test_stream._init_sync.to_iso8601_string()
def test_engagements_stream_pagination_works(requests_mock, common_params):
"""
Tests the engagements stream handles pagination correctly, for both
full_refresh and incremental sync modes.
"""
# Mocking Request
requests_mock.register_uri(
"GET",
"/engagements/v1/engagements/paged?count=250",
[
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": 1641234593251}} for y in range(250)],
"hasMore": True,
"offset": 250,
},
"status_code": 200,
},
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": 1641234593251}} for y in range(250, 500)],
"hasMore": True,
"offset": 500,
},
"status_code": 200,
},
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": 1641234595251}} for y in range(500, 600)],
"hasMore": False,
},
"status_code": 200,
},
],
)
requests_mock.register_uri(
"GET",
"/engagements/v1/engagements/recent/modified?count=100",
[
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": 1641234595252}} for y in range(100)],
"hasMore": True,
"offset": 100,
},
"status_code": 200,
},
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": 1641234595252}} for y in range(100, 200)],
"hasMore": True,
"offset": 200,
},
"status_code": 200,
},
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": 1641234595252}} for y in range(200, 250)],
"hasMore": False,
},
"status_code": 200,
},
],
)
# Create test_stream instance for full refresh.
test_stream = Engagements(**common_params)
records = read_full_refresh(test_stream)
# The stream should handle pagination correctly and output 600 records.
assert len(records) == 600
assert test_stream.state["lastUpdated"] == int(test_stream._init_sync.timestamp() * 1000)
test_stream = Engagements(**common_params)
records, _ = read_incremental(test_stream, {})
# The stream should handle pagination correctly and output 250 records.
assert len(records) == 100
assert test_stream.state["lastUpdated"] == int(test_stream._init_sync.timestamp() * 1000)
def test_engagements_stream_since_old_date(requests_mock, common_params, fake_properties_list):
"""
Connector should use 'All Engagements' API for old dates (more than 30 days)
"""
old_date = 1614038400000 # Tuesday, 23 February 2021 г., 0:00:00
responses = [
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": old_date}} for y in range(100)],
"hasMore": False,
"offset": 0,
"total": 100
},
"status_code": 200,
}
]
# Create test_stream instance with some state
test_stream = Engagements(**common_params)
test_stream.state = {"lastUpdated": old_date}
# Mocking Request
requests_mock.register_uri("GET", "/engagements/v1/engagements/paged?count=250", responses)
records, _ = read_incremental(test_stream, {})
# The stream should not attempt to get more than 10K records.
assert len(records) == 100
assert test_stream.state["lastUpdated"] == int(test_stream._init_sync.timestamp() * 1000)
def test_engagements_stream_since_recent_date(requests_mock, common_params, fake_properties_list):
"""
Connector should use 'Recent Engagements' API for recent dates (less than 30 days)
"""
recent_date = pendulum.now() - timedelta(days=10) # 10 days ago
recent_date = int(recent_date.timestamp() * 1000)
responses = [
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": recent_date}} for y in range(100)],
"hasMore": False,
"offset": 0,
"total": 100
},
"status_code": 200,
}
]
# Create test_stream instance with some state
test_stream = Engagements(**common_params)
test_stream.state = {"lastUpdated": recent_date}
# Mocking Request
requests_mock.register_uri("GET", f"/engagements/v1/engagements/recent/modified?count=100&since={recent_date}", responses)
records, _ = read_incremental(test_stream, {"lastUpdated": recent_date})
# The stream should not attempt to get more than 10K records.
assert len(records) == 100
assert test_stream.state["lastUpdated"] == int(test_stream._init_sync.timestamp() * 1000)
def test_engagements_stream_since_recent_date_more_than_10k(requests_mock, common_params, fake_properties_list):
"""
Connector should use 'Recent Engagements' API for recent dates (less than 30 days).
If response from 'Recent Engagements' API returns 10k records, it means that there more records,
so 'All Engagements' API should be used.
"""
recent_date = pendulum.now() - timedelta(days=10) # 10 days ago
recent_date = int(recent_date.timestamp() * 1000)
responses = [
{
"json": {
"results": [{"engagement": {"id": f"{y}", "lastUpdated": recent_date}} for y in range(100)],
"hasMore": False,
"offset": 0,
"total": 10001
},
"status_code": 200,
}
]
# Create test_stream instance with some state
test_stream = Engagements(**common_params)
test_stream.state = {"lastUpdated": recent_date}
# Mocking Request
requests_mock.register_uri("GET", f"/engagements/v1/engagements/recent/modified?count=100&since={recent_date}", responses)
requests_mock.register_uri("GET", "/engagements/v1/engagements/paged?count=250", responses)
records, _ = read_incremental(test_stream, {"lastUpdated": recent_date})
assert len(records) == 100
assert test_stream.state["lastUpdated"] == int(test_stream._init_sync.timestamp() * 1000)
def test_pagination_marketing_emails_stream(requests_mock, common_params):
"""
Test pagination for Marketing Emails stream
"""
requests_mock.register_uri(
"GET",
"/marketing-emails/v1/emails/with-statistics?limit=250",
[
{
"json": {
"objects": [{"id": f"{y}", "updated": 1641234593251} for y in range(250)],
"limit": 250,
"offset": 0,
"total": 600,
},
"status_code": 200,
},
{
"json": {
"objects": [{"id": f"{y}", "updated": 1641234593251} for y in range(250, 500)],
"limit": 250,
"offset": 250,
"total": 600,
},
"status_code": 200,
},
{
"json": {
"objects": [{"id": f"{y}", "updated": 1641234595251} for y in range(500, 600)],
"limit": 250,
"offset": 500,
"total": 600,
},
"status_code": 200,
},
],
)
test_stream = MarketingEmails(**common_params)
records = read_full_refresh(test_stream)
# The stream should handle pagination correctly and output 600 records.
assert len(records) == 600