Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 62 additions & 2 deletions shotgun_api3/lib/mockgun/mockgun.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@
"""

import datetime
import mimetypes
import os
from typing import Any

from ... import ShotgunError
Expand Down Expand Up @@ -446,8 +448,66 @@ def revive(self, entity_type, entity_id):
else:
return False

def upload(self, entity_type, entity_id, path, field_name=None, display_name=None, tag_list=None):
raise NotImplementedError
def upload(self, entity_type, entity_id, path, field_name=None, display_name=None, tag_list=None,
created_at=None):
"""
Leaves the records an upload leaves on the server: an Attachment linked to the entity, and
the entity's field pointing at it, with the tags of tag_list. The file itself is not stored.

:returns: Id of the Attachment entity, as the server returns.
"""
self._validate_entity_type(entity_type)
self._validate_entity_exists(entity_type, entity_id)
path = os.path.abspath(os.path.expanduser(path or ""))
if not os.path.isfile(path):
raise ShotgunError("Path must be a valid file, got '%s'" % path)
if os.path.getsize(path) == 0:
raise ShotgunError("Path cannot be an empty file: '%s'" % path)
is_thumbnail = field_name in ("thumb_image", "filmstrip_thumb_image", "image", "filmstrip_image")
if field_name and not is_thumbnail:
self._validate_entity_fields(entity_type, [field_name])
if self._get_field_type(entity_type, field_name) != "url":
raise ShotgunError("%s.%s is not a File/Link field" % (entity_type, field_name))

filename = os.path.basename(path)
entity = {"type": entity_type, "id": entity_id}
data = {
"filename": filename,
"display_name": display_name or filename,
"file_size": os.path.getsize(path),
"file_extension": os.path.splitext(filename)[1].lstrip(".") or None,
"attachment_links": [entity],
"project": self._db[entity_type][entity_id].get("project"),
"created_at": created_at,
}
# Schemas differ between sites: only set the fields this one has.
data = dict((k, v) for k, v in data.items() if v is not None and k in self._schema["Attachment"])
attachment_id = self.create("Attachment", data)["id"]

url = "%s://%s/file_serve/attachment/%d" % (self.config.scheme, self.config.server, attachment_id)
this_file = {
"type": "Attachment",
"id": attachment_id,
"name": display_name or filename,
"url": url,
"link_type": "upload",
"content_type": mimetypes.guess_type(filename)[0],
}
self.update("Attachment", attachment_id, {"this_file": this_file})
if tag_list and "tag_list" in self._schema["Attachment"]:
# A tag field holds the tag names. Written to the row directly, as Mockgun does not
# take writes to tag fields.
tags = [tag.strip() for tag in tag_list.split(",") if tag.strip()]
self._db["Attachment"][attachment_id]["tag_list"] = tags
if is_thumbnail:
# An image field holds the thumbnail's URL. Written to the row directly, as Mockgun
# does not take writes to image fields.
image_field = "filmstrip_image" if "filmstrip" in field_name else "image"
if image_field in self._schema[entity_type]:
self._db[entity_type][entity_id][image_field] = url
elif field_name:
self.update(entity_type, entity_id, {field_name: this_file})
return attachment_id

def upload_thumbnail(self, entity_type, entity_id, path, **kwargs):
pass
Expand Down
100 changes: 100 additions & 0 deletions tests/test_mockgun.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
import datetime
import re
import os
import shutil
import tempfile
import unittest
from shotgun_api3.lib.mockgun import Shotgun as Mockgun
from shotgun_api3 import ShotgunError
Expand Down Expand Up @@ -755,5 +757,103 @@ def test_set_server_params_with_url_with_path(self):
self.assertEqual(mockgun.config.api_path, "/something/api3/json")


class TestUpload(unittest.TestCase):
"""
upload leaves the records the server leaves.
"""

def setUp(self):
self._mockgun = Mockgun(
"https://test.shotgunstudio.com", login="user", password="1234"
)
self._project = self._mockgun.create("Project", {"name": "prj"})
self._version = self._mockgun.create(
"Version", {"code": "v001", "project": self._project}
)
folder = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, folder)
self._path = os.path.join(folder, "v001.mov")
with open(self._path, "wb") as f:
f.write(b"movie")

def test_upload_to_field(self):
attachment_id = self._mockgun.upload(
"Version",
self._version["id"],
self._path,
field_name="sg_uploaded_movie",
display_name="Latest",
)
version = self._mockgun.find_one(
"Version", [["id", "is", self._version["id"]]], ["sg_uploaded_movie"]
)
movie = version["sg_uploaded_movie"]
self.assertEqual((movie["type"], movie["id"]), ("Attachment", attachment_id))
self.assertEqual((movie["name"], movie["link_type"]), ("Latest", "upload"))
self.assertEqual(
movie["url"],
"https://test.shotgunstudio.com/file_serve/attachment/%d" % attachment_id,
)
attachment = self._mockgun.find_one(
"Attachment",
[["id", "is", attachment_id]],
["filename", "file_size", "attachment_links", "project", "this_file"],
)
self.assertEqual(attachment["filename"], "v001.mov")
self.assertEqual(attachment["file_size"], 5)
self.assertEqual(
attachment["attachment_links"],
[{"type": "Version", "id": self._version["id"]}],
)
self.assertEqual(attachment["project"]["id"], self._project["id"])
self.assertEqual(attachment["this_file"], movie)

def test_upload_without_field(self):
attachment_id = self._mockgun.upload("Version", self._version["id"], self._path)
found = self._mockgun.find(
"Attachment", [["attachment_links", "is", self._version]]
)
self.assertEqual([a["id"] for a in found], [attachment_id])

def test_upload_tags(self):
attachment_id = self._mockgun.upload(
"Version", self._version["id"], self._path, tag_list="review, final"
)
attachment = self._mockgun.find_one(
"Attachment", [["id", "is", attachment_id]], ["tag_list"]
)
self.assertEqual(attachment["tag_list"], ["review", "final"])

def test_upload_thumbnail_field(self):
self._mockgun.upload(
"Version", self._version["id"], self._path, field_name="thumb_image"
)
version = self._mockgun.find_one(
"Version", [["id", "is", self._version["id"]]], ["image"]
)
self.assertTrue(
version["image"].startswith(
"https://test.shotgunstudio.com/file_serve/attachment/"
)
)

def test_invalid(self):
version_id = self._version["id"]
with self.assertRaises(ShotgunError):
self._mockgun.upload("Version", version_id, self._path + ".missing")
empty = os.path.join(os.path.dirname(self._path), "empty.mov")
open(empty, "wb").close()
with self.assertRaises(ShotgunError):
self._mockgun.upload("Version", version_id, empty)
with self.assertRaises(ShotgunError):
self._mockgun.upload("Version", version_id, self._path, field_name="code")
with self.assertRaises(ShotgunError):
self._mockgun.upload(
"Version", version_id, self._path, field_name="no_such_field"
)
with self.assertRaises(ShotgunError):
self._mockgun.upload("Version", version_id + 100, self._path)


if __name__ == "__main__":
unittest.main()
Loading