From 0882427675b4d6d8467f4f1937b54981e7a92e0e Mon Sep 17 00:00:00 2001 From: Patrick Wolf <758811+patrickwolf@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:00:05 +0000 Subject: [PATCH 1/2] Mockgun: implement upload upload raised NotImplementedError. It now validates the path and the field as the server does and creates the records an upload leaves: an Attachment linked to the entity, holding the file's name, size and tags, and the File/Link field pointing at it. A thumbnail field sets the entity's image field. The file itself is not stored. Co-Authored-By: Claude Opus 5.5 --- shotgun_api3/lib/mockgun/mockgun.py | 64 +++++++++++++++++- tests/test_mockgun.py | 100 ++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+), 2 deletions(-) diff --git a/shotgun_api3/lib/mockgun/mockgun.py b/shotgun_api3/lib/mockgun/mockgun.py index 522e162d9..99fd210df 100644 --- a/shotgun_api3/lib/mockgun/mockgun.py +++ b/shotgun_api3/lib/mockgun/mockgun.py @@ -115,6 +115,8 @@ """ import datetime +import mimetypes +import os from typing import Any from ... import ShotgunError @@ -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 diff --git a/tests/test_mockgun.py b/tests/test_mockgun.py index b12c318f7..7018e3794 100644 --- a/tests/test_mockgun.py +++ b/tests/test_mockgun.py @@ -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 @@ -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() From 2563f0ba6427e0b20a75a6ef2c5437eeec3da1e0 Mon Sep 17 00:00:00 2001 From: Patrick Wolf <758811+patrickwolf@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:44:59 +0000 Subject: [PATCH 2/2] Mockgun: implement download_attachment upload now keeps a copy of the file in a temporary folder, removed with the Mockgun instance. download_attachment returns it, as bytes or written to file_path, for an Attachment entity, a File/Link field value or an id, and also returns the file of a local file link. It raises ShotgunFileDownloadError for an attachment it has no file for, as the server does. Co-Authored-By: Claude Opus 5.5 --- shotgun_api3/lib/mockgun/mockgun.py | 50 ++++++++++++++++++++++++-- tests/test_mockgun.py | 54 ++++++++++++++++++++++++++++- 2 files changed, 101 insertions(+), 3 deletions(-) diff --git a/shotgun_api3/lib/mockgun/mockgun.py b/shotgun_api3/lib/mockgun/mockgun.py index 99fd210df..1605c23c8 100644 --- a/shotgun_api3/lib/mockgun/mockgun.py +++ b/shotgun_api3/lib/mockgun/mockgun.py @@ -117,9 +117,12 @@ import datetime import mimetypes import os +import shutil +import tempfile +import weakref from typing import Any -from ... import ShotgunError +from ... import ShotgunError, ShotgunFileDownloadError from ...shotgun import _Config from .errors import MockgunError from .schema import SchemaFactory @@ -208,6 +211,9 @@ def __init__(self, # initialize the "database" self._db = dict((entity, {}) for entity in self._schema) + # the copies of uploaded files, by Attachment id, in a folder made on the first upload + self._uploads = {} + self._upload_folder = None # set some basic public members that exist in the Shotgun API self.base_url = base_url @@ -452,7 +458,8 @@ def upload(self, entity_type, entity_id, path, field_name=None, display_name=Non 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. + the entity's field pointing at it, with the tags of tag_list. A copy of the file is kept in a + temporary folder, which download_attachment returns and which is removed with this instance. :returns: Id of the Attachment entity, as the server returns. """ @@ -483,6 +490,13 @@ def upload(self, entity_type, entity_id, path, field_name=None, display_name=Non # 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"] + if self._upload_folder is None: + self._upload_folder = tempfile.mkdtemp(prefix="mockgun_uploads_") + weakref.finalize(self, shutil.rmtree, self._upload_folder, True) + copy = os.path.join(self._upload_folder, str(attachment_id), filename) + os.makedirs(os.path.dirname(copy)) + shutil.copyfile(path, copy) + self._uploads[attachment_id] = copy url = "%s://%s/file_serve/attachment/%d" % (self.config.scheme, self.config.server, attachment_id) this_file = { @@ -509,6 +523,38 @@ def upload(self, entity_type, entity_id, path, field_name=None, display_name=Non self.update(entity_type, entity_id, {field_name: this_file}) return attachment_id + def download_attachment(self, attachment=False, file_path=None, attachment_id=None): + """ + Returns a file this instance uploaded, or the file a local file link points at. + + :param attachment: An Attachment entity, the value of a File/Link field, or an Attachment id. + :param str file_path: Optional path to write the file to. + :returns: file_path if given, the file's content as bytes otherwise, None for an attachment of None. + """ + if attachment is False: + if isinstance(attachment_id, int): + attachment = attachment_id + else: + raise TypeError( + "Missing parameter 'attachment'. Expected a dict, int, NoneType value or " + "an int for parameter attachment_id" + ) + if attachment is None: + return None + if isinstance(attachment, dict) and attachment.get("link_type") == "local": + source = attachment.get("local_path") + else: + source = self._uploads.get(attachment.get("id") if isinstance(attachment, dict) else attachment) + if not source or not os.path.isfile(source): + raise ShotgunFileDownloadError( + "Failed to open %s\nAttachment may not exist or is a local file?" % (attachment,) + ) + if file_path: + shutil.copyfile(source, file_path) + return file_path + with open(source, "rb") as f: + return f.read() + def upload_thumbnail(self, entity_type, entity_id, path, **kwargs): pass diff --git a/tests/test_mockgun.py b/tests/test_mockgun.py index 7018e3794..4877292f4 100644 --- a/tests/test_mockgun.py +++ b/tests/test_mockgun.py @@ -36,13 +36,14 @@ """ import datetime +import gc import re import os import shutil import tempfile import unittest from shotgun_api3.lib.mockgun import Shotgun as Mockgun -from shotgun_api3 import ShotgunError +from shotgun_api3 import ShotgunError, ShotgunFileDownloadError mockgun_schema_folder = os.path.join(os.path.dirname(__file__), "mockgun") @@ -855,5 +856,56 @@ def test_invalid(self): self._mockgun.upload("Version", version_id + 100, self._path) +class TestDownloadAttachment(unittest.TestCase): + """ + download_attachment returns what was uploaded, and the file of a local file link. + """ + + setUp = TestUpload.setUp + + def test_download_upload(self): + self._mockgun.upload( + "Version", self._version["id"], self._path, field_name="sg_uploaded_movie" + ) + movie = self._mockgun.find_one( + "Version", [["id", "is", self._version["id"]]], ["sg_uploaded_movie"] + )["sg_uploaded_movie"] + self.assertEqual(self._mockgun.download_attachment(movie), b"movie") + self.assertEqual(self._mockgun.download_attachment(movie["id"]), b"movie") + self.assertEqual( + self._mockgun.download_attachment(attachment_id=movie["id"]), b"movie" + ) + target = os.path.join(os.path.dirname(self._path), "downloaded.mov") + self.assertEqual( + self._mockgun.download_attachment(movie, file_path=target), target + ) + with open(target, "rb") as f: + self.assertEqual(f.read(), b"movie") + + def test_copy_outlives_source(self): + attachment_id = self._mockgun.upload("Version", self._version["id"], self._path) + os.remove(self._path) + self.assertEqual(self._mockgun.download_attachment(attachment_id), b"movie") + + def test_download_local_file_link(self): + link = {"local_path": self._path, "link_type": "local", "name": "v001.mov"} + self.assertEqual(self._mockgun.download_attachment(link), b"movie") + + def test_download_missing(self): + self.assertIsNone(self._mockgun.download_attachment(None)) + with self.assertRaises(ShotgunFileDownloadError): + self._mockgun.download_attachment(12345) + with self.assertRaises(TypeError): + self._mockgun.download_attachment() + + def test_folder_removed_with_instance(self): + self._mockgun.upload("Version", self._version["id"], self._path) + folder = self._mockgun._upload_folder + self.assertTrue(os.path.isdir(folder)) + del self._mockgun + gc.collect() + self.assertFalse(os.path.exists(folder)) + + if __name__ == "__main__": unittest.main()