forked from subzeroid/instagrapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
1559 lines (1411 loc) · 60.8 KB
/
tests.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
import json
import os
import os.path
import random
import unittest
from datetime import datetime, timedelta
from json.decoder import JSONDecodeError
from pathlib import Path
from instagrapi import Client
from instagrapi.exceptions import DirectThreadNotFound
from instagrapi.story import StoryBuilder
from instagrapi.types import (
Account,
Collection,
Comment,
DirectMessage,
DirectThread,
Hashtag,
Highlight,
Location,
Media,
MediaOembed,
Share,
Story,
StoryLink,
StoryMedia,
StoryMention,
StorySticker,
User,
UserShort,
Usertag,
)
from instagrapi.utils import generate_jazoest
from instagrapi.zones import UTC
ACCOUNT_USERNAME = os.environ.get("IG_USERNAME", "instagrapi2")
ACCOUNT_PASSWORD = os.environ.get("IG_PASSWORD", "yoa5af6deeRujeec")
ACCOUNT_SESSIONID = os.environ.get("IG_SESSIONID", "")
REQUIRED_MEDIA_FIELDS = [
"pk", "taken_at", "id", "media_type", "code", "thumbnail_url", "location",
"user", "comment_count", "like_count", "caption_text", "usertags",
"video_url", "view_count", "video_duration", "title"
]
REQUIRED_STORY_FIELDS = [
'pk', 'id', 'code', 'taken_at', 'media_type', 'product_type',
'thumbnail_url', 'user', 'video_url', 'video_duration', 'mentions',
'links'
]
def cleanup(*paths):
for path in paths:
try:
os.remove(path)
os.remove(f'{path}.jpg')
except FileNotFoundError:
continue
def keep_path(user):
user.profile_pic_url = user.profile_pic_url.path
return user
class BaseClientMixin:
def __init__(self, *args, **kwargs):
if self.cl is None:
self.cl = Client()
self.set_proxy_if_exists()
super().__init__(*args, **kwargs)
def set_proxy_if_exists(self):
proxy = os.environ.get("IG_PROXY", "")
if proxy:
self.cl.set_proxy(proxy) # "socks5://127.0.0.1:30235"
return True
class FakeClientTestCase(BaseClientMixin, unittest.TestCase):
cl = None
def test_login(self):
try:
self.cl.login(ACCOUNT_USERNAME, "fakepassword")
except Exception as e:
self.assertEqual(
str(e), "The password you entered is incorrect. Please try again."
)
class ClientPrivateTestCase(BaseClientMixin, unittest.TestCase):
cl = None
def __init__(self, *args, **kwargs):
filename = f'/tmp/instagrapi_tests_client_settings_{ACCOUNT_USERNAME}.json'
self.cl = Client()
settings = {}
try:
st = os.stat(filename)
if datetime.fromtimestamp(st.st_mtime) > (datetime.now() - timedelta(seconds=3600)):
# use only fresh session (5 minutes)
settings = self.cl.load_settings(filename)
except FileNotFoundError:
pass
except JSONDecodeError as e:
print('JSONDecodeError when read stored client settings. Use empty settings')
print(str(e))
self.cl.set_settings(settings)
# self.cl.set_locale('ru_RU')
# self.cl.set_timezone_offset(10800)
self.cl.request_timeout = 1
self.set_proxy_if_exists()
if ACCOUNT_SESSIONID:
self.cl.login_by_sessionid(ACCOUNT_SESSIONID)
else:
self.cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD, relogin=True)
self.cl.dump_settings(filename)
super().__init__(*args, **kwargs)
class ClientPublicTestCase(BaseClientMixin, unittest.TestCase):
cl = None
def assertDict(self, obj, data):
for key, value in data.items():
if isinstance(value, str) and "..." in value:
self.assertTrue(value.replace("...", "") in obj[key])
elif isinstance(value, int):
self.assertTrue(obj[key] >= value)
else:
self.assertEqual(obj[key], value)
def test_media_info_gql(self):
media_pk = self.cl.media_pk_from_url("https://www.instagram.com/p/BVDOOolFFxg/")
m = self.cl.media_info_gql(media_pk)
self.assertIsInstance(m, Media)
media = {
'pk': 1532130876531694688,
'id': '1532130876531694688_1903424587',
'code': 'BVDOOolFFxg',
'taken_at': datetime(2017, 6, 7, 19, 37, 35, tzinfo=UTC()),
'media_type': 1,
'product_type': '',
'thumbnail_url': 'https://...',
'location': None,
'comment_count': 6,
'like_count': 79,
'has_liked': None,
'caption_text': '#creepy #creepyclothing',
'usertags': [],
'video_url': None,
'view_count': 0,
'video_duration': 0.0,
'title': '',
'resources': []
}
self.assertDict(m.dict(), media)
user = {
'pk': 1903424587,
'username': 'adw0rd',
'full_name': 'Mikhail Andreev',
'profile_pic_url': 'https://...',
}
self.assertDict(m.user.dict(), user)
class ClientTestCase(unittest.TestCase):
def test_jazoest(self):
phone_id = "57d64c41-a916-3fa5-bd7a-3796c1dab122"
self.assertTrue(generate_jazoest(phone_id), "22413")
def test_lg(self):
settings = {
"uuids": {
"phone_id": "57d64c41-a916-3fa5-bd7a-3796c1dab122",
"uuid": "8aa373c6-f316-44d7-b49e-d74563f4a8f3",
"client_session_id": "6c296d0a-3534-4dce-b5aa-a6a6ab017443",
"advertising_id": "8dc88b76-dfbc-44dc-abbc-31a6f1d54b04",
"android_device_id": "android-e021b636049dc0e9",
"request_id": "72d0f808-b5cd-40e2-910b-01ae7ae60a5b",
"tray_session_id": "bc44ef1d-c083-4ecd-b369-6f4a9e1a077c",
},
"mid": "YA1YMAACAAGtxxnZ1p4AYc8ufNMn",
"device_settings": {
"cpu": "h1",
"dpi": "640dpi",
"model": "h1",
"device": "RS988",
"resolution": "1440x2392",
"app_version": "117.0.0.28.123",
"manufacturer": "LGE/lge",
"version_code": "168361634",
"android_release": "6.0.1",
"android_version": 23
},
# "user_agent": "Instagram 117.0.0.28.123 Android (23/6.0.1; US; 168361634)"
"user_agent": "Instagram 117.1.0.29.119 Android (27/8.1.0; 480dpi; 1080x1776; motorola; Moto G (5S); montana; qcom; ru_RU; 253447809)",
"country": "RU",
"locale": "ru_RU",
"timezone_offset": 10800, # Moscow, GMT+3
}
cl = Client(settings)
cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)
self.assertIsInstance(cl.user_id, int)
self.assertEqual(cl.username, ACCOUNT_USERNAME)
def test_country_locale_timezone(self):
cl = Client()
# defaults:
self.assertEqual(cl.country, "US")
self.assertEqual(cl.locale, "en_US")
self.assertEqual(cl.timezone_offset, -14400)
settings = {
"uuids": {
"phone_id": "57d64c41-a916-3fa5-bd7a-3796c1dab122",
"uuid": "8aa373c6-f316-44d7-b49e-d74563f4a8f3",
"client_session_id": "6c296d0a-3534-4dce-b5aa-a6a6ab017443",
"advertising_id": "8dc88b76-dfbc-44dc-abbc-31a6f1d54b04",
"android_device_id": "android-e021b636049dc0e9",
"request_id": "72d0f808-b5cd-40e2-910b-01ae7ae60a5b",
"tray_session_id": "bc44ef1d-c083-4ecd-b369-6f4a9e1a077c",
},
"mid": "YA1YMAACAAGtxxnZ1p4AYc8ufNMn",
"device_settings": {
"app_version": "194.0.0.36.172",
"android_version": 26,
"android_release": "8.0.0",
"dpi": "480dpi",
"resolution": "1080x1920",
"manufacturer": "Xiaomi",
"device": "capricorn",
"model": "MI 5s",
"cpu": "qcom",
"version_code": "301484483"
},
"user_agent": "Instagram 194.0.0.36.172 Android (26/8.0.0; 480dpi; 1080x1920; Xiaomi; MI 5s; capricorn; qcom; en_US; 301484483)",
"country": "UK",
"locale": "en_US",
"timezone_offset": 3600, # London, GMT+1
}
device = {
"app_version": "165.1.0.20.119",
"android_version": 27,
"android_release": "8.1.0",
"dpi": "480dpi",
"resolution": "1080x1776",
"manufacturer": "motorola",
"device": "Moto G (5S)",
"model": "montana",
"cpu": "qcom",
"version_code": "253447809",
}
# change settings
cl.set_settings(settings)
def check(country, locale, timezone_offset):
self.assertDictEqual(cl.get_settings()["uuids"], settings["uuids"])
self.assertEqual(cl.country, country)
self.assertEqual(cl.locale, locale)
self.assertEqual(cl.timezone_offset, timezone_offset)
self.assertIn(cl.locale, cl.user_agent)
cl.set_country("AU") # change only country
check("AU", "en_US", 3600)
cl.set_locale("ru_RU") # locale change country
check("RU", "ru_RU", 3600)
cl.set_timezone_offset(10800) # change timezone_offset
check("RU", "ru_RU", 10800)
cl.set_user_agent("TEST") # change user-agent
self.assertEqual(cl.get_settings()["user_agent"], "TEST")
cl.set_device(device) # change device
self.assertDictEqual(cl.get_settings()["device_settings"], device)
cl.set_settings(settings) # load source settings
check("UK", "en_US", 3600)
self.assertEqual(cl.get_settings()["user_agent"], settings["user_agent"])
self.assertEqual(cl.get_settings()["device_settings"], settings["device_settings"])
class ClientDeviceTestCase(ClientPrivateTestCase):
def test_set_device(self):
fields = ['uuids', 'cookies', 'last_login', 'device_settings', 'user_agent']
for field in fields:
settings = self.cl.get_settings()
self.assertIn(field, settings)
device = {
"app_version": "165.1.0.20.119",
"android_version": 27,
"android_release": "8.1.0",
"dpi": "480dpi",
"resolution": "1080x1776",
"manufacturer": "motorola",
"device": "Moto G (5S)",
"model": "montana",
"cpu": "qcom",
"version_code": "253447809",
}
user_agent = "Instagram 165.1.0.29.119 Android (27/8.1.0; 480dpi; 1080x1776; motorola; Moto G (5S); montana; qcom; ru_RU; 253447809)"
self.cl.set_device(device)
self.cl.set_user_agent(user_agent)
settings = self.cl.get_settings()
self.assertDictEqual(device, settings['device_settings'])
self.assertEqual(user_agent, settings['user_agent'])
self.cl.user_info_by_username_v1('adw0rd')
request_user_agent = self.cl.last_response.request.headers.get('User-Agent')
self.assertEqual(user_agent, request_user_agent)
class ClientDeviceAgentTestCase(ClientPrivateTestCase):
def test_set_device_agent(self):
device = {
"app_version": "165.1.0.20.119",
"android_version": 27,
"android_release": "8.1.0",
"dpi": "480dpi",
"resolution": "1080x1776",
"manufacturer": "motorola",
"device": "Moto G (5S)",
"model": "montana",
"cpu": "qcom",
"version_code": "253447809",
}
user_agent = "Instagram 165.1.0.29.119 Android (27/8.1.0; 480dpi; 1080x1776; motorola; Moto G (5S); montana; qcom; ru_RU; 253447809)"
cl = Client()
cl.set_device(device)
cl.set_user_agent(user_agent)
cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)
self.assertDictEqual(device, cl.settings['device_settings'])
self.assertEqual(user_agent, cl.settings['user_agent'])
class ClientUserTestCase(ClientPrivateTestCase):
def test_username_from_user_id(self):
self.assertEqual(self.cl.username_from_user_id(1903424587), "adw0rd")
def test_user_medias(self):
user_id = self.cl.user_id_from_username("adw0rd")
medias = self.cl.user_medias(user_id)
self.assertGreater(len(medias), 100)
media = medias[0]
self.assertIsInstance(media, Media)
for field in REQUIRED_MEDIA_FIELDS:
self.assertTrue(hasattr(media, field))
def test_usertag_medias(self):
user_id = self.cl.user_id_from_username("adw0rd")
medias = self.cl.usertag_medias(user_id)
self.assertGreater(len(medias), 50)
media = medias[0]
self.assertIsInstance(media, Media)
for field in REQUIRED_MEDIA_FIELDS:
self.assertTrue(hasattr(media, field))
def test_user_followers(self):
user_id = self.cl.user_id_from_username("asphalt_kings_lb")
followers = self.cl.user_followers(self.cl.user_id)
self.assertIn(user_id, followers)
self.assertEqual(followers[user_id].username, "asphalt_kings_lb")
def test_user_followers_amount(self):
user_id = self.cl.user_id_from_username("adw0rd")
followers = self.cl.user_followers(user_id, amount=10)
self.assertTrue(len(followers) == 10)
self.assertIsInstance(list(followers.values())[0], UserShort)
def test_user_following(self):
user_id = self.cl.user_id_from_username("asphalt_kings_lb")
following = self.cl.user_following(self.cl.user_id)
self.assertIn(user_id, following)
self.assertEqual(following[user_id].username, "asphalt_kings_lb")
def test_user_following_amount(self):
user_id = self.cl.user_id_from_username("adw0rd")
following = self.cl.user_following(user_id, amount=10)
self.assertTrue(len(following) == 10)
self.assertIsInstance(list(following.values())[0], UserShort)
def test_user_follow_unfollow(self):
user_id = self.cl.user_id_from_username("bmxtravel")
self.cl.user_follow(user_id)
following = self.cl.user_following(self.cl.user_id)
self.assertIn(user_id, following)
self.cl.user_unfollow(user_id)
following = self.cl.user_following(self.cl.user_id)
self.assertNotIn(user_id, following)
def test_user_info(self):
user_id = self.cl.user_id_from_username("adw0rd")
user = self.cl.user_info(user_id)
self.assertIsInstance(user, User)
for key, value in {
"biography": "Engineer: Python, JavaScript, Erlang...",
"external_url": "https://adw0rd.com/",
"full_name": "Mikhail Andreev",
"pk": 1903424587,
"is_private": False,
"is_verified": False,
"profile_pic_url": "https://...",
"username": "adw0rd",
}.items():
if isinstance(value, str) and "..." in value:
self.assertTrue(value.replace("...", "") in getattr(user, key))
else:
self.assertEqual(value, getattr(user, key))
def test_user_info_by_username(self):
user = self.cl.user_info_by_username("adw0rd")
self.assertIsInstance(user, User)
self.assertEqual(user.pk, 1903424587)
self.assertEqual(user.full_name, "Mikhail Andreev")
self.assertFalse(user.is_private)
def test_age_restricted_user_info_by_username(self):
user = self.cl.user_info_by_username("philippe_jury_")
self.assertIsInstance(user, User)
self.assertEqual(user.pk, 5802433335)
self.assertEqual(user.full_name, "Philippe Jury")
self.assertFalse(user.is_private)
class ClientMediaTestCase(ClientPrivateTestCase):
def test_media_id(self):
self.assertEqual(
self.cl.media_id(2154602296692269830), "2154602296692269830_1903424587"
)
def test_media_pk(self):
self.assertEqual(
self.cl.media_pk("2154602296692269830_1903424587"), 2154602296692269830
)
def test_media_pk_from_code(self):
self.assertEqual(
self.cl.media_pk_from_code("B-fKL9qpeab"), 2278584739065882267
)
self.assertEqual(
self.cl.media_pk_from_code("B8jnuB2HAbyc0q001y3F9CHRSoqEljK_dgkJjo0"),
2243811726252050162,
)
def test_code_from_media_pk(self):
self.assertEqual(
self.cl.media_code_from_pk(2278584739065882267), "B-fKL9qpeab"
)
self.assertEqual(
self.cl.media_code_from_pk(2243811726252050162), "B8jnuB2HAby"
)
def test_media_pk_from_url(self):
self.assertEqual(
self.cl.media_pk_from_url("https://instagram.com/p/B1LbfVPlwIA/"),
2110901750722920960,
)
self.assertEqual(
self.cl.media_pk_from_url(
"https://www.instagram.com/p/B-fKL9qpeab/?igshid=1xm76zkq7o1im"
),
2278584739065882267,
)
def test_media_edit(self):
# Upload photo
media_pk = self.cl.media_pk_from_url("https://www.instagram.com/p/BVDOOolFFxg/")
path = self.cl.photo_download(media_pk)
self.assertIsInstance(path, Path)
try:
msg = "Test caption for photo"
media = self.cl.photo_upload(path, msg)
self.assertIsInstance(media, Media)
self.assertEqual(media.caption_text, msg)
# Change caption
msg = "New caption %s" % random.randint(1, 100)
self.cl.media_edit(media.pk, msg)
media = self.cl.media_info(media.pk)
self.assertIsInstance(media, Media)
self.assertEqual(media.caption_text, msg)
self.assertTrue(self.cl.media_delete(media.pk))
finally:
cleanup(path)
def test_media_edit_igtv(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/tv/B91gKCcpnTk/"
)
path = self.cl.igtv_download(media_pk)
self.assertIsInstance(path, Path)
try:
media = self.cl.igtv_upload(path, "Test title", "Test caption for IGTV")
self.assertIsInstance(media, Media)
# Enter title
title = "Title %s" % random.randint(1, 100)
msg = "New caption %s" % random.randint(1, 100)
self.cl.media_edit(media.pk, msg, title)
media = self.cl.media_info(media.pk)
self.assertIsInstance(media, Media)
self.assertEqual(media.title, title)
self.assertEqual(media.caption_text, msg)
# Split caption to title and caption
title = "Title %s" % random.randint(1, 100)
msg = "New caption %s" % random.randint(1, 100)
self.cl.media_edit(media.pk, f"{title}\n{msg}")
media = self.cl.media_info(media.pk)
self.assertIsInstance(media, Media)
self.assertEqual(media.title, title)
self.assertEqual(media.caption_text, msg)
# Empty title (duplicate one-line caption)
msg = "New caption %s" % random.randint(1, 100)
self.cl.media_edit(media.pk, msg, "")
media = self.cl.media_info(media.pk)
self.assertIsInstance(media, Media)
self.assertEqual(media.title, msg)
self.assertEqual(media.caption_text, msg)
self.assertTrue(self.cl.media_delete(media.id))
finally:
cleanup(path)
def test_media_user(self):
user = self.cl.media_user(2154602296692269830)
self.assertIsInstance(user, UserShort)
for key, val in {
"pk": 1903424587,
"username": "adw0rd",
"full_name": "Mikhail Andreev",
"is_private": False,
}.items():
self.assertEqual(getattr(user, key), val)
self.assertTrue(user.profile_pic_url.startswith("https://"))
def test_media_oembed(self):
media_oembed = self.cl.media_oembed(
"https://www.instagram.com/p/B3mr1-OlWMG/"
)
self.assertIsInstance(media_oembed, MediaOembed)
for key, val in {
"title": "В гостях у ДК @delai_krasivo_kaifui",
"author_name": "adw0rd",
"author_url": "https://www.instagram.com/adw0rd",
"author_id": 1903424587,
"media_id": "2154602296692269830_1903424587",
"width": 658,
"height": None,
"thumbnail_width": 640,
"thumbnail_height": 480,
"can_view": True,
}.items():
self.assertEqual(getattr(media_oembed, key), val)
self.assertTrue(media_oembed.thumbnail_url.startswith('http'))
def test_media_like_by_pk(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/ByU3LAslgWY/"
)
self.assertTrue(
self.cl.media_like(media_pk)
)
def test_media_like_and_unlike(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/B3mr1-OlWMG/"
)
self.assertTrue(self.cl.media_unlike(media_pk))
media = self.cl.media_info_v1(media_pk)
like_count = int(media.like_count)
# like
self.assertTrue(self.cl.media_like(media.id))
media = self.cl.media_info_v1(media_pk) # refresh after like
new_like_count = int(media.like_count)
self.assertEqual(new_like_count, like_count + 1)
# unlike
self.assertTrue(self.cl.media_unlike(media.id))
media = self.cl.media_info_v1(media_pk) # refresh after unlike
self.assertEqual(media.like_count, like_count)
def test_media_likers(self):
media = self.cl.user_medias(self.cl.user_id, amount=3)[-1]
self.assertIsInstance(media, Media)
likers = self.cl.media_likers(media.pk)
self.assertTrue(len(likers) > 0)
self.assertIsInstance(likers[0], UserShort)
class ClientCommentTestCase(ClientPrivateTestCase):
def test_media_comments_amount(self):
comments = self.cl.media_comments(2154602296692269830, amount=2)
self.assertTrue(len(comments) == 2)
comments = self.cl.media_comments(2154602296692269830, amount=0)
self.assertTrue(len(comments) > 2)
def test_media_comments(self):
comments = self.cl.media_comments(2154602296692269830)
self.assertTrue(len(comments) > 5)
comment = comments[0]
self.assertIsInstance(comment, Comment)
comment_fields = comment.__fields__.keys()
user_fields = comment.user.__fields__.keys()
for field in [
"pk",
"text",
"created_at_utc",
"content_type",
"status",
"user"
]:
self.assertIn(field, comment_fields)
for field in [
"pk",
"username",
"full_name",
"profile_pic_url",
]:
self.assertIn(field, user_fields)
def test_media_comment(self):
text = "Test text [%s]" % datetime.now().strftime("%s")
now = datetime.now(tz=UTC())
comment = self.cl.media_comment(2276404890775267248, text)
self.assertIsInstance(comment, Comment)
comment = comment.dict()
for key, val in {
"text": text,
"content_type": "comment",
"status": "Active"
}.items():
self.assertEqual(comment[key], val)
self.assertIn("pk", comment)
# The comment was written no more than 120 seconds ago
self.assertTrue(
abs((now - comment["created_at_utc"]).total_seconds()) <= 120
)
user_fields = comment['user'].keys()
for field in ["pk", "username", "full_name", "profile_pic_url"]:
self.assertIn(field, user_fields)
def test_comment_like_and_unlike(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/B3mr1-OlWMG/"
)
comment = self.cl.media_comments(media_pk)[0]
if comment.has_liked:
self.assertTrue(
self.cl.comment_unlike(comment.pk)
)
like_count = int(comment.like_count)
# like
self.assertTrue(self.cl.comment_like(comment.pk))
comment = self.cl.media_comments(media_pk)[0]
new_like_count = int(comment.like_count)
self.assertEqual(new_like_count, like_count + 1)
# unlike
self.assertTrue(self.cl.comment_unlike(comment.pk))
comment = self.cl.media_comments(media_pk)[0]
self.assertEqual(comment.like_count, like_count)
class ClientCompareExtractTestCase(ClientPrivateTestCase):
def assertLocation(self, v1, gql):
if not isinstance(v1, dict):
return self.assertEqual(v1, gql)
for key, val in v1.items():
if key == 'external_id':
continue # id may differ
gql_val = gql[key]
if isinstance(val, float):
val, gql_val = round(val, 4), round(gql_val, 4)
self.assertEqual(val, gql_val)
def assertMedia(self, v1, gql):
self.assertTrue(v1.pop("comment_count") <= gql.pop("comment_count"))
self.assertLocation(v1.pop('location'), gql.pop('location'))
v1.pop('has_liked')
gql.pop('has_liked')
self.assertDictEqual(v1, gql)
def media_info(self, media_pk):
media_v1 = self.cl.media_info_v1(media_pk)
self.assertIsInstance(media_v1, Media)
media_gql = self.cl.media_info_gql(media_pk)
self.assertIsInstance(media_gql, Media)
return media_v1.dict(), media_gql.dict()
def test_two_extract_media_photo(self):
media_v1, media_gql = self.media_info(
self.cl.media_pk_from_code('B3mr1-OlWMG')
)
self.assertTrue(media_v1.pop("thumbnail_url").startswith("https://"))
self.assertTrue(media_gql.pop("thumbnail_url").startswith("https://"))
self.assertMedia(media_v1, media_gql)
def test_two_extract_media_video(self):
media_v1, media_gql = self.media_info(
self.cl.media_pk_from_code('B3rFQPblq40')
)
self.assertTrue(media_v1.pop("video_url").startswith("https://"))
self.assertTrue(media_gql.pop("video_url").startswith("https://"))
self.assertTrue(media_v1.pop("thumbnail_url").startswith("https://"))
self.assertTrue(media_gql.pop("thumbnail_url").startswith("https://"))
self.assertMedia(media_v1, media_gql)
def test_two_extract_media_album(self):
media_v1, media_gql = self.media_info(
self.cl.media_pk_from_code('BjNLpA1AhXM')
)
for res in media_v1['resources']:
self.assertTrue(res.pop("thumbnail_url").startswith("https://"))
if res['media_type'] == 2:
self.assertTrue(res.pop("video_url").startswith("https://"))
for res in media_gql['resources']:
self.assertTrue(res.pop("thumbnail_url").startswith("https://"))
if res['media_type'] == 2:
self.assertTrue(res.pop("video_url").startswith("https://"))
self.assertMedia(media_v1, media_gql)
def test_two_extract_media_igtv(self):
media_v1, media_gql = self.media_info(
self.cl.media_pk_from_code('ByYn5ZNlHWf')
)
self.assertTrue(media_v1.pop("video_url").startswith("https://"))
self.assertTrue(media_gql.pop("video_url").startswith("https://"))
self.assertTrue(media_v1.pop("thumbnail_url").startswith("https://"))
self.assertTrue(media_gql.pop("thumbnail_url").startswith("https://"))
self.assertMedia(media_v1, media_gql)
def test_two_extract_user(self):
user_v1 = self.cl.user_info_v1(1903424587)
user_gql = self.cl.user_info_gql(1903424587)
self.assertIsInstance(user_v1, User)
self.assertIsInstance(user_gql, User)
user_v1, user_gql = user_v1.dict(), user_gql.dict()
self.assertTrue(user_v1.pop("profile_pic_url").startswith("https://"))
self.assertTrue(user_gql.pop("profile_pic_url").startswith("https://"))
self.assertDictEqual(user_v1, user_gql)
class ClientExtractTestCase(ClientPrivateTestCase):
def test_extract_media_photo(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/B3mr1-OlWMG/"
)
media = self.cl.media_info(media_pk)
self.assertIsInstance(media, Media)
self.assertTrue(len(media.resources) == 0)
self.assertTrue(media.comment_count > 5)
self.assertTrue(media.like_count > 80)
for key, val in {
"caption_text": "В гостях у ДК @delai_krasivo_kaifui",
"thumbnail_url": "https://",
"pk": 2154602296692269830,
"code": "B3mr1-OlWMG",
"media_type": 1,
"taken_at": datetime(2019, 10, 14, 15, 57, 10, tzinfo=UTC())
}.items():
if isinstance(val, str):
self.assertTrue(getattr(media, key).startswith(val))
else:
self.assertEqual(getattr(media, key), val)
for key, val in {"pk": 1903424587, "username": "adw0rd"}.items():
self.assertEqual(getattr(media.user, key), val)
def test_extract_media_video(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/BgRIGUQFltp/"
)
media = self.cl.media_info(media_pk)
self.assertIsInstance(media, Media)
self.assertTrue(len(media.resources) == 0)
self.assertTrue(media.view_count > 150)
self.assertTrue(media.comment_count > 1)
self.assertTrue(media.like_count > 40)
for key, val in {
"caption_text": "Веселья ради\n\n@milashensky #dowhill #skateboarding #foros #crimea",
"pk": 1734202949948037993,
"code": "BgRIGUQFltp",
"video_url": "https://",
"thumbnail_url": "https://",
"media_type": 2,
"taken_at": datetime(2018, 3, 13, 14, 59, 23, tzinfo=UTC())
}.items():
if isinstance(val, str):
self.assertTrue(getattr(media, key).startswith(val))
else:
self.assertEqual(getattr(media, key), val)
for key, val in {"pk": 1903424587, "username": "adw0rd"}.items():
self.assertEqual(getattr(media.user, key), val)
def test_extract_media_album(self):
media_pk = self.cl.media_pk_from_url('https://www.instagram.com/p/BjNLpA1AhXM/')
media = self.cl.media_info(media_pk)
self.assertIsInstance(media, Media)
self.assertTrue(len(media.resources) == 3)
video_resource = media.resources[0]
photo_resource = media.resources.pop()
self.assertTrue(media.view_count == 0)
self.assertTrue(media.comment_count == 0)
self.assertTrue(media.like_count > 40)
for key, val in {
"caption_text": "@mind__flowers в Форосе под дождём, 24 мая 2018 #downhill "
"#skateboarding #downhillskateboarding #crimea #foros #rememberwheels",
"pk": 1787135824035452364,
"code": "BjNLpA1AhXM",
"media_type": 8,
"taken_at": datetime(2018, 5, 25, 15, 46, 53, tzinfo=UTC()),
"product_type": "",
}.items():
self.assertEqual(getattr(media, key), val)
for key, val in {"pk": 1903424587, "username": "adw0rd"}.items():
self.assertEqual(getattr(media.user, key), val)
for key, val in {
"video_url": "https://",
"thumbnail_url": "https://",
"media_type": 2,
"pk": 1787135361353462176,
}.items():
if isinstance(val, str):
self.assertTrue(getattr(video_resource, key).startswith(val))
else:
self.assertEqual(getattr(video_resource, key), val)
for key, val in {
"video_url": None,
"thumbnail_url": "https://",
"media_type": 1,
"pk": 1787133803186894424,
}.items():
if isinstance(val, str):
self.assertTrue(getattr(photo_resource, key).startswith(val))
else:
self.assertEqual(getattr(photo_resource, key), val)
def test_extract_media_igtv(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/tv/ByYn5ZNlHWf/"
)
media = self.cl.media_info(media_pk)
self.assertIsInstance(media, Media)
self.assertTrue(len(media.resources) == 0)
self.assertTrue(media.view_count > 200)
self.assertTrue(media.comment_count > 10)
self.assertTrue(media.like_count > 50)
for key, val in {
"title": "zr trip, crimea, feb 2017. Edit by @milashensky",
"caption_text": "Нашёл на диске неопубликованное в инсте произведение @milashensky",
"pk": 2060572297417487775,
"video_url": "https://",
"thumbnail_url": "https://",
"code": "ByYn5ZNlHWf",
"media_type": 2,
"taken_at": datetime(2019, 6, 6, 22, 22, 6, tzinfo=UTC()),
"product_type": "igtv",
}.items():
if isinstance(val, str):
self.assertTrue(getattr(media, key).startswith(val))
else:
self.assertEqual(getattr(media, key), val)
for key, val in {"pk": 1903424587, "username": "adw0rd"}.items():
self.assertEqual(getattr(media.user, key), val)
class ClienUploadTestCase(ClientPrivateTestCase):
def get_location(self):
location = self.cl.location_search(lat=59.939095, lng=30.315868)[0]
self.assertIsInstance(location, Location)
return location
def assertLocation(self, location):
# Instagram sometimes changes location by GEO coordinates:
locations = [
dict(
pk=213597007,
name='Palace Square',
lat=59.939166666667,
lng=30.315833333333
),
dict(
pk=107617247320879,
name='Russia, Saint-Petersburg',
address='Russia, Saint-Petersburg',
lat=59.93318,
lng=30.30605,
external_id=107617247320879,
external_id_source='facebook_places'
)
]
for data in locations:
if data['pk'] == location.pk:
break
for key, val in data.items():
itm = getattr(location, key)
if isinstance(val, float):
val = round(val, 2)
itm = round(itm, 2)
self.assertEqual(itm, val)
def test_photo_upload_without_location(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/BVDOOolFFxg/"
)
path = self.cl.photo_download(media_pk)
self.assertIsInstance(path, Path)
try:
media = self.cl.photo_upload(path, "Test caption for photo")
self.assertIsInstance(media, Media)
self.assertEqual(media.caption_text, "Test caption for photo")
self.assertFalse(media.location)
finally:
cleanup(path)
self.assertTrue(self.cl.media_delete(media.id))
def test_photo_upload(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/BVDOOolFFxg/"
)
path = self.cl.photo_download(media_pk)
self.assertIsInstance(path, Path)
try:
media = self.cl.photo_upload(
path, "Test caption for photo",
location=self.get_location()
)
self.assertIsInstance(media, Media)
self.assertEqual(media.caption_text, "Test caption for photo")
self.assertLocation(media.location)
finally:
cleanup(path)
self.assertTrue(self.cl.media_delete(media.id))
def test_video_upload(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/p/Bk2tOgogq9V/"
)
path = self.cl.video_download(media_pk)
self.assertIsInstance(path, Path)
try:
media = self.cl.video_upload(
path, "Test caption for video",
location=self.get_location()
)
self.assertIsInstance(media, Media)
self.assertEqual(media.caption_text, "Test caption for video")
self.assertLocation(media.location)
finally:
cleanup(path)
self.assertTrue(self.cl.media_delete(media.id))
def test_album_upload(self):
media_pk = self.cl.media_pk_from_url("https://www.instagram.com/p/BjNLpA1AhXM/")
paths = self.cl.album_download(media_pk)
[self.assertIsInstance(path, Path) for path in paths]
try:
adw0rd = self.cl.user_info_by_username('adw0rd')
usertag = Usertag(user=adw0rd, x=0.5, y=0.5)
location = self.get_location()
media = self.cl.album_upload(
paths, "Test caption for album",
usertags=[usertag],
location=location
)
self.assertIsInstance(media, Media)
self.assertEqual(media.caption_text, "Test caption for album")
self.assertEqual(len(media.resources), 3)
self.assertLocation(media.location)
keep_path(media.usertags[0].user)
keep_path(usertag.user)
self.assertEqual(media.usertags, [usertag])
finally:
cleanup(*paths)
self.assertTrue(self.cl.media_delete(media.id))
def test_igtv_upload(self):
media_pk = self.cl.media_pk_from_url(
"https://www.instagram.com/tv/B91gKCcpnTk/"
)
path = self.cl.igtv_download(media_pk)
self.assertIsInstance(path, Path)
try:
title = "6/6: The Transceiver Failure"
caption_text = "Test caption for IGTV"
media = self.cl.igtv_upload(
path, title, caption_text,
location=self.get_location()
)
self.assertIsInstance(media, Media)
self.assertEqual(media.title, title)
self.assertEqual(media.caption_text, caption_text)
self.assertLocation(media.location)
finally:
cleanup(path)
self.assertTrue(self.cl.media_delete(media.id))
def test_clip_upload(self):
# media_type: 2 (video, not IGTV)
# product_type: clips
media_pk = self.cl.media_pk_from_url("https://www.instagram.com/p/CEjXskWJ1on/")
path = self.cl.clip_download(media_pk)
self.assertIsInstance(path, Path)