def test_item_states(self, ConnectionMock): api = self._get_list_mock(ConnectionMock) video = Video(name="Name of video", id=TEST_VIDEO_ID) video.item_state = enums.ItemStateEnum.PENDING, video.save() item_state_sent = api.method_calls[1][2]['video']['itemState'][0] self.assertEquals(item_state_sent, enums.ItemStateEnum.PENDING)
def test_invalid_name(self, ConnectionMock): v = Video(name="Name is too long" * 20, short_description="ok desc", filename="somefile.mov") try: v.validate() except pybrightcove.exceptions.PyBrightcoveError, e: self.assertEqual(str(e), "Video.name must be 255 characters or less.")
def test_delete(self, ConnectionMock): m = ConnectionMock() m.get_item.return_value = VIDEO_DATA video = Video(id=TEST_VIDEO_ID) video.delete() self.assertEquals(m.method_calls[0][0], 'get_item') self.assertEquals(m.method_calls[1][0], 'post') self.assertEquals(m.method_calls[1][1][0], 'delete_video') self.assertEquals(m.method_calls[1][2]['video_id'], TEST_VIDEO_ID)
def test_invalid_reference_id(self, ConnectionMock): video = Video(name="Name is too long", short_description="ok desc", filename="somefile.mov") video.reference_id = "long ref id" * 100 try: video.validate() except pybrightcove.exceptions.PyBrightcoveError, e: self.assertEqual(str(e), "Video.reference_id must be 150 characters or less.")
def test_find_related(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) m.get_item.return_value = VIDEO_DATA video = Video(id=TEST_VIDEO_ID) for related_video in video.find_related(): print related_video # self.assertEquals(type(related_video), Video) print m.method_calls self.assertEquals(m.method_calls[1][0], 'get_list') self.assertEquals(m.method_calls[1][1][0], 'find_related_videos') self.assertEquals(m.method_calls[1][2]['video_id'], TEST_VIDEO_ID)
def test_invalid_long_description(self, ConnectionMock): video = Video(name="Name is too long", short_description="ok desc", filename="somefile.mov") video.long_description = "Very long" * 5000 try: video.validate() except pybrightcove.exceptions.PyBrightcoveError, e: self.assertEqual(str(e), "Video.long_description must be 5000 characters or less.")
def test_invalid_video_full_length(self, ConnectionMock): video = Video(name="Name is too long", short_description="ok desc", filename="somefile.mov") video.video_full_length = 10 try: video.validate() except pybrightcove.exceptions.PyBrightcoveError, e: self.assertEqual(str(e), "Video.video_full_length must be of type Rendition")
def test_invalid_economics(self, ConnectionMock): video = Video(name="Name is too long", short_description="ok desc", filename="somefile.mov") video.economics = "The Keynesian view is Wrong" try: video.validate() except pybrightcove.exceptions.PyBrightcoveError, e: err = "Video.economics must be either EconomicsEnum.FREE or" err += " EconomicsEnum.AD_SUPPORTED" self.assertEqual(str(e), err)
def test_invalid_item_state(self, ConnectionMock): video = Video(name="Name is too long", short_description="ok desc", filename="somefile.mov") video.item_state = "Invalid" try: video.validate() except pybrightcove.exceptions.PyBrightcoveError, e: err = "Video.item_state must be either ItemStateEnum.ACTIVE or " err += "ItemStateEnum.INACTIVE or ItemStateEnum.DELETED" self.assertEqual(str(e), err)
def test_save_new(self, ConnectionMock): m = ConnectionMock() m.post.return_value = 10 video = Video(filename='bears.mov', name='The Bears', short_description='Opening roll for an exciting soccer match.') video.tags.append('unittest') self.assertEquals(video.id, None) video.save() self.assertEquals(video.id, 10) self.assertEquals(m.method_calls[0][0], 'post') self.assertEquals(m.method_calls[0][1][0], 'create_video')
def test_get_upload_status(self, ConnectionMock): m = ConnectionMock() m.post.return_value = pybrightcove.enums.UploadStatusEnum.PROCESSING m.get_item.return_value = VIDEO_DATA video = Video(id=TEST_VIDEO_ID) status = video.get_upload_status() self.assertEquals(status, pybrightcove.enums.UploadStatusEnum.PROCESSING) self.assertEquals(m.method_calls[0][0], 'get_item') self.assertEquals(m.method_calls[1][0], 'post') self.assertEquals(m.method_calls[1][1][0], 'get_upload_status') self.assertEquals(m.method_calls[1][2]['video_id'], TEST_VIDEO_ID)
def test_get_metadata(self, ConnectionMock): m = self._get_item_mock(ConnectionMock) video = Video(id=TEST_VIDEO_IDS[0]) m.get_item.return_value = {"customFields": {"sample": "title"}} video.get_custom_metadata() print video # self.assertEquals(type(video), Video) print m.method_calls print video.metadata self.assertEquals(m.method_calls[0][0], 'get_item') self.assertEquals(m.method_calls[0][1][0], 'find_video_by_id') self.assertEquals(m.method_calls[1][1][0], 'find_video_by_id') self.assertEquals(m.method_calls[1][2]["video_fields"], 'customFields') self.assertEquals(video.metadata[0]["key"], "sample") self.assertEquals(video.metadata[0]["value"], "title")
def download_video(id): logger.info("Video(%s)" % (id,)) try: # get video object from ID v = Video(id=id, _connection=OLDCONN, media_delivery="http", custom_fields=MY_CUSTOM_FIELDS) except NoDataFoundError: logger.warn(" **> No data found for (%s)" % (id,)) return None # determine best rendition (largest size) best_rendition = None for rendition in v.renditions: if rendition.url is not None and rendition.url.startswith('http'): if best_rendition is None: best_rendition = rendition elif rendition.size > best_rendition.size: best_rendition = rendition if best_rendition is None: logger.warn(" No best rendition found for (%s). Skipping." % (id,)) return else: # use best rendition to fetch video fname = DOWNLOAD_DIR + str(id) if best_rendition.video_codec == 'H264': fname += ".mp4" elif best_rendition.video_codec == 'M2TS': fname += ".m2ts" logger.info(" fetching ID(%s) codec(%s) to (%s)" % (v.id, best_rendition.video_codec,fname,)) try: req = urllib2.urlopen(best_rendition.url) downloaded = 0 CHUNK = 4096 with open(fname, 'wb') as fp: while True: chunk = req.read(CHUNK) downloaded += len(chunk) if not chunk: break fp.write(chunk) logger.debug(" bytes downloaded: " + str(downloaded)) v._filename = fname # required for upload with v.save() except urllib2.HTTPError, e: logger.warn("HTTP Error: %s - (%s)" % (e.code, url,)) return False except urllib2.URLError, e: logger.warn("URL Error: %s - (%s)" % (e.reason, url,)) return False
def test_set_image(self, ConnectionMock): image = pybrightcove.video.Image(reference_id="img-%s" % self.test_uuid, display_name="My Test Image", type=pybrightcove.enums.ImageTypeEnum.VIDEO_STILL) m = ConnectionMock() m.post.return_value = IMAGE_DATA m.get_item.return_value = VIDEO_DATA video = Video(id=TEST_VIDEO_ID) video.set_image(image, filename="IMG_0050.JPG") self.assertEquals(m.method_calls[0][0], 'get_item') self.assertEquals(m.method_calls[1][0], 'post') self.assertEquals(m.method_calls[1][1][0], 'add_image') self.assertEquals(m.method_calls[1][2]['video_id'], TEST_VIDEO_ID) self.assertEquals(video.image.to_dict(), IMAGE_DATA)
def test_ensure_essential_fields(self): essentials = ["creationDate", "economics", "id", "lastModifiedDate", "length", "linkText", "linkURL", "longDescription", "name", "playsTotal", "playsTrailingWeek", "publishedDate", "referenceId", "shortDescription"] kwargs = Video.ensure_essential_fields(**{}) self.assertEqual(kwargs, {}) kwargs = {'video_fields': ['itemState', ]} kwargs = Video.ensure_essential_fields(**kwargs) for key in essentials: self.assertTrue(key in kwargs['video_fields']) self.assertTrue('itemState' in kwargs['video_fields'])
def test_save_update(self, ConnectionMock): m = ConnectionMock() m.post.return_value = VIDEO_DATA m.get_item.return_value = VIDEO_DATA video = Video(id=TEST_VIDEO_ID) video.tags.append('tag-%s' % self.test_uuid) video.tags.append('unittest') self.assertEquals(video.id, TEST_VIDEO_ID) video.save() self.assertEquals(video.id, TEST_VIDEO_ID) self.assertEquals(video.reference_id, TEST_VIDEO_REF_ID) self.assertEquals(m.method_calls[0][0], 'get_item') self.assertEquals(m.method_calls[1][0], 'post') self.assertEquals(m.method_calls[1][1][0], 'update_video') self.assertTrue('unittest' in m.method_calls[1][2]['video']['tags']) self.assertTrue('tag-%s' % self.test_uuid in m.method_calls[1][2]['video']['tags'])
def test_find_all(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) videos = Video.find_all() for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_all_videos')
def test_find_by_ids(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) videos = Video.find_by_ids(TEST_VIDEO_IDS) for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_videos_by_ids') self.assertEquals(m.method_calls[0][2]['video_ids'], ','.join([str(x) for x in TEST_VIDEO_IDS])) videos = Video.find_by_ids(TEST_VIDEO_IDS, unfiltered=True) for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[1][0], 'get_list') self.assertEquals(m.method_calls[1][1][0], 'find_videos_by_ids_unfiltered') self.assertEquals(m.method_calls[1][2]['video_ids'], ','.join([str(x) for x in TEST_VIDEO_IDS]))
def test_find_by_user(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) videos = Video.find_by_user(12312431) for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_videos_by_user_id') self.assertEquals(m.method_calls[0][2]['user_id'], 12312431)
def test_find_by_tags(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) videos = Video.find_by_tags(and_tags=['unittest', 'two']) for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_videos_by_tags') self.assertEquals(m.method_calls[0][2]['and_tags'], ','.join(['unittest', 'two']))
def test_find_by_text(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) videos = Video.find_by_text('bear') for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_videos_by_text') self.assertEquals(m.method_calls[0][2]['text'], 'bear')
def test_find_by_campaign(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) videos = Video.find_by_campaign(988756758) for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_videos_by_campaign_id') self.assertEquals(m.method_calls[0][2]['campaign_id'], 988756758)
def test_save_new_with_metadata(self, ConnectionMock): m = ConnectionMock() m.post.return_value = TEST_VIDEO_ID video = Video(filename='bears.mov', name='The Bears', short_description='Opening roll for an exciting soccer match.') video.tags.append('unittest') self.assertEquals(video.id, None) video.add_custom_metadata('genre', 'Sci-Fi') video.add_custom_metadata('rating', 'PG-13') video.save() self.assertEquals(video.id, TEST_VIDEO_ID) self.assertEquals(m.method_calls[0][0], 'post') self.assertEquals(m.method_calls[0][1][0], 'create_video') self.assertTrue('unittest' in m.method_calls[0][2]['video']['tags']) self.assertTrue('customFields' in m.method_calls[0][2]['video']) self.assertTrue('genre' in m.method_calls[0][2]['video']['customFields']) self.assertTrue('rating' in m.method_calls[0][2]['video']['customFields']) self.assertEquals(m.method_calls[0][2]['video']['customFields']['genre'], 'Sci-Fi') self.assertEquals(m.method_calls[0][2]['video']['customFields']['rating'], 'PG-13')
def test_find_modified_unfiltered(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) yesterday = datetime.now() - timedelta(days=1) videos = Video.find_modified(since=yesterday) for video in videos: print video # self.assertEquals(type(video), Video) print m.method_calls self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_modified_videos') self.assertEquals(m.method_calls[0][2]['from_date'] > 0, True)
def test_find_modified_filtered(self, ConnectionMock): m = self._get_list_mock(ConnectionMock) yesterday = datetime.now() - timedelta(days=1) filters = [pybrightcove.enums.FilterChoicesEnum.PLAYABLE, pybrightcove.enums.FilterChoicesEnum.DELETED] videos = Video.find_modified(since=yesterday, filter_list=filters) for video in videos: print video # self.assertEquals(type(video), Video) self.assertEquals(m.method_calls[0][0], 'get_list') self.assertEquals(m.method_calls[0][1][0], 'find_modified_videos') self.assertEquals(m.method_calls[0][2]['from_date'] > 0, True) self.assertEquals(m.method_calls[0][2]['filter'], filters)
def test_save_new_with_renditions(self, ConnectionMock): m = ConnectionMock() m.post.return_value = 10 renditions = [] r = pybrightcove.video.Rendition() r.remote_url = 'http://my.server.com/640_h264.flv' r.size = 232522522 r.video_duration = 60000 r.video_codec = pybrightcove.enums.VideoCodecEnum.H264 renditions.append(r) r = pybrightcove.video.Rendition() r.remote_url = 'http://my.server.com/560_h264.flv' r.size = 23252252 r.video_duration = 60000 r.video_codec = pybrightcove.enums.VideoCodecEnum.H264 renditions.append(r) r = pybrightcove.video.Rendition() r.remote_url = 'http://my.server.com/480_h264.flv' r.size = 2325225 r.video_duration = 60000 r.video_codec = pybrightcove.enums.VideoCodecEnum.H264 renditions.append(r) video = Video(name='The Bears', renditions=renditions, short_description='Opening roll for an exciting soccer match.') video.tags.append('unittest') self.assertEquals(video.id, None) video.save() m.post.return_value = {'id': 123456, 'referenceId': 777777, 'type': 'VIDEO_STILL', 'remoteUrl': 'http://my.sample.com/image-2', 'displayName': None} i = pybrightcove.video.Image() i.type = pybrightcove.enums.ImageTypeEnum.THUMBNAIL i.remote_url = 'http://my.sample.com/image-1.jpg' video.set_image(i) i = pybrightcove.video.Image() i.type = pybrightcove.enums.ImageTypeEnum.VIDEO_STILL i.remote_url = 'http://my.sample.com/image-2.jpg' video.set_image(i) self.assertEquals(video.id, 10) self.assertEquals(m.method_calls[0][0], 'post') self.assertEquals(m.method_calls[0][1][0], 'create_video') self.assertEquals(len(m.method_calls[0][2]['video']['renditions']), 3) self.assertEquals(m.method_calls[0][2]['video']['renditions'][1]['remoteUrl'], 'http://my.server.com/560_h264.flv') self.assertEquals(m.method_calls[1][0], 'post') self.assertEquals(m.method_calls[1][1][0], 'add_image') self.assertEquals(m.method_calls[1][2]['image']['remoteUrl'], 'http://my.sample.com/image-1.jpg') self.assertEquals(m.method_calls[2][0], 'post') self.assertEquals(m.method_calls[2][1][0], 'add_image') self.assertEquals(m.method_calls[2][2]['image']['remoteUrl'], 'http://my.sample.com/image-2.jpg')
def test_save_update_with_metadata(self, ConnectionMock): m = ConnectionMock() m.post.return_value = VIDEO_DATA m.get_item.return_value = VIDEO_DATA video = Video(id=TEST_VIDEO_ID) video.tags.append('tag-%s' % self.test_uuid) video.tags.append('unittest') video.add_custom_metadata('genre', 'Sci-Fi', 'string') video.add_custom_metadata('rating', 'PG-13', 'string') self.assertEquals(video.id, TEST_VIDEO_ID) video.save() self.assertEquals(video.id, TEST_VIDEO_ID) self.assertEquals(video.reference_id, TEST_VIDEO_REF_ID) self.assertEquals(m.method_calls[0][0], 'get_item') self.assertEquals(m.method_calls[1][0], 'post') self.assertEquals(m.method_calls[1][1][0], 'update_video') self.assertTrue('unittest' in m.method_calls[1][2]['video']['tags']) self.assertTrue('tag-%s' % self.test_uuid in m.method_calls[1][2]['video']['tags']) self.assertTrue('customFields' in m.method_calls[1][2]['video']) self.assertTrue('genre' in m.method_calls[1][2]['video']['customFields']) self.assertTrue('rating' in m.method_calls[1][2]['video']['customFields']) self.assertEquals(m.method_calls[1][2]['video']['customFields']['genre'], 'Sci-Fi') self.assertEquals(m.method_calls[1][2]['video']['customFields']['rating'], 'PG-13')
# furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from pybrightcove.connection import Connection from pybrightcove.video import Video c = Connection() import sys video = Video() video.name = sys.argv[1] video.shortDescription = sys.argv[1] * 50 for tag in sys.argv[2:]: video.tags.append(tag) print "Attempting to upload %s" % sys.argv[1] c.create_video(sys.argv[1], video=video) print "Done"
def download_video(id): logger.info("Video(%s)" % (id, )) try: # get video object from ID v = Video(id=id, _connection=OLDCONN, media_delivery="http", custom_fields=MY_CUSTOM_FIELDS) except NoDataFoundError: logger.warn(" **> No data found for (%s)" % (id, )) return None # determine best rendition (largest size) best_rendition = None for rendition in v.renditions: if rendition.url is not None and rendition.url.startswith('http'): if best_rendition is None: best_rendition = rendition elif rendition.size > best_rendition.size: best_rendition = rendition if best_rendition is None: logger.warn(" No best rendition found for (%s). Skipping." % (id, )) return else: # use best rendition to fetch video fname = DOWNLOAD_DIR + str(id) if best_rendition.video_codec == 'H264': fname += ".mp4" elif best_rendition.video_codec == 'M2TS': fname += ".m2ts" logger.info(" fetching ID(%s) codec(%s) to (%s)" % ( v.id, best_rendition.video_codec, fname, )) try: req = urllib2.urlopen(best_rendition.url) downloaded = 0 CHUNK = 4096 with open(fname, 'wb') as fp: while True: chunk = req.read(CHUNK) downloaded += len(chunk) if not chunk: break fp.write(chunk) logger.debug(" bytes downloaded: " + str(downloaded)) v._filename = fname # required for upload with v.save() except urllib2.HTTPError, e: logger.warn("HTTP Error: %s - (%s)" % ( e.code, url, )) return False except urllib2.URLError, e: logger.warn("URL Error: %s - (%s)" % ( e.reason, url, )) return False
# furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from pybrightcove.connection import Connection from pybrightcove.video import Video c = Connection() import sys video = Video() video.name = sys.argv[1] video.shortDescription = sys.argv[1]*50 for tag in sys.argv[2:]: video.tags.append(tag) print "Attempting to upload %s" % sys.argv[1] c.create_video(sys.argv[1], video=video) print "Done"