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
112 changes: 109 additions & 3 deletions shotgun_api3/lib/mockgun/mockgun.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,14 @@
"""

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
Expand Down Expand Up @@ -206,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
Expand Down Expand Up @@ -446,8 +454,106 @@ 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. 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.
"""
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"]
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 = {
"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 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
Expand Down
154 changes: 153 additions & 1 deletion tests/test_mockgun.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +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")

Expand Down Expand Up @@ -755,5 +758,154 @@ 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)


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()
Loading