forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_confluence.py
1377 lines (1224 loc) · 42.7 KB
/
test_confluence.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 Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
"""Tests the Confluence database source class methods"""
import ssl
from contextlib import asynccontextmanager
from copy import copy
from unittest import mock
from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
import pytest
from aiohttp import StreamReader
from freezegun import freeze_time
from connectors.access_control import DLS_QUERY
from connectors.protocol import Filter
from connectors.source import ConfigurableFieldValueError
from connectors.sources.confluence import (
CONFLUENCE_CLOUD,
CONFLUENCE_DATA_CENTER,
CONFLUENCE_SERVER,
ConfluenceClient,
ConfluenceDataSource,
)
from connectors.utils import ssl_context
from tests.commons import AsyncIterator
from tests.sources.support import create_source
ADVANCED_SNIPPET = "advanced_snippet"
HOST_URL = "http://127.0.0.1:9696"
EXCEPTION_MESSAGE = "Something went wrong"
CONTENT_QUERY = "limit=1&expand=children.attachment,history.lastUpdated,body.storage"
RESPONSE_SPACE = {
"results": [
{
"id": 4554779,
"name": "DEMO",
"_links": {
"webui": "/spaces/DM",
},
}
],
"start": 0,
"limit": 1,
"size": 1,
"_links": {},
}
SPACE = {
"id": 4554779,
"name": "DEMO",
"_links": {
"webui": "/spaces/DM",
},
"permissions": [
{
"id": 1,
"subjects": {
"group": {
"results": [
{
"type": "group",
"name": "group1",
"id": "group_id_1",
}
],
"size": 1,
},
},
"operation": {"operation": "read", "targetType": "space"},
}
],
}
RESPONSE_PAGE = {
"results": [
{
"id": 4779,
"title": "ES-scrum",
"type": "page",
"history": {"lastUpdated": {"when": "2023-01-24T04:07:19.672Z"}},
"children": {"attachment": {"size": 2}},
"body": {"storage": {"value": "This is a test page"}},
"space": {"name": "DEMO"},
"_links": {
"webui": "/spaces/~1234abc/pages/4779/ES-scrum",
},
}
],
"start": 0,
"limit": 1,
"size": 1,
"_links": {},
}
EXPECTED_PAGE = {
"_id": 4779,
"type": "page",
"_timestamp": "2023-01-24T04:07:19.672Z",
"title": "ES-scrum",
"body": "This is a test page",
"space": "DEMO",
"url": f"{HOST_URL}/spaces/~1234abc/pages/4779/ES-scrum",
}
EXPECTED_SPACE = {
"_id": 4554779,
"type": "Space",
"title": "DEMO",
"_timestamp": "2024-04-02T09:53:15.818621+00:00",
"url": "http://127.0.0.1:9696/spaces/DM",
}
RESPONSE_ATTACHMENT = {
"results": [
{
"id": "att3637249",
"title": "demo.py",
"type": "attachment",
"version": {"when": "2023-01-03T09:24:50.633Z"},
"extensions": {"fileSize": 230},
"_links": {
"download": "/download/attachments/1113/demo.py?version=1&modificationDate=1672737890633&cacheVersion=1&api=v2",
"webui": "/pages/viewpageattachments.action?pageId=1113&preview=demo.py",
},
}
],
"start": 0,
"limit": 1,
"size": 1,
"_links": {},
}
EXPECTED_ATTACHMENT = {
"_id": "att3637249",
"type": "attachment",
"_timestamp": "2023-01-03T09:24:50.633Z",
"title": "demo.py",
"size": 230,
"space": "DEMO",
"page": "ES-scrum",
"url": f"{HOST_URL}/pages/viewpageattachments.action?pageId=1113&preview=demo.py",
}
RESPONSE_CONTENT = "# This is the dummy file"
RESPONSE_SPACE_KEYS = {
"results": [
{
"id": 23456,
"key": "DM",
},
{
"id": 9876,
"key": "ES",
},
],
"start": 0,
"limit": 100,
"size": 2,
"_links": {},
}
EXPECTED_CONTENT = {
"_id": "att3637249",
"_timestamp": "2023-01-03T09:24:50.633Z",
"_attachment": "IyBUaGlzIGlzIHRoZSBkdW1teSBmaWxl",
}
EXPECTED_CONTENT_EXTRACTED = {
"_id": "att3637249",
"_timestamp": "2023-01-03T09:24:50.633Z",
"body": RESPONSE_CONTENT,
}
EXPECTED_BLOG = {
"_id": 4779,
"type": "blogpost",
"_timestamp": "2023-01-24T04:07:19.672Z",
"title": "demo-blog",
"body": "This is a test blog",
"space": "DEMO",
"url": f"{HOST_URL}/spaces/~1234abc/blogposts/4779/demo-blog",
}
EXPECTED_BLOG_ATTACHMENT = {
"_id": "att3637249",
"type": "attachment",
"_timestamp": "2023-01-03T09:24:50.633Z",
"title": "demo.py",
"size": 230,
"space": "DEMO",
"blog": "demo-blog",
"url": f"{HOST_URL}/pages/viewpageattachments.action?pageId=1113&preview=demo.py",
}
RESPONSE_SEARCH_RESULT = {
"results": [
{
"content": {
"id": "983046",
"type": "page",
"space": {"name": "Software Development"},
},
"title": "Product Details",
"excerpt": "Confluence Connector currently supports below objects for ingestion of data in ElasticSearch.\nBlogs\nAttachments\nPages\nSpaces",
"url": "/spaces/SD/pages/983046/Product+Details",
"lastModified": "2022-12-19T13:06:18.000Z",
"entityType": "content",
},
{
"content": {
"id": "att4587521",
"type": "attachment",
"extensions": {
"mediaType": "application/pdf",
"fileSize": 1119256,
},
"space": {"name": "Software Development"},
"container": {"type": "page", "title": "Product Details"},
"_links": {"download": "/download/attachments/196717/Potential.pdf"},
},
"title": "Potential.pdf",
"excerpt": "Evaluation Overview",
"url": "/pages/viewpageattachments.action?pageId=196717&preview=%2F196717%2F4587521%2FPotential.pdf",
"lastModified": "2023-01-24T03:34:38.000Z",
"entityType": "content",
},
{
"space": {
"id": 196612,
"key": "SD",
"type": "global",
},
"title": "Software Development",
"excerpt": "",
"url": "/spaces/SD",
"lastModified": "2022-12-13T09:49:01.000Z",
"entityType": "space",
},
]
}
EXPECTED_SEARCH_RESULT = [
{
"_id": "983046",
"title": "Product Details",
"_timestamp": "2022-12-19T13:06:18.000Z",
"body": "Confluence Connector currently supports below objects for ingestion of data in ElasticSearch.\nBlogs\nAttachments\nPages\nSpaces",
"type": "page",
"space": "Software Development",
"url": f"{HOST_URL}/spaces/SD/pages/983046/Product+Details",
},
{
"_id": "att4587521",
"title": "Potential.pdf",
"_timestamp": "2023-01-24T03:34:38.000Z",
"type": "attachment",
"url": f"{HOST_URL}/pages/viewpageattachments.action?pageId=196717&preview=%2F196717%2F4587521%2FPotential.pdf",
"space": "Software Development",
"size": 1119256,
"page": "Product Details",
},
{
"_id": 196612,
"title": "Software Development",
"_timestamp": "2022-12-13T09:49:01.000Z",
"body": "",
"type": "space",
"url": f"{HOST_URL}/spaces/SD",
},
]
SPACE_PERMISSION_RESPONSE = [
{
"id": 1,
"subjects": {
"group": {
"results": [
{
"type": "group",
"name": "group1",
"id": "group_id_1",
}
],
"size": 1,
},
},
"operation": {"operation": "read", "targetType": "space"},
},
]
PAGE_PERMISSION_RESPONSE = [
{
"id": 1,
"subjects": {
"group": {
"results": [
{
"type": "group",
"name": "group2",
"id": "group_id_2",
}
],
"size": 1,
},
},
"operation": {"operation": "read", "targetType": "page"},
},
]
BLOG_POST_PERMISSION_RESPONSE = [
{
"id": 1,
"subjects": {
"group": {
"results": [
{
"type": "group",
"name": "group2",
"id": "group_id_2",
}
],
"size": 1,
},
},
"operation": {"operation": "read", "targetType": "blogpost"},
},
]
PAGE_RESTRICTION_RESPONSE = {
"user": {
"results": [
{
"type": "known",
"accountId": "user_id_4",
"accountType": "atlassian",
"displayName": "user_4",
},
{
"type": "known",
"accountId": "user_id_5",
"accountType": "atlassian",
"displayName": "user_5",
},
],
"size": 2,
},
"group": {"results": [], "size": 0},
}
@asynccontextmanager
async def create_confluence_source(use_text_extraction_service=False):
async with create_source(
ConfluenceDataSource,
data_source=CONFLUENCE_SERVER,
username="admin",
password="changeme",
confluence_url=HOST_URL,
spaces="*",
ssl_enabled=False,
use_document_level_security=False,
use_text_extraction_service=use_text_extraction_service,
) as source:
yield source
class JSONAsyncMock(AsyncMock):
def __init__(self, json, *args, **kwargs):
super().__init__(*args, **kwargs)
self._json = json
async def json(self):
return self._json
class StreamReaderAsyncMock(AsyncMock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.content = StreamReader
@pytest.mark.asyncio
async def test_validate_configuration_with_invalid_concurrent_downloads():
"""Test validate configuration method of BaseDataSource class with invalid concurrent downloads"""
# Setup
async with create_confluence_source() as source:
source.configuration.get_field("concurrent_downloads").value = 100000
# Execute
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"configs",
[
(
# Confluence Server with blank dependent fields
{
"data_source": CONFLUENCE_SERVER,
"username": "",
"password": "",
"account_email": "[email protected]",
"api_token": "foo",
}
),
(
# Confluence Data Center with blank dependent fields
{
"data_source": CONFLUENCE_DATA_CENTER,
"data_center_username": "",
"data_center_password": "",
"account_email": "[email protected]",
"api_token": "foo",
}
),
(
# Confluence Cloud with blank dependent fields
{
"data_source": CONFLUENCE_CLOUD,
"username": "foo",
"password": "bar",
"account_email": "",
"api_token": "",
}
),
],
)
async def test_validate_configuration_with_invalid_dependency_fields_raises_error(
configs,
):
# Setup
async with create_confluence_source() as source:
for k, v in configs.items():
source.configuration.get_field(k).value = v
# Execute
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"configs",
[
(
# Confluence Server with blank non-dependent fields
{
"data_source": CONFLUENCE_SERVER,
"username": "foo",
"password": "bar",
"account_email": "",
"api_token": "",
}
),
(
# Confluence Data Center with blank dependent fields
{
"data_source": CONFLUENCE_DATA_CENTER,
"data_center_username": "foo",
"data_center_password": "bar",
"account_email": "",
"api_token": "",
}
),
(
# Confluence Cloud with blank non-dependent fields
{
"data_source": CONFLUENCE_CLOUD,
"username": "",
"password": "",
"account_email": "[email protected]",
"api_token": "foobar",
}
),
(
# SSL certificate not enabled (empty ssl_ca okay)
{
"username": "foo",
"password": "bar",
"ssl_enabled": False,
"ssl_ca": "",
}
),
],
)
async def test_validate_config_with_valid_dependency_fields_does_not_raise_error(
configs,
):
async with create_confluence_source() as source:
source.confluence_client.ping = AsyncMock()
for k, v in configs.items():
source.configuration.get_field(k).value = v
await source.validate_config()
@pytest.mark.asyncio
@patch("aiohttp.ClientSession.get")
async def test_validate_config_when_ssl_enabled_and_ssl_ca_not_empty_does_not_raise_error(
mock_get,
):
with patch.object(ssl, "create_default_context", return_value=MockSSL()):
async with create_confluence_source() as source:
source.configuration.get_field("username").value = "foo"
source.configuration.get_field("password").value = "foo"
source.configuration.get_field("ssl_enabled").value = True
source.configuration.get_field(
"ssl_ca"
).value = (
"-----BEGIN CERTIFICATE----- Certificate -----END CERTIFICATE-----"
)
await source.validate_config()
@pytest.mark.asyncio
async def test_tweak_bulk_options():
"""Test tweak_bulk_options method of BaseDataSource class"""
# Setup
async with create_confluence_source() as source:
source.concurrent_downloads = 10
options = {"concurrent_downloads": 5}
# Execute
source.tweak_bulk_options(options)
assert options["concurrent_downloads"] == 10
@pytest.mark.asyncio
async def test_close_with_client_session():
"""Test close method for closing the existing session"""
# Setup
async with create_confluence_source() as source:
source.confluence_client._get_session()
# Execute
await source.close()
assert source.confluence_client.session is None
@pytest.mark.asyncio
async def test_close_without_client_session():
"""Test close method when the session does not exist"""
# Setup
async with create_confluence_source() as source:
# Execute
await source.close()
assert source.confluence_client.session is None
@pytest.mark.asyncio
async def test_remote_validation_when_space_keys_are_valid():
async with create_confluence_source() as source:
source.spaces = ["DM", "ES"]
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_SPACE_KEYS)
)
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
await source._remote_validation()
@pytest.mark.asyncio
async def test_remote_validation_when_space_keys_are_unavailable_then_raise_exception():
async with create_confluence_source() as source:
source.spaces = ["ES", "CS"]
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_SPACE_KEYS)
)
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
with pytest.raises(
ConfigurableFieldValueError,
match="Spaces 'CS' are not available. Available spaces are: 'DM, ES'",
):
await source._remote_validation()
class MockSSL:
"""This class contains methods which returns dummy ssl context"""
def load_verify_locations(self, cadata):
"""This method verify locations"""
pass
@pytest.mark.parametrize(
"field, data_source",
[
("confluence_url", "confluence_cloud"),
("account_email", "confluence_cloud"),
("api_token", "confluence_cloud"),
("username", "confluence_server"),
("password", "confluence_server"),
("data_center_username", "confluence_data_center"),
("data_center_password", "confluence_data_center"),
],
)
@pytest.mark.asyncio
async def test_validate_configuration_for_empty_fields(field, data_source):
async with create_confluence_source() as source:
source.confluence_client.configuration.get_field(
"data_source"
).value = data_source
source.confluence_client.configuration.get_field(field).value = ""
# Execute
with pytest.raises(Exception):
await source.validate_config()
@pytest.mark.asyncio
@patch("aiohttp.ClientSession.get")
async def test_ping_with_ssl(mock_get):
"""Test ping method of ConfluenceDataSource class with SSL"""
# Execute
mock_get.return_value.__aenter__.return_value.status = 200
async with create_confluence_source() as source:
source.confluence_client.ssl_enabled = True
source.confluence_client.certificate = (
"-----BEGIN CERTIFICATE----- Certificate -----END CERTIFICATE-----"
)
# Execute
with patch.object(ssl, "create_default_context", return_value=MockSSL()):
source.confluence_client.ssl_ctx = ssl_context(
certificate=source.confluence_client.certificate
)
await source.ping()
@pytest.mark.asyncio
@patch("aiohttp.ClientSession.get")
async def test_ping_for_failed_connection_exception(mock_get):
"""Tests the ping functionality when connection can not be established to Confluence."""
# Setup
async with create_confluence_source() as source:
# Execute
with patch.object(
ConfluenceClient, "api_call", side_effect=Exception("Something went wrong")
):
with pytest.raises(Exception):
await source.ping()
@pytest.mark.asyncio
async def test_validate_configuration_for_ssl_enabled():
"""This function tests _validate_configuration when certification is empty and ssl is enabled"""
# Setup
async with create_confluence_source() as source:
source.ssl_enabled = True
# Execute
with pytest.raises(Exception):
source._validate_configuration()
@freeze_time("2023-01-24T04:07:19")
@pytest.mark.asyncio
async def test_fetch_spaces():
# Setup
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_SPACE)
)
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
async for response in source.confluence_client.fetch_spaces():
assert response == RESPONSE_SPACE["results"][0]
@pytest.mark.asyncio
async def test_fetch_documents():
# Setup
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(return_value=JSONAsyncMock(RESPONSE_PAGE))
# Execute
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
async for response, _, _, _, _ in source.fetch_documents(api_query=""):
assert response == EXPECTED_PAGE
@pytest.mark.asyncio
async def test_fetch_attachments():
# Setup
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_ATTACHMENT)
)
# Execute
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
async for response, _ in source.fetch_attachments(
content_id=1113,
parent_name="ES-scrum",
parent_space="DEMO",
parent_type="page",
):
assert response == EXPECTED_ATTACHMENT
@pytest.mark.asyncio
async def test_search_by_query():
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_SEARCH_RESULT)
)
documents = []
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
async for response, _ in source.search_by_query(
query="type in ('space', 'page', 'attachment') AND space.key ='SD'"
):
documents.append(response)
assert documents == EXPECTED_SEARCH_RESULT
@pytest.mark.asyncio
async def test_search_by_query_for_datacenter():
async with create_confluence_source() as source:
async_response = AsyncMock()
source.confluence_client.data_source_type = "confluence_data_center"
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_SEARCH_RESULT)
)
documents = []
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
async for response, _ in source.search_by_query(
query="type in ('space', 'page', 'attachment') AND space.key ='SD'"
):
documents.append(response)
assert documents == EXPECTED_SEARCH_RESULT
@pytest.mark.asyncio
async def test_download_attachment():
# Setup
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(return_value=StreamReaderAsyncMock())
# Execute
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
with mock.patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes(RESPONSE_CONTENT, "utf-8")]),
):
response = await source.download_attachment(
url="download/attachments/1113/demo.py?version=1&modificationDate=1672737890633&cacheVersion=1&api=v2",
attachment=EXPECTED_ATTACHMENT,
doit=True,
)
assert response == EXPECTED_CONTENT
@pytest.mark.asyncio
async def test_download_attachment_with_upper_extension():
# Setup
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(return_value=StreamReaderAsyncMock())
# Execute
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
with mock.patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes(RESPONSE_CONTENT, "utf-8")]),
):
attachment = copy(EXPECTED_ATTACHMENT)
attachment["title"] = "batch.TXT"
response = await source.download_attachment(
url="download/attachments/1113/demo.py?version=1&modificationDate=1672737890633&cacheVersion=1&api=v2",
attachment=EXPECTED_ATTACHMENT,
doit=True,
)
assert response == EXPECTED_CONTENT
@pytest.mark.asyncio
async def test_download_attachment_when_filesize_is_large_then_download_skips():
"""Tests the download attachments method for file size greater than max limit."""
# Setup
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(return_value=StreamReaderAsyncMock())
# Execute
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
with mock.patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes(RESPONSE_CONTENT, "utf-8")]),
):
attachment = copy(EXPECTED_ATTACHMENT)
attachment["size"] = 23000000
response = await source.download_attachment(
url="download/attachments/1113/demo.py?version=1&modificationDate=1672737890633&cacheVersion=1&api=v2",
attachment=attachment,
doit=True,
)
assert response is None
@pytest.mark.asyncio
async def test_download_attachment_when_unsupported_filetype_used_then_fail_download_skips():
"""Tests the download attachments method for file type is not supported"""
# Setup
async with create_confluence_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(return_value=StreamReaderAsyncMock())
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
with mock.patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes(RESPONSE_CONTENT, "utf-8")]),
):
attachment = copy(EXPECTED_ATTACHMENT)
attachment["title"] = "batch.mysy"
response = await source.download_attachment(
url="download/attachments/1113/demo.py?version=1&modificationDate=1672737890633&cacheVersion=1&api=v2",
attachment=attachment,
doit=True,
)
assert response is None
@pytest.mark.asyncio
@patch(
"connectors.content_extraction.ContentExtraction._check_configured",
lambda *_: True,
)
async def test_download_attachment_with_text_extraction_enabled_adds_body():
with patch(
"connectors.content_extraction.ContentExtraction.extract_text",
return_value=RESPONSE_CONTENT,
), patch(
"connectors.content_extraction.ContentExtraction.get_extraction_config",
return_value={"host": "http://localhost:8090"},
):
async with create_confluence_source(use_text_extraction_service=True) as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(return_value=StreamReaderAsyncMock())
# Execute
with mock.patch("aiohttp.ClientSession.get", return_value=async_response):
with mock.patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes(RESPONSE_CONTENT, "utf-8")]),
):
response = await source.download_attachment(
url="download/attachments/1113/demo.py?version=1&modificationDate=1672737890633&cacheVersion=1&api=v2",
attachment=EXPECTED_ATTACHMENT,
doit=True,
)
assert response == EXPECTED_CONTENT_EXTRACTED
@pytest.mark.asyncio
@mock.patch.object(
ConfluenceClient,
"fetch_spaces",
return_value=AsyncIterator([copy(SPACE)]),
)
@mock.patch.object(
ConfluenceDataSource,
"fetch_documents",
side_effect=[
(AsyncIterator([[copy(EXPECTED_PAGE), 1, "space_key", [], {}]])),
(AsyncIterator([[copy(EXPECTED_BLOG), 1, "space_key", [], {}]])),
],
)
@mock.patch.object(
ConfluenceDataSource,
"fetch_attachments",
side_effect=[
(AsyncIterator([[copy(EXPECTED_ATTACHMENT), "download-url"]])),
(AsyncIterator([[copy(EXPECTED_BLOG_ATTACHMENT), "download-url"]])),
],
)
@mock.patch.object(
ConfluenceDataSource,
"download_attachment",
return_value=AsyncIterator([[copy(EXPECTED_CONTENT)]]),
)
@freeze_time("2024-04-02T09:53:15.818621+00:00")
async def test_get_docs(spaces_patch, pages_patch, attachment_patch, content_patch):
"""Tests the get_docs method"""
# Setup
async with create_confluence_source() as source:
expected_responses = [
EXPECTED_SPACE,
EXPECTED_PAGE,
EXPECTED_BLOG,
EXPECTED_ATTACHMENT,
EXPECTED_BLOG_ATTACHMENT,
]
# Execute
documents = []
source.confluence_client.data_source_type = "confluence_cloud"
async for item, _ in source.get_docs():
documents.append(item)
assert documents == expected_responses
@pytest.mark.asyncio
async def test_get_session():
"""Test that the instance of session returned is always the same for the datasource class."""
async with create_confluence_source() as source:
first_instance = source.confluence_client._get_session()
second_instance = source.confluence_client._get_session()
assert first_instance is second_instance
@pytest.mark.asyncio
async def test_get_access_control_dls_disabled():
async with create_confluence_source() as source:
source._dls_enabled = MagicMock(return_value=False)
acl = []
async for access_control in source.get_access_control():
acl.append(access_control)
assert len(acl) == 0
@pytest.mark.asyncio
@freeze_time("2023-01-24T04:07:19")
async def test_get_access_control_dls_enabled():
mock_users = [
{
# Indexable: The user is active and atlassian user.
"self": "url1",
"accountId": "607194d6bc3c3f006f4c35d6",
"accountType": "atlassian",
"displayName": "user1",
"locale": "en-US",
"emailAddress": "[email protected]",
"active": True,
},
{
# Non-Indexable: The user is no longer active.
"self": "url2",
"accountId": "607194d6bc3c3f006f4c35d7",
"accountType": "atlassian",
"displayName": "user2",
"locale": "en-US",
"emailAddress": "[email protected]",
"active": False,
},
{
# Non-Indexable: User account type is app; it must be atlassian.
"self": "url2",
"accountId": "607194d6bc3c3f006f4c35d7",
"accountType": "app",
"displayName": "user2",
"active": False,
},
{
# Non-Indexable: Personal information about user is missing.
"accountId": "607194d6bc3c3f006f4c35d7",
"accountType": "app",
"displayName": "user2",
"active": False,
},
]
mock_user1 = {
"self": "url1",
"accountId": "607194d6bc3c3f006f4c35d6",
"accountType": "atlassian",
"displayName": "user1",
"locale": "en-US",
"emailAddress": "[email protected]",
"active": True,
"groups": {
"size": 1,
"items": [
{
"name": "group1",