-
Notifications
You must be signed in to change notification settings - Fork 200
/
test_api.py
3037 lines (2498 loc) · 121 KB
/
test_api.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) 2019 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to the Shotgun Pipeline Toolkit Source Code License. All rights
# not expressly granted therein are reserved by Shotgun Software Inc.
"""Test calling the Shotgun API functions.
Includes short run tests, like simple crud and single finds. See
test_api_long for other tests.
"""
from __future__ import print_function
import datetime
import sys
import os
from . import mock
from .mock import patch, MagicMock
import ssl
import time
import types
import uuid
import unittest
from shotgun_api3.lib.six.moves import range, urllib
import warnings
import glob
import shotgun_api3
from shotgun_api3.lib.httplib2 import Http
from shotgun_api3.lib import six
# To mock the correct exception when testion on Python 2 and 3, use the
# ShotgunSSLError variable from sgsix that contains the appropriate exception
# class for the current Python version.
from shotgun_api3.lib.sgsix import ShotgunSSLError
from . import base
class TestShotgunApi(base.LiveTestBase):
def setUp(self):
super(TestShotgunApi, self).setUp()
# give note unicode content
self.sg.update('Note', self.note['id'], {'content': u'La Pe\xf1a'})
def test_info(self):
"""Called info"""
# TODO do more to check results
self.sg.info()
def test_server_dates(self):
"""Pass datetimes to the server"""
# TODO check results
t = {'project': self.project,
'start_date': datetime.date.today()}
self.sg.create('Task', t, ['content', 'sg_status_list'])
def test_batch(self):
"""Batched create, update, delete"""
requests = [
{
"request_type": "create",
"entity_type": "Shot",
"data": {
"code": "New Shot 5",
"project": self.project
}
},
{
"request_type": "update",
"entity_type": "Shot",
"entity_id": self.shot['id'],
"data": {
"code": "Changed 1"
}
}
]
new_shot, updated_shot = self.sg.batch(requests)
self.assertEqual(self.shot['id'], updated_shot["id"])
self.assertTrue(new_shot.get("id"))
new_shot_id = new_shot["id"]
requests = [
{
"request_type": "delete",
"entity_type": "Shot",
"entity_id": new_shot_id
},
{
"request_type": "update",
"entity_type": "Shot",
"entity_id": self.shot['id'],
"data": {"code": self.shot['code']}
}
]
result = self.sg.batch(requests)[0]
self.assertEqual(True, result)
def test_empty_batch(self):
"""Empty list sent to .batch()"""
result = self.sg.batch([])
self.assertEqual([], result)
def test_create_update_delete(self):
"""Called create, update, delete, revive"""
data = {
'project': self.project,
'code': 'JohnnyApple_Design01_FaceFinal',
'description': 'fixed rig per director final notes',
'sg_status_list': 'rev',
'entity': self.asset,
'user': self.human_user
}
version = self.sg.create("Version", data, return_fields=["id"])
self.assertTrue(isinstance(version, dict))
self.assertTrue("id" in version)
# TODO check results more thoroughly
# TODO: test returned fields are requested fields
data = data = {
"description": "updated test"
}
version = self.sg.update("Version", version["id"], data)
self.assertTrue(isinstance(version, dict))
self.assertTrue("id" in version)
rv = self.sg.delete("Version", version["id"])
self.assertEqual(True, rv)
rv = self.sg.delete("Version", version["id"])
self.assertEqual(False, rv)
rv = self.sg.revive("Version", version["id"])
self.assertEqual(True, rv)
rv = self.sg.revive("Version", version["id"])
self.assertEqual(False, rv)
def test_last_accessed(self):
page = self.sg.find('Page', [], fields=['last_accessed'], limit=1)
self.assertEqual("Page", page[0]['type'])
self.assertEqual(datetime.datetime, type(page[0]['last_accessed']))
def test_get_session_token(self):
"""Got session UUID"""
# TODO test results
rv = self.sg.get_session_token()
self.assertTrue(rv)
def test_upload_download(self):
"""Upload and download an attachment tests"""
# upload / download only works against a live server because it does
# not use the standard http interface
if 'localhost' in self.server_url:
print("upload / down tests skipped for localhost")
return
this_dir, _ = os.path.split(__file__)
path = os.path.abspath(os.path.expanduser(
os.path.join(this_dir, "sg_logo.jpg")))
size = os.stat(path).st_size
attach_id = self.sg.upload("Version",
self.version['id'], path, 'sg_uploaded_movie',
tag_list="monkeys, everywhere, send, help")
# test download with attachment_id
attach_file = self.sg.download_attachment(attach_id)
self.assertTrue(attach_file is not None)
self.assertEqual(size, len(attach_file))
orig_file = open(path, "rb").read()
self.assertEqual(orig_file, attach_file)
# test download with attachment_id as keyword
attach_file = self.sg.download_attachment(attachment_id=attach_id)
self.assertTrue(attach_file is not None)
self.assertEqual(size, len(attach_file))
orig_file = open(path, "rb").read()
self.assertEqual(orig_file, attach_file)
# test download with attachment_id (write to disk)
file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sg_logo_download.jpg")
result = self.sg.download_attachment(attach_id, file_path=file_path)
self.assertEqual(result, file_path)
# On windows read may not read to end of file unless opened 'rb'
fp = open(file_path, 'rb')
attach_file = fp.read()
fp.close()
self.assertEqual(size, len(attach_file))
self.assertEqual(orig_file, attach_file)
# test download with attachment hash
version = self.sg.find_one('Version', [['id', 'is', self.version['id']]],
['sg_uploaded_movie'])
# Look for the attachment we just uploaded, the attachments are not returned from latest
# to earliest.
attachment = [v for k, v in version["sg_uploaded_movie"].items() if (k, v) == ("id", attach_id)]
self.assertEqual(len(attachment), 1)
attachment = attachment[0]
attach_file = self.sg.download_attachment(attachment)
self.assertTrue(attach_file is not None)
self.assertEqual(size, len(attach_file))
self.assertEqual(orig_file, attach_file)
# test download with attachment hash (write to disk)
result = self.sg.download_attachment(attachment,
file_path=file_path)
self.assertEqual(result, file_path)
fp = open(file_path, 'rb')
attach_file = fp.read()
fp.close()
self.assertTrue(attach_file is not None)
self.assertEqual(size, len(attach_file))
self.assertEqual(orig_file, attach_file)
# test invalid requests
INVALID_S3_URL = "https://sg-media-usor-01.s3.amazonaws.com/ada3de3ee3873875e1dd44f2eb0882c75ae36a4a/cd31346421dbeef781e0e480f259a3d36652d7f2/IMG_0465.MOV?AWSAccessKeyId=AKIAIQGOBSVN3FSQ5QFA&Expires=1371789959&Signature=SLbzv7DuVlZ8XAoOSQQAiGpF3u8%3D" # noqa
self.assertRaises(shotgun_api3.ShotgunFileDownloadError,
self.sg.download_attachment,
{"url": INVALID_S3_URL})
INVALID_ATTACHMENT_ID = 99999999
self.assertRaises(shotgun_api3.ShotgunFileDownloadError,
self.sg.download_attachment,
INVALID_ATTACHMENT_ID)
self.assertRaises(TypeError, self.sg.download_attachment,
"/path/to/some/file.jpg")
self.assertRaises(ValueError, self.sg.download_attachment,
{"id": 123, "type": "Shot"})
self.assertRaises(TypeError, self.sg.download_attachment)
# test upload of non-ascii, unicode path
u_path = os.path.abspath(
os.path.expanduser(
glob.glob(os.path.join(six.text_type(this_dir), "Noëlご.jpg"))[0]
)
)
# If this is a problem, it'll raise with a UnicodeEncodeError. We
# don't need to check the results of the upload itself -- we're
# only checking that the non-ascii string encoding doesn't trip
# us up the way it used to.
self.sg.upload(
"Version",
self.version['id'],
u_path,
'sg_uploaded_movie',
tag_list="monkeys, everywhere, send, help"
)
# Also make sure that we can pass in a utf-8 encoded string path
# with non-ascii characters and have it work properly. This is
# primarily a concern on Windows, as it doesn't handle that
# situation as well as OS X and Linux.
self.sg.upload(
"Version",
self.version['id'],
u_path.encode("utf-8"),
'sg_uploaded_movie',
tag_list="monkeys, everywhere, send, help"
)
if six.PY2:
# In Python2, make sure that non-utf-8 encoded paths raise when they
# can't be converted to utf-8. For Python3, we'll skip these tests
# since string encoding is handled differently.
# We need to touch the file we're going to test with first. We can't
# bundle a file with this filename in the repo due to some pip install
# problems on Windows. Note that the path below is utf-8 encoding of
# what we'll eventually encode as shift-jis.
file_path_s = os.path.join(this_dir, "./\xe3\x81\x94.shift-jis")
file_path_u = file_path_s.decode("utf-8")
with open(file_path_u if sys.platform.startswith("win") else file_path_s, "w") as fh:
fh.write("This is just a test file with some random data in it.")
self.assertRaises(
shotgun_api3.ShotgunError,
self.sg.upload,
"Version",
self.version['id'],
file_path_u.encode("shift-jis"),
'sg_uploaded_movie',
tag_list="monkeys, everywhere, send, help"
)
# But it should work in all cases if a unicode string is used.
self.sg.upload(
"Version",
self.version['id'],
file_path_u,
'sg_uploaded_movie',
tag_list="monkeys, everywhere, send, help"
)
# cleanup
os.remove(file_path_u)
# cleanup
os.remove(file_path)
@patch('shotgun_api3.Shotgun._send_form')
def test_upload_to_sg(self, mock_send_form):
"""
Upload an attachment tests for _upload_to_sg()
"""
self.sg.server_info["s3_direct_uploads_enabled"] = False
mock_send_form.method.assert_called_once()
mock_send_form.return_value = "1\n:123\nasd"
this_dir, _ = os.path.split(__file__)
u_path = os.path.abspath(
os.path.expanduser(
glob.glob(os.path.join(six.text_type(this_dir), "Noëlご.jpg"))[0]
)
)
upload_id = self.sg.upload(
"Version",
self.version['id'],
u_path,
'attachments',
tag_list="monkeys, everywhere, send, help"
)
mock_send_form_args, _ = mock_send_form.call_args
display_name_to_send = mock_send_form_args[1].get("display_name", "")
self.assertTrue(isinstance(upload_id, int))
self.assertFalse(
display_name_to_send.startswith("b'") and
display_name_to_send.endswith("'")
)
upload_id = self.sg.upload(
"Version",
self.version['id'],
u_path,
'filmstrip_image',
tag_list="monkeys, everywhere, send, help",
)
self.assertTrue(isinstance(upload_id, int))
mock_send_form_args, _ = mock_send_form.call_args
display_name_to_send = mock_send_form_args[1].get("display_name", "")
self.assertTrue(isinstance(upload_id, int))
self.assertFalse(
display_name_to_send.startswith("b'") and
display_name_to_send.endswith("'")
)
mock_send_form.method.assert_called_once()
mock_send_form.return_value = "2\nIt can't be upload"
self.assertRaises(
shotgun_api3.ShotgunError,
self.sg.upload,
"Version",
self.version['id'],
u_path,
'attachments',
tag_list="monkeys, everywhere, send, help"
)
self.sg.server_info["s3_direct_uploads_enabled"] = True
def test_upload_thumbnail_in_create(self):
"""Upload a thumbnail via the create method"""
this_dir, _ = os.path.split(__file__)
path = os.path.abspath(os.path.expanduser(
os.path.join(this_dir, "sg_logo.jpg")))
# test thumbnail upload
data = {'image': path, 'code': 'Test Version',
'project': self.project}
new_version = self.sg.create("Version", data, return_fields=['image'])
new_version = self.find_one_await_thumbnail(
"Version",
[["id", "is", new_version["id"]]],
fields=["image", "project", "type", "id"],
)
self.assertTrue(new_version is not None)
self.assertTrue(isinstance(new_version, dict))
self.assertTrue(isinstance(new_version.get('id'), int))
self.assertEqual(new_version.get('type'), 'Version')
self.assertEqual(new_version.get('project'), self.project)
self.assertTrue(new_version.get('image') is not None)
h = Http(".cache")
thumb_resp, content = h.request(new_version.get('image'), "GET")
self.assertIn(thumb_resp['status'], ['200', '304'])
self.assertIn(thumb_resp['content-type'], ['image/jpeg', 'image/png'])
self.sg.delete("Version", new_version['id'])
# test filmstrip image upload
data = {'filmstrip_image': path, 'code': 'Test Version',
'project': self.project}
new_version = self.sg.create("Version", data, return_fields=['filmstrip_image'])
self.assertTrue(new_version is not None)
self.assertTrue(isinstance(new_version, dict))
self.assertTrue(isinstance(new_version.get('id'), int))
self.assertEqual(new_version.get('type'), 'Version')
self.assertEqual(new_version.get('project'), self.project)
self.assertTrue(new_version.get('filmstrip_image') is not None)
url = new_version.get('filmstrip_image')
data = self.sg.download_attachment({'url': url})
self.assertTrue(isinstance(data, six.binary_type))
self.sg.delete("Version", new_version['id'])
# end test_upload_thumbnail_in_create
def test_upload_thumbnail_for_version(self):
"""simple upload thumbnail for version test."""
this_dir, _ = os.path.split(__file__)
path = os.path.abspath(os.path.expanduser(
os.path.join(this_dir, "sg_logo.jpg")))
# upload thumbnail
thumb_id = self.sg.upload_thumbnail("Version", self.version['id'], path)
self.assertTrue(isinstance(thumb_id, int))
# check result on version
version_with_thumbnail = self.sg.find_one('Version', [['id', 'is', self.version['id']]])
version_with_thumbnail = self.find_one_await_thumbnail(
"Version", [["id", "is", self.version["id"]]]
)
self.assertEqual(version_with_thumbnail.get('type'), 'Version')
self.assertEqual(version_with_thumbnail.get('id'), self.version['id'])
h = Http(".cache")
thumb_resp, content = h.request(version_with_thumbnail.get('image'), "GET")
self.assertIn(thumb_resp['status'], ['200', '304'])
self.assertIn(thumb_resp['content-type'], ['image/jpeg', 'image/png'])
# clear thumbnail
response_clear_thumbnail = self.sg.update("Version", self.version['id'], {'image': None})
expected_clear_thumbnail = {'id': self.version['id'], 'image': None, 'type': 'Version'}
self.assertEqual(expected_clear_thumbnail, response_clear_thumbnail)
def test_upload_thumbnail_for_task(self):
"""simple upload thumbnail for task test."""
this_dir, _ = os.path.split(__file__)
path = os.path.abspath(os.path.expanduser(
os.path.join(this_dir, "sg_logo.jpg")))
# upload thumbnail
thumb_id = self.sg.upload_thumbnail("Task", self.task['id'], path)
self.assertTrue(isinstance(thumb_id, int))
# check result on version
task_with_thumbnail = self.sg.find_one('Task', [['id', 'is', self.task['id']]])
task_with_thumbnail = self.find_one_await_thumbnail(
"Task", [["id", "is", self.task["id"]]]
)
self.assertEqual(task_with_thumbnail.get('type'), 'Task')
self.assertEqual(task_with_thumbnail.get('id'), self.task['id'])
h = Http(".cache")
thumb_resp, content = h.request(task_with_thumbnail.get('image'), "GET")
self.assertIn(thumb_resp['status'], ['200', '304'])
self.assertIn(thumb_resp['content-type'], ['image/jpeg', 'image/png'])
# clear thumbnail
response_clear_thumbnail = self.sg.update("Version", self.version['id'], {'image': None})
expected_clear_thumbnail = {'id': self.version['id'], 'image': None, 'type': 'Version'}
self.assertEqual(expected_clear_thumbnail, response_clear_thumbnail)
def test_upload_thumbnail_with_upload_function(self):
"""Upload thumbnail via upload function test"""
path = os.path.abspath(os.path.expanduser(os.path.join(os.path.dirname(__file__), "sg_logo.jpg")))
# upload thumbnail
thumb_id = self.sg.upload("Task", self.task['id'], path, 'image')
self.assertTrue(isinstance(thumb_id, int))
# upload filmstrip thumbnail
f_thumb_id = self.sg.upload("Task", self.task['id'], path, 'filmstrip_image')
self.assertTrue(isinstance(f_thumb_id, int))
def test_requires_direct_s3_upload(self):
"""Test _requires_direct_s3_upload"""
upload_types = self.sg.server_info.get("s3_enabled_upload_types")
direct_uploads_enabled = self.sg.server_info.get("s3_direct_uploads_enabled")
self.sg.server_info["s3_enabled_upload_types"] = None
self.sg.server_info["s3_direct_uploads_enabled"] = None
# Test s3_enabled_upload_types and s3_direct_uploads_enabled not set
self.assertFalse(self.sg._requires_direct_s3_upload("Version", "sg_uploaded_movie"))
self.sg.server_info["s3_enabled_upload_types"] = {
"Version": ["sg_uploaded_movie"]
}
# Test direct_uploads_enabled not set
self.assertFalse(self.sg._requires_direct_s3_upload("Version", "sg_uploaded_movie"))
self.sg.server_info["s3_direct_uploads_enabled"] = True
# Test regular path
self.assertTrue(self.sg._requires_direct_s3_upload("Version", "sg_uploaded_movie"))
self.assertFalse(self.sg._requires_direct_s3_upload("Version", "abc"))
self.assertFalse(self.sg._requires_direct_s3_upload("Abc", "abc"))
# Test star field wildcard and arrays of fields
self.sg.server_info["s3_enabled_upload_types"] = {
"Version": ["sg_uploaded_movie", "test", "other"],
"Test": ["*"],
"Asset": "*"
}
self.assertTrue(self.sg._requires_direct_s3_upload("Version", "sg_uploaded_movie"))
self.assertTrue(self.sg._requires_direct_s3_upload("Version", "test"))
self.assertTrue(self.sg._requires_direct_s3_upload("Version", "other"))
self.assertTrue(self.sg._requires_direct_s3_upload("Test", "abc"))
self.assertTrue(self.sg._requires_direct_s3_upload("Asset", "test"))
# Test default allowed upload type
self.sg.server_info["s3_enabled_upload_types"] = None
self.assertTrue(self.sg._requires_direct_s3_upload("Version", "sg_uploaded_movie"))
self.assertFalse(self.sg._requires_direct_s3_upload("Version", "test"))
# Test star entity_type
self.sg.server_info["s3_enabled_upload_types"] = {
"*": ["sg_uploaded_movie", "test"]
}
self.assertTrue(self.sg._requires_direct_s3_upload("Something", "sg_uploaded_movie"))
self.assertTrue(self.sg._requires_direct_s3_upload("Version", "test"))
self.assertFalse(self.sg._requires_direct_s3_upload("Version", "other"))
# Test entity_type and field_name wildcard
self.sg.server_info["s3_enabled_upload_types"] = {
"*": "*"
}
self.assertTrue(self.sg._requires_direct_s3_upload("Something", "sg_uploaded_movie"))
self.assertTrue(self.sg._requires_direct_s3_upload("Version", "abc"))
self.sg.server_info["s3_enabled_upload_types"] = upload_types
self.sg.server_info["s3_direct_uploads_enabled"] = direct_uploads_enabled
def test_linked_thumbnail_url(self):
this_dir, _ = os.path.split(__file__)
path = os.path.abspath(os.path.expanduser(
os.path.join(this_dir, "sg_logo.jpg")))
thumb_id = self.sg.upload_thumbnail("Project", self.version['project']['id'], path)
response_version_with_project = self.find_one_await_thumbnail(
"Version",
[["id", "is", self.version["id"]]],
fields=["id", "code", "project.Project.image"],
thumbnail_field_name="project.Project.image",
)
if self.sg.server_caps.version and self.sg.server_caps.version >= (3, 3, 0):
self.assertEqual(response_version_with_project.get('type'), 'Version')
self.assertEqual(response_version_with_project.get('id'), self.version['id'])
self.assertEqual(response_version_with_project.get('code'), self.config.version_code)
h = Http(".cache")
thumb_resp, content = h.request(response_version_with_project.get('project.Project.image'), "GET")
self.assertIn(thumb_resp['status'], ['200', '304'])
self.assertIn(thumb_resp['content-type'], ['image/jpeg', 'image/png'])
else:
expected_version_with_project = {
'code': self.config.version_code,
'type': 'Version',
'id': self.version['id'],
'project.Project.image': thumb_id
}
self.assertEqual(expected_version_with_project, response_version_with_project)
# For now skip tests that are erroneously failling on some sites to
# allow CI to pass until the known issue causing this is resolved.
@base.skip("Skipping test that erroneously fails on some sites.")
def test_share_thumbnail(self):
"""share thumbnail between two entities"""
def share_thumbnail_retry(*args, **kwargs):
# Since share_thumbnail raises a ShotgunError if the thumbnail is still
# pending, sleep and retry if this exception is raised, to allow time for
# the thumbnail to finish processing.
thumbnail_id = None
attempts = 0
while attempts < base.THUMBNAIL_MAX_ATTEMPTS and thumbnail_id is None:
try:
thumbnail_id = self.sg.share_thumbnail(*args, **kwargs)
attempts += 1
except shotgun_api3.ShotgunError:
time.sleep(base.THUMBNAIL_RETRY_INTERVAL)
return thumbnail_id
this_dir, _ = os.path.split(__file__)
path = os.path.abspath(os.path.expanduser(os.path.join(this_dir, "sg_logo.jpg")))
# upload thumbnail to first entity and share it with the rest
share_thumbnail_retry([self.version, self.shot], thumbnail_path=path)
response_version_thumbnail = self.find_one_await_thumbnail(
'Version',
[['id', 'is', self.version['id']]],
fields=['id', 'code', 'image'],
)
response_shot_thumbnail = self.find_one_await_thumbnail(
'Shot',
[['id', 'is', self.shot['id']]],
fields=['id', 'code', 'image'],
)
shot_url = urllib.parse.urlparse(response_shot_thumbnail.get('image'))
version_url = urllib.parse.urlparse(response_version_thumbnail.get('image'))
shot_path = _get_path(shot_url)
version_path = _get_path(version_url)
self.assertEqual(shot_path, version_path)
# share thumbnail from source entity with entities
self.sg.upload_thumbnail("Version", self.version['id'], path)
share_thumbnail_retry([self.asset, self.shot], source_entity=self.version)
response_version_thumbnail = self.find_one_await_thumbnail(
'Version',
[['id', 'is', self.version['id']]],
fields=['id', 'code', 'image'],
)
response_shot_thumbnail = self.find_one_await_thumbnail(
'Shot',
[['id', 'is', self.shot['id']]],
fields=['id', 'code', 'image'],
)
response_asset_thumbnail = self.find_one_await_thumbnail(
'Asset',
[['id', 'is', self.asset['id']]],
fields=['id', 'code', 'image'],
)
shot_url = urllib.parse.urlparse(response_shot_thumbnail.get('image'))
version_url = urllib.parse.urlparse(response_version_thumbnail.get('image'))
asset_url = urllib.parse.urlparse(response_asset_thumbnail.get('image'))
shot_path = _get_path(shot_url)
version_path = _get_path(version_url)
asset_path = _get_path(asset_url)
self.assertEqual(version_path, shot_path)
self.assertEqual(version_path, asset_path)
# raise errors when missing required params or providing conflicting ones
self.assertRaises(shotgun_api3.ShotgunError, self.sg.share_thumbnail,
[self.shot, self.asset], path, self.version)
self.assertRaises(shotgun_api3.ShotgunError, self.sg.share_thumbnail,
[self.shot, self.asset])
@patch('shotgun_api3.Shotgun._send_form')
def test_share_thumbnail_not_ready(self, mock_send_form):
"""throw an exception if trying to share a transient thumbnail"""
mock_send_form.method.assert_called_once()
mock_send_form.return_value = ("2"
"\nsource_entity image is a transient thumbnail that cannot be shared. "
"Try again later, when the final thumbnail is available\n")
self.assertRaises(shotgun_api3.ShotgunThumbnailNotReady, self.sg.share_thumbnail,
[self.version, self.shot], source_entity=self.asset)
@patch('shotgun_api3.Shotgun._send_form')
def test_share_thumbnail_returns_error(self, mock_send_form):
"""throw an exception if server returns an error code"""
mock_send_form.method.assert_called_once()
mock_send_form.return_value = "1\nerror message.\n"
self.assertRaises(shotgun_api3.ShotgunError, self.sg.share_thumbnail,
[self.version, self.shot], source_entity=self.asset)
def test_deprecated_functions(self):
"""Deprecated functions raise errors"""
self.assertRaises(shotgun_api3.ShotgunError, self.sg.schema, "foo")
self.assertRaises(shotgun_api3.ShotgunError, self.sg.entity_types)
def test_simple_summary(self):
"""Test simple call to summarize"""
summaries = [{'field': 'id', 'type': 'count'}]
grouping = [{'direction': 'asc', 'field': 'id', 'type': 'exact'}]
filters = [['project', 'is', self.project]]
result = self.sg.summarize('Shot',
filters=filters,
summary_fields=summaries,
grouping=grouping)
assert(result['groups'])
assert(result['groups'][0]['group_name'])
assert(result['groups'][0]['group_value'])
assert(result['groups'][0]['summaries'])
assert(result['summaries'])
def test_summary_include_archived_projects(self):
"""Test summarize with archived project"""
if self.sg.server_caps.version > (5, 3, 13):
# archive project
self.sg.update('Project', self.project['id'], {'archived': True})
# Ticket #25082 ability to hide archived projects in summary
summaries = [{'field': 'id', 'type': 'count'}]
grouping = [{'direction': 'asc', 'field': 'id', 'type': 'exact'}]
filters = [['project', 'is', self.project]]
result = self.sg.summarize('Shot',
filters=filters,
summary_fields=summaries,
grouping=grouping,
include_archived_projects=False)
self.assertEqual(result['summaries']['id'], 0)
self.sg.update('Project', self.project['id'], {'archived': False})
def test_summary_values(self):
"""Test summarize return data"""
# create three unique shots
shot_prefix = uuid.uuid4().hex
shots = []
shot_data_1 = {
"code": "%s Shot 1" % shot_prefix,
"sg_status_list": "ip",
"sg_cut_duration": 100,
"project": self.project
}
shot_data_2 = {
"code": "%s Shot 2" % shot_prefix,
"sg_status_list": "ip",
"sg_cut_duration": 100,
"project": self.project
}
shot_data_3 = {
"code": "%s Shot 3" % shot_prefix,
"sg_status_list": "fin",
"sg_cut_duration": 100,
"project": self.project
}
shot_data_4 = {
"code": "%s Shot 4" % shot_prefix,
"sg_status_list": "wtg",
"sg_cut_duration": 0,
"project": self.project
}
shots.append(self.sg.create("Shot", shot_data_1))
shots.append(self.sg.create("Shot", shot_data_2))
shots.append(self.sg.create("Shot", shot_data_3))
shots.append(self.sg.create("Shot", shot_data_4))
summaries = [{'field': 'id', 'type': 'count'},
{'field': 'sg_cut_duration', 'type': 'sum'}]
grouping = [{'direction': 'asc',
'field': 'sg_status_list',
'type': 'exact'}]
filters = [['project', 'is', self.project],
['code', 'starts_with', shot_prefix]]
result = self.sg.summarize('Shot',
filters=filters,
summary_fields=summaries,
grouping=grouping)
count = {'id': 4, 'sg_cut_duration': 300}
groups = [
{
'group_name': 'fin',
'group_value': 'fin',
'summaries': {'id': 1, 'sg_cut_duration': 100}
},
{
'group_name': 'ip',
'group_value': 'ip',
'summaries': {'id': 2, 'sg_cut_duration': 200}
},
{
'group_name': 'wtg',
'group_value': 'wtg',
'summaries': {'id': 1, 'sg_cut_duration': 0}
}
]
# clean up
batch_data = []
for s in shots:
batch_data.append({
"request_type": "delete",
"entity_type": "Shot",
"entity_id": s["id"]
})
self.sg.batch(batch_data)
self.assertEqual(result['summaries'], count)
# Do not assume the order of the summarized results.
self.assertEqual(
sorted(
result['groups'],
key=lambda x: x["group_name"]
),
groups
)
def test_ensure_ascii(self):
'''test_ensure_ascii tests ensure_unicode flag.'''
sg_ascii = shotgun_api3.Shotgun(self.config.server_url,
ensure_ascii=True,
**self.auth_args)
result = sg_ascii.find_one('Note', [['id', 'is', self.note['id']]], fields=['content'])
if six.PY2:
# In Python3 there isn't a separate unicode type.
self.assertFalse(_has_unicode(result))
def test_ensure_unicode(self):
'''test_ensure_unicode tests ensure_unicode flag.'''
sg_unicode = shotgun_api3.Shotgun(self.config.server_url,
ensure_ascii=False,
**self.auth_args)
result = sg_unicode.find_one('Note', [['id', 'is', self.note['id']]], fields=['content'])
self.assertTrue(_has_unicode(result))
def test_work_schedule(self):
'''test_work_schedule tests WorkDayRules api'''
self.maxDiff = None
start_date = '2012-01-01'
start_date_obj = datetime.datetime(2012, 1, 1)
end_date = '2012-01-07'
end_date_obj = datetime.datetime(2012, 1, 7)
project = self.project
# We're going to be comparing this value with the value returned from the server, so extract only the type, id
# and name
user = {"type": self.human_user["type"], "id": self.human_user["id"], "name": self.human_user["name"]}
work_schedule = self.sg.work_schedule_read(start_date, end_date, project, user)
# Test that the work_schedule_read api method is called with the 'start_date' and 'end_date' arguments
# in the 'YYYY-MM-DD' string format.
self.assertRaises(shotgun_api3.ShotgunError, self.sg.work_schedule_read,
start_date_obj, end_date_obj, project, user)
resp = self.sg.work_schedule_update('2012-01-02', False, 'Studio Holiday')
expected = {
'date': '2012-01-02',
'description': 'Studio Holiday',
'project': None,
'user': None,
'working': False
}
self.assertEqual(expected, resp)
resp = self.sg.work_schedule_read(start_date, end_date, project, user)
work_schedule['2012-01-02'] = {"reason": "STUDIO_EXCEPTION", "working": False, "description": "Studio Holiday"}
self.assertEqual(work_schedule, resp)
resp = self.sg.work_schedule_update('2012-01-03', False, 'Project Holiday', project)
expected = {
'date': '2012-01-03',
'description': 'Project Holiday',
'project': project,
'user': None,
'working': False
}
self.assertEqual(expected, resp)
resp = self.sg.work_schedule_read(start_date, end_date, project, user)
work_schedule['2012-01-03'] = {
"reason": "PROJECT_EXCEPTION",
"working": False,
"description": "Project Holiday"
}
self.assertEqual(work_schedule, resp)
jan4 = datetime.datetime(2012, 1, 4)
self.assertRaises(shotgun_api3.ShotgunError, self.sg.work_schedule_update,
jan4, False, 'Artist Holiday', user=user)
resp = self.sg.work_schedule_update("2012-01-04", False, 'Artist Holiday', user=user)
expected = {
'date': '2012-01-04',
'description': 'Artist Holiday',
'project': None,
'user': user,
'working': False
}
self.assertEqual(expected, resp)
resp = self.sg.work_schedule_read(start_date, end_date, project, user)
work_schedule['2012-01-04'] = {"reason": "USER_EXCEPTION", "working": False, "description": "Artist Holiday"}
self.assertEqual(work_schedule, resp)
# test_preferences_read fails when preferences don't match the expected
# preferences.
def test_preferences_read(self):
# Only run the tests on a server with the feature.
if not self.sg.server_caps.version or self.sg.server_caps.version < (7, 10, 0):
return
# This is a big diff if it fails, so show everything.
self.maxDiff = None
# all prefs
resp = self.sg.preferences_read()
expected = {
'date_component_order': 'month_day',
'duration_units': 'days',
'format_currency_fields_decimal_options': '$1,000.99',
'format_currency_fields_display_dollar_sign': False,
'format_currency_fields_negative_options': '- $1,000',
'format_date_fields': '08/04/22 OR 04/08/22 (depending on the Month order preference)',
'format_float_fields': '9,999.99',
'format_float_fields_rounding': '9.999999',
'format_footage_fields': '10-05',
'format_number_fields': '1,000',
'format_time_hour_fields': '12 hour',
'hours_per_day': 8.0,
'support_local_storage': True,
'enable_rv_integration': True,
'enable_shotgun_review_for_rv': False,
}
# Simply make sure viewmaster settings are there. These change frequently and we
# don't want to have the test break because Viewmaster changed or because we didn't
# update the test.
self.assertIn("view_master_settings", resp)
resp.pop("view_master_settings")
self.assertEqual(expected, resp)
# all filtered
resp = self.sg.preferences_read(['date_component_order', 'support_local_storage'])
expected = {
'date_component_order': 'month_day',
'support_local_storage': True
}
self.assertEqual(expected, resp)
# all filtered with invalid pref
resp = self.sg.preferences_read(['date_component_order', 'support_local_storage', 'email_notifications'])
expected = {
'date_component_order': 'month_day',
'support_local_storage': True
}
self.assertEqual(expected, resp)
class TestDataTypes(base.LiveTestBase):
'''Test fields representing the different data types mapped on the server side.
Untested data types: password, percent, pivot_column, serializable, image, currency
system_task_type, timecode, url, uuid, url_template
'''
def setUp(self):
super(TestDataTypes, self).setUp()
def test_set_checkbox(self):
entity = 'HumanUser'
entity_id = self.human_user['id']
field_name = 'email_notes'
pos_values = [False, True]
expected, actual = self.assert_set_field(entity,
entity_id,
field_name,
pos_values)
self.assertEqual(expected, actual)
def test_set_color(self):
entity = 'Task'
entity_id = self.task['id']
field_name = 'color'
pos_values = ['pipeline_step', '222,0,0']
expected, actual = self.assert_set_field(entity,
entity_id,
field_name,
pos_values)
self.assertEqual(expected, actual)
def test_set_date(self):
entity = 'Task'
entity_id = self.task['id']
field_name = 'due_date'
pos_values = ['2008-05-08', '2011-05-05']
expected, actual = self.assert_set_field(entity,
entity_id,
field_name,
pos_values)
self.assertEqual(expected, actual)
def test_set_date_time(self):
if self.config.jenkins:
self.skipTest("Jenkins. locked_until not updating.")
entity = 'HumanUser'