def test_track_add_validating(self): """ track_add -- validating the form, metadata only without a file """ from c3sar.views.track import track_add request = testing.DummyRequest( post={u'form.submitted': True, u'track_name': u'my test track', #u'track_file': u'', # <-- without file upload! u'track_url': u'http://me.com/file.mp3', u'track_album': u'my test album', }) self.config = testing.setUp(request=request) _registerRoutes(self.config) result = track_add(request) # expect a redirect self.assertTrue(isinstance(result, HTTPFound), "should have been a redirect") # ToDo: check for track entry in db from c3sar.models import Track my_track = Track.get_by_track_id(u'1') self.assertEquals(my_track.name, 'my test track') self.assertEquals(my_track.album, 'my test album') self.assertEquals(my_track.url, 'http://me.com/file.mp3')
def test_track_add_validating_w_file(self): """ track_add -- validating the form, metadata & file """ from c3sar.views.track import track_add # note: file upload is a FieldStorage thing # # request.POST looks like this: # MultiDict( # [ # (u'_csrf', u'fe0251aad0b051c0bfc856826ff50b2fe917c8ac'), # (u'track_name', u'another track'), # (u'track_album', u'another album'), # (u'track_url', u'http://somewhe.re/track.mp3'), # (u'track_file', # FieldStorage( # u'track_file', u"lissie_-_when_i'm_alone.mp3")), # (u'form.submitted', u'Save')]) # class AFile(object): """dummy to allow for attributes """ pass _a_file = AFile() _a_file.file = open('c3sar/models.py', 'r') _a_file.filename = 'my model' import os _a_file.size = os.path.getsize('c3sar/models.py') request = testing.DummyRequest( post={u'form.submitted': True, u'track_name': u'my test track', u'track_upload': _a_file, # see class AFile above u'track_url': u'http://me.com/file.mp3', u'track_album': u'my test album', }) if DEBUG: # pragma: no cover print "the request.POST: " pp.pprint(request.POST) self.config = testing.setUp(request=request) _registerRoutes(self.config) result = track_add(request) if DEBUG: # pragma: no cover print "the result of track_add with file: " pp.pprint(result) # close the file again _a_file.file.close() # expect a redirect self.assertTrue(isinstance(result, HTTPFound), "should have been a redirect") # ToDo: check for track entry in db from c3sar.models import Track my_track = Track.get_by_track_id(u'1') self.assertEquals(my_track.name, 'my test track') self.assertEquals(my_track.album, 'my test album') self.assertEquals(my_track.url, 'http://me.com/file.mp3')
def test_track_add_license_submit_cc_generic(self): """ track add license & submit: cc-by generic""" from c3sar.views.track import track_add_license # add a track track1 = self._makeTrack() self.dbsession.add(track1) self.dbsession.flush() request = testing.DummyRequest( post={'form.submitted': True, u'cc_js_want_cc_license': u'sure', u'cc_js_share': u'1', u'cc_js_remix': u'', u'cc_js_jurisdiction': u'generic', u'cc_js_result_uri': u'http://creativecommons.org/licenses/by/3.0/', u'cc_js_result_img': u'http://i.creativecommons.org/l/by/3.0/88x31.png', u'cc_js_result_name': u'Creative Commons Attribution 3.0 Unported', }) request.matchdict['track_id'] = 1 self.config = testing.setUp(request=request) _registerRoutes(self.config) result = track_add_license(request) if DEBUG: # pragma: no cover pp.pprint(result) # check for redirect self.assertTrue(isinstance(result, HTTPFound), "no redirect") # redirect goes to track/view/1 self.assertTrue('track/view/1' in result.headerlist[2][1], "no redirect") from c3sar.models import Track the_track = Track.get_by_track_id(1) the_license = the_track.license[0] self.assertEquals(the_license.id, 1, "wrong id: should be the only one in database") self.assertEquals(the_license.img, u'http://i.creativecommons.org/l/by/3.0/88x31.png', "wrong license img") self.assertEquals(the_license.uri, u'http://creativecommons.org/licenses/by/3.0/', "wrong license uri") self.assertEquals( the_license.name, u'Creative Commons Attribution 3.0 Unported', "wrong license name") # and now let's go to track/view/1 from c3sar.views.track import track_view request = testing.DummyRequest() request.matchdict['track_id'] = 1 self.config = testing.setUp(request=request) result = track_view(request)
def test_track_add_license_submit_by_nc_sa_de(self): """ track add license & submit: cc-by-nc-sa-de""" from c3sar.views.track import track_add_license # add a track track1 = self._makeTrack() self.dbsession.add(track1) self.dbsession.flush() request = testing.DummyRequest( post={'form.submitted': True, u'cc_js_want_cc_license': u'sure', u'cc_js_share': u'1', u'cc_js_remix': u'', u'cc_js_nc': u'1', u'cc_js_jurisdiction': u'de', u'cc_js_result_uri': u'http://creativecommons.org/licenses/by-nc-sa/3.0/', u'cc_js_result_img': u'http://i.creativecommons.org/l/by-nc-sa/3.0/88x31.png', u'cc_js_result_name': u'Creative Commons Attribution-NonCommercial-ShareAlike 3.0', }) request.matchdict['track_id'] = 1 self.config = testing.setUp(request=request) _registerRoutes(self.config) result = track_add_license(request) if DEBUG: # pragma: no cover pp.pprint(result) # check for redirect self.assertTrue(isinstance(result, HTTPFound), "no redirect") from c3sar.models import Track the_track = Track.get_by_track_id(1) the_license = the_track.license[0] self.assertEquals(the_license.id, 1, "wrong id: should be the only one in database") self.assertEquals( the_license.img, u'http://i.creativecommons.org/l/by-nc-sa/3.0/88x31.png', "wrong license image") self.assertEquals( the_license.uri, u'http://creativecommons.org/licenses/by-nc-sa/3.0/', "wrong license uri") self.assertEquals( the_license.name, u'Creative Commons Attribution-NonCommercial-ShareAlike 3.0', "wrong license name")
def test_get_by_track_name(self): """ testing Track.get_by_track_name() """ if DEBUG: # pragma: no cover print "----- this is TrackModelTests.test_get_by_track_name" instance = self._makeOne() self.session.add(instance) self.session.flush() # to get the id from the db # print "--- type(instance): " + str(type(instance)) # <class 'c3sar.models.Track'> # print "--- instance.id: " + str(instance.id) # 1 from c3sar.models import Track result = Track.get_by_track_name(u'Some Trackname') self.assertEqual(instance.name, result.name, "should have matched.") self.assertEqual(instance.id, result.id, "track ids didn't match!")
def test_get_by_track_id(self): if DEBUG: # pragma: no cover print "----- this is TrackModelTests.test_get_by_track_id" instance = self._makeOne() self.session.add(instance) self.session.flush() # to get the id from the db # print "--- type(instance): " + str(type(instance)) # <class 'c3sar.models.License'> # print "--- dir(instance): " + str(dir(instance)) # ... '_sa_instance_state', 'author', 'get_by_license_id', # 'id', 'license_listing', 'metadata', 'name', 'url' #print "--- instance.id: " + str(instance.id) # 1 from c3sar.models import Track result = Track.get_by_track_id(1) # print "result: " + str(result) # <c3sar.models.Track object at 0x949f74c> # print "result.id: " + str(result.id) # 1 self.assertNotEqual(instance.id, None, "may not be None.") self.assertNotEqual(result.id, None, "may not be None.") self.assertEqual(instance.id, result.id, "track ids didn't match!")
def test_track_listing(self): if DEBUG: # pragma: no cover print "----- this is TrackModelTests.test_track_listing" instance = self._makeOne() self.session.add(instance) self.session.flush() # to get the id from the db # print "--- type(instance): " + str(type(instance)) # <class 'c3sar.models.License'> # print "--- dir(instance): " + str(dir(instance)) # ... '_sa_instance_state', 'author', 'get_by_license_id', # 'id', 'license_listing', 'metadata', 'name', 'url' # print "--- instance.id: " + str(instance.id) # 1 from c3sar.models import Track result = Track.track_listing(order_by="NotImplemented") # print "--- result: " + str(result) # [<c3sar.models.License object at 0x9fba10c>] # print "--- dir(result): " + str(dir(result)) # # print "--- test_track_listing: result.__len__(): " # + str(result.__len__()) # 1 self.assertEqual(result.__len__(), 1, "we expect the result list to have one entry")
def test_track_add_license_submit_all_rights_reserved(self): """ track add license & submit: allrights reserved""" from c3sar.views.track import track_add_license # add a track track1 = self._makeTrack() self.dbsession.add(track1) self.dbsession.flush() request = testing.DummyRequest( post={'form.submitted': True, u'cc_js_want_cc_license': u'nah', u'cc_js_share': u'1', u'cc_js_jurisdiction': u'de', u'cc_js_result_uri': u'', u'cc_js_result_img': u'', u'cc_js_result_name': u'No license chosen', }) request.matchdict['track_id'] = 1 self.config = testing.setUp(request=request) _registerRoutes(self.config) result = track_add_license(request) if DEBUG: # pragma: no cover pp.pprint(result) # check for redirect self.assertTrue(isinstance(result, HTTPFound), "no redirect") from c3sar.models import Track the_track = Track.get_by_track_id(1) the_license = the_track.license[0] self.assertEquals(the_license.id, 1, "wrong id: should be the only one in database") self.assertEquals(the_license.img, u'', "wrong license image") self.assertEquals(the_license.uri, u'', "wrong license uri") self.assertEquals(the_license.name, u'All rights reserved', "wrong license name")
def track_edit(request): track_id = request.matchdict['track_id'] track = Track.get_by_track_id(track_id) if track is None: msg = "Track was not found in database!" request.session.flash("Track was not found in database!") return HTTPFound(route_url('not_found', request)) form = Form(request, schema=TrackEditSchema, obj=track) if 'form.submitted' in request.POST and not form.validate(): request.session.flash('form does not validate. check errors below!') if 'form.submitted' in request.POST and form.validate(): if form.data['name'] != track.name: track.name = form.data['name'] if DEBUG: # pragma: no cover print "changing track name" request.session.flash('changing track name') if form.data['album'] != track.album: track.album = form.data['album'] if DEBUG: # pragma: no cover print "changing track album" request.session.flash('changing track album') if form.data['url'] != track.url: track.url = form.data['url'] if DEBUG: # pragma: no cover print "changing track url" request.session.flash('changing track url') # TODO: trigger url_verification process #request.session.flash(u'writing to database ...') dbsession.flush() # if all went well, redirect to track view return HTTPFound(route_url('track_view', request, track_id=track.id)) return {'form': FormRenderer(form)}
def test_track_edit_set_new_values(self): """edit track -- submit valid data through form""" from c3sar.views.track import track_edit # add a track track1 = self._makeTrack() self.dbsession.add(track1) self.dbsession.flush() request = testing.DummyRequest( post={'form.submitted': True, 'name': u"changed track name", 'album': u'changed album name', 'url': u"http://totally.different.url"} ) request.matchdict['track_id'] = 1 self.config = testing.setUp(request=request) _registerRoutes(self.config) result = track_edit(request) if DEBUG: # pragma: no cover pp.pprint(result) #pp.pprint(result.headers[2]) # check for redirect self.assertTrue(isinstance(result, HTTPFound), "no redirect seen") self.assertTrue('track/view/1' in str(result.headers), "wrong redirect seen") # compare submitted data with track from database from c3sar.models import Track db_track = Track.get_by_track_id(1) self.assertEquals(db_track.name, u"changed track name", "data mismatch") self.assertEquals(db_track.album, u"changed album name", "data mismatch") self.assertEquals(db_track.url, u"http://totally.different.url", "data mismatch")
def __getitem__(self, key): track = Track.get_by_track_id(key) track.__parent__ = self track.__name__ = key return track
def track_add(request): viewer_username = authenticated_userid(request) # if hasattr(request, user): # viewer_username = request.user.username if viewer_username == "": # pragma: no cover viewer_username = "******" form = Form(request, TrackSchema) if DEBUG: # pragma: no cover if 'form.submitted' in request.POST: if 'track_name' in form.data: print "track_name : " + form.data['track_name'] if 'track_album' in form.data: print "track_album: " + form.data['track_album'] if 'track_url' in form.data: print "track_url : " + form.data['track_url'] if 'track_upload' in form.data: print "track_upload : " + form.data['track_upload'] print "track_upload.filename : " + form.data['track_upload'].filename print "track_upload.file : " + form.data['track_upload'].file if 'form.submitted' in request.POST and not form.validate(): # form didn't validate request.session.flash('form does not validate!') if 'form.submitted' in request.POST and form.validate(): request.session.flash('form validated!') # some defaults file_path = '' # where the file is stored (incl. name) output_file_size = None # the size of the file if DEBUG: # pragma: no cover print "---- form.data: ----" pp.pprint(form.data) print "---- request.POST['track_file']: ----" if 'track_upload' in request.POST: pp.pprint(request.POST['track_upload']) pp.pprint(request.POST['track_upload'].filename) pp.pprint(request.POST['track_upload'].file) #request.POST['track_upload'] FieldStorage(u'track_upload', u'blahblah.mp3') #request.POST['track_upload'].filename u'blahblah.mp3' #request.POST['track_upload'].file <open file '<fdopen>', mode 'w+b' at ...> else: print "no 'track_upload' in request.POST" # check if the form contained a file and if yes.... if 'track_upload' in form.data and form.data['track_upload'] != '': # https://docs.pylonsproject.org/projects/ # pyramid_cookbook/dev/files.html#basic-file-uploads # # ``filename`` contains the name of the file in string format. # #WARNING: this example does not deal with the fact that IE sends an # absolute file *path* as the filename. This example is naive; it # trusts user input. file_name = sanitize_filename( request.POST['track_upload'].filename) # ``input_file`` contains the actual file data which needs to be # stored somewhere. input_file = request.POST['track_upload'].file # Using the filename like this without cleaning it is very # insecure so please keep that in mind when writing your own # file handling. TODO !!! if DEBUG: # pragma: no cover print "=== current working dir: " + os.path.abspath('.') print "=== upload target dir: " + os.path.abspath('tracks') # prepare to save the file the_cwd = os.path.abspath('.') file_dir = os.path.join(the_cwd, 'tracks') # create a directory for tracks on the filesystem if not os.path.exists(file_dir): os.makedirs(file_dir) # pragma: no cover file_path = os.path.join(file_dir, file_name) try: output_file = open(file_path, 'wb') # Finally write the data to the output file input_file.seek(0) while True: data = input_file.read(8192) if not data: break output_file.write(data) # determining filesize output_file_size = os.path.getsize(file_path) output_file.close() request.session.flash('file was saved') # return Response('OK') except IOError, ioerr: # pragma: no cover print "==== got an error ====" print ioerr print "something failed." dbsession = DBSession() # if file_path.startswith('c3sar/'): # file_path = file_path.replace('c3sar/', '') track = Track( name=unicode(form.data['track_name']), album=unicode(form.data['track_album']), url=unicode(form.data['track_url']), filepath=unicode(file_path), bytesize=output_file_size, ) track.registrar_id = viewer_username dbsession.add(track) dbsession.flush() # ToDo: send mail... redirect_url = route_url('track_view', request, track_id=track.id) return HTTPFound(location=redirect_url)
def track_list(request): tracks = Track.track_listing(Track.id.desc()) return {'tracks': tracks}
def track_view(request): if DEBUG: # pragma: no cover print "============ T R A C K == V I E W ==========================" id = request.matchdict['track_id'] track = Track.get_by_track_id(id) # import pdb; pdb.set_trace() # redirect if id does not exist in database if not isinstance(track, Track): msg = "the track does not exist in the database!" return HTTPFound(route_url('not_found', request)) # try: # print "== track.id: " + str(track.id) # print "== track.license.__len__(): " + str(track.license.__len__()) # except AttributeError, a: # #'NoneType' object has no attribute 'license' # print "== AttributeError: " # print a # here we should redirect to NotFound or give some info #calculate for next/previous-navigation max_id = Track.get_max_id() # previous if track.id == 1: # if looking at first id prev_id = max_id # --> choose highest db row else: # if looking at any other id prev_id = track.id - 1 # --> choose previous # next if track.id != max_id: # if not on highest id next_id = track.id + 1 # --> choose next elif track.id == max_id: # if highest id next_id = 1 # --> choose first id ('wrap around')) # show who is watching. maybe we should log this ;-) viewer_username = authenticated_userid(request) #request.session.flash( # "track.license.__len__(): " + str(track.license.__len__())) #request.session.flash("track.license.name: " + track.license[0].name) #request.session.flash(track.license.__len__()) # type(track.license) is <class 'sqlalchemy.orm.collections.InstrumentedList'> if track.license.__len__() == 0: track_is_licensed = False license = License(name=u"All Rights Reserved.", uri=u"", img=u"", author=u"default license") #request.session.flash("track_is_licensed: " + str(track_is_licensed)) else: track_is_licensed = True license = track.license[0] #request.session.flash("track_is_licensed: " + str(track_is_licensed)) #request.session.flash( # "track.license.name: " + str(track.license[0].img)) if DEBUG: # pragma: no cover print "str(type(track.license)): " + str(type(license)) print "str(dir(track.license)): " + str(dir(license)) # print "str(help(track.license.pop())): " # + str(help(track.license.pop())) print "str(type(license)): " + str(type(license)) # print "str(type(license.name)): " + str(type(license.name)) # print str(dir(license)) # print str(license.name) return { 'track': track, 'track_is_licensed': track_is_licensed, 'license': license, 'viewer_username': viewer_username, 'prev_id': prev_id, 'id': id, 'next_id': next_id }
def track_add_license(request): # which one? id = request.matchdict['track_id'] track = Track.get_by_track_id(id) # license = track.license[1] # request.session.flash(track.license[0]) # request.session.flash(track.license[1]) # who is doing this? viewer_username = authenticated_userid(request) form = Form(request) if 'form.submitted' in request.POST: request.session.flash("And this is request.POST") request.session.flash(request.POST) my_results_dict = request.POST #request.session.flash(my_results_dict.keys()) #pp.pprint(my_results_dict) if 'cc_js_want_cc_license' in my_results_dict: if DEBUG: # pragma: no cover print "=====" pp.pprint(my_results_dict.keys()) pp.pprint(my_results_dict['cc_js_want_cc_license']) # request.session.flash("cc license? " # + my_results_dict['cc_js_want_cc_license']) # request.session.flash(my_results_dict['cc_js_result_uri']) # request.session.flash(my_results_dict['cc_js_result_img']) # request.session.flash(my_results_dict[u'cc_js_result_name']) if (my_results_dict['cc_js_want_cc_license'] == 'sure'): request.session.flash("we got a cc license...") # track.license = [ # License( # name = my_results_dict['cc_js_result_name'], # uri = my_results_dict['cc_js_result_uri'], # img = my_results_dict['cc_js_result_img'], # author = viewer_username # ) # ] track.license.append(License( name=my_results_dict['cc_js_result_name'], uri=my_results_dict['cc_js_result_uri'], img=my_results_dict['cc_js_result_img'], author=viewer_username ) ) # dbsession.add(license) # no, add via track # dbsession.add(track) # no, don't add, just update request.session.flash(u'writing to database ... by flush') dbsession.flush() elif (my_results_dict['cc_js_want_cc_license'] == 'nah'): request.session.flash("got an all rights reserved license...") track.license.append(License( name=u'All rights reserved', uri=u'', img=u'', author=viewer_username )) request.session.flash(u'writing to database ... by flushing') dbsession.flush() # redirect to license_view redirect_url = route_url('track_view', request, track_id=str(track.id)) # + str(track.id) from pyramid.httpexceptions import HTTPFound return HTTPFound(location=redirect_url) return { 'viewer_username': viewer_username, 'track_id': id, 'track': track, 'license': license, 'form': FormRenderer(form) }