def test_confirm_submission_success_noaction_withpom(self): userobj = User.objects.create_user(username='******', password='******', is_superuser=True) userobj.save() jarfile = SimpleUploadedFile('SomeApp-1.0.0.jar', b'data', content_type='application/zip') pending = views._create_pending(userobj, 'SomeApp', '1.0.0', 'workswith', [], jarfile) testpomfile = SimpleUploadedFile('pom.xml', PomParseTest.get_valid_pom_as_bytes(), content_type='text/xml') testpomfile.open(mode='r') pending.pom_xml_file.save(os.path.basename(testpomfile.name), testpomfile) testpomfile.close() res = self.client.login(username='******', password='******') self.assertTrue(res) response = self.client.post('/submit_app/confirm/' + str(pending.id), follow=True) self.assertEqual(200, response.status_code) self.assertTrue(b'Cytoscape App Store - ' b'Confirm Submission' in response.content) self.assertTrue(b'es.imim' in response.content) self.assertTrue(b'DisGeNET' in response.content) self.assertTrue(b'6.3.2' in response.content)
class AttachmentModelTest(TestCase): def setUp(self): self.test_image = SimpleUploadedFile( name='testimage.jpg', content=open(TEST_IMAGE_1, 'rb').read(), content_type='image/jpeg' ) def tearDown(self): self.test_image.close() try: if os.path.isdir(settings.TEST_MEDIA_ROOT): shutil.rmtree(settings.TEST_MEDIA_ROOT) except Exception as e: print(e) def test_save(self): attachment = Attachment.objects.create(image=self.test_image) self.assertIsNotNone(attachment.md5sum) self.assertEqual(attachment.filename, 'testimage.jpg') self.assertIsInstance(attachment, Attachment) def test_upload_to(self): attachment = Attachment(image=self.test_image, md5sum='abc') returned_upload_to = upload_to(attachment, attachment.filename) expected_upload_to = 'uploads/%s' % 'abc' self.assertEqual(returned_upload_to, expected_upload_to) def test_upload_to_with_avatar(self): attachment = Attachment( image=self.test_image, md5sum='abc', is_avatar=True ) returned_upload_to = upload_to(attachment, attachment.filename) expected_upload_to = 'avatars/%s' % 'abc' self.assertEqual(returned_upload_to, expected_upload_to)
def test_verify_javadocs_jar_invalid_zip(self): testzipfile = SimpleUploadedFile('javadoc.jar', b'invalidzip', content_type='application/zip') testzipfile.open(mode='rb') res = views._verify_javadocs_jar(testzipfile) self.assertTrue('not a valid jar' in res) testzipfile.close()
def test_tag_printfile_closedfile(self): template = "{{ my_file|print_file_content }}" my_file = SimpleUploadedFile("foo.txt", b"foo") my_file.close() context = {"my_file": my_file} output = u"" t = Template('{% load contest_extras %}' + template) c = Context(context) self.assertEqual(t.render(c), output)
def test_detect_file_value(self): val = SimpleUploadedFile("sample_invalid_image.jpg", b"file_content", content_type="image/jpeg") default_storage.save(val.name, val) val.close() self.event.settings.set('test', val) self.event.settings._flush() f = self.event.settings.get('test', as_type=File) self.assertIsInstance(f, File) self.assertTrue(f.name.endswith(val.name)) f.close()
def file_fixture(test_file_path, file_path_after_save=None): with open(test_file_path, 'rb') as f: f.seek(0) uploaded_file = SimpleUploadedFile(f.name, f.read()) yield uploaded_file uploaded_file.close() if (file_path_after_save is not None and os.path.exists(file_path_after_save)): os.remove(file_path_after_save)
def test_autodetect_file_value_of_parent(self): val = SimpleUploadedFile("sample_invalid_image.jpg", b"file_content", content_type="image/jpeg") default_storage.save(val.name, val) val.close() self.organizer.settings.set('test', val) self.organizer.settings._flush() f = self.event.settings.get('test') self.assertIsInstance(f, File) self.assertTrue(f.name.endswith(val.name)) f.close()
def test_unserialize_file_value(self): val = SimpleUploadedFile("sample_invalid_image.jpg", b"file_content", content_type="image/jpeg") default_storage.save(val.name, val) val.close() self.user.settings.set('test', val) self.user.settings.flush() f = self.user.settings.get('test', as_type=File) self.assertIsInstance(f, File) self.assertTrue(f.name.endswith(val.name)) f.close()
class OrganisationTests(APITestCase): """ Test Organisation model. """ def setUp(self): """ Initialize variables. """ self.user = create_user() self.logo = SimpleUploadedFile('logo.jpg', b'JPG IMAGE') self.organisation_name = 'Organisation Name' self.organisation_description = 'Organisation Description' self.organisation = Organisation( user=self.user, logo=self.logo, name=self.organisation_name, description=self.organisation_description ) def tearDown(self): """ Close open files. """ self.logo.close() def test_organisation_created(self): """ Test an organisation instance is created correctly, given all the data. """ self.organisation.save() organisation_instance = Organisation.objects.get(pk=1) self.assertEqual( # Compare file like objects(logos) organisation_instance.logo.read(), self.organisation.logo.read(), 'Organisation logo\'s don\'t match.' ) self.assertEqual( organisation_instance.user, self.organisation.user, 'Users don\'t match.' ) self.assertEqual( organisation_instance.name, self.organisation.name, 'Organisation name\'s don\'t match.' ) self.assertEqual( organisation_instance.description, self.organisation.description, 'Organisation description\'s don\'t match.' )
def setUpTestData(self): testdoc = SimpleUploadedFile('testdocument.docx', b'', content_type='text/plain') self.doc = Document.objects.create(name='Document1', upload=testdoc) self.doc.save() self.dcpage = DocPage.objects.create(name='Info', slug='info', text='Created new text') self.dcpage.files.add(self.doc) self.dcpage.save() testdoc.close()
class UploadZipViewTest(TestCase): """ Contains unit tests for the UploadZipView. """ def setUp(self): """ This method is called before each test and is responsible for setting up data needed by the tests. """ super(UploadZipViewTest, self).setUp() # create a client for html requests self.client = Client() # open a file and create a file object tmp_file = open(os.path.join(os.path.dirname(__file__), 'autoscottytest-7613.zip'), 'rb') self.zip_file = SimpleUploadedFile(tmp_file.name, tmp_file.read()) # reset the file and create a hash, then close the file tmp_file.seek(0) self.hash = hashlib.sha1() self.hash.update(tmp_file.read()) tmp_file.close() def tearDown(self): """ This method is called after a test runs. It does any cleanup necessary, such as closing files. """ if self.zip_file: self.zip_file.close() def test_invalid_form(self): """ Makes requests with invalid data and ensures the proper response codes and context errors are returned. """ # test no data response = self.client.post(reverse('autoscotty_upload')) self.assertEqual(400, response.status_code) self.assertEqual(response.context['form']['zip_file'].errors, [u'This field is required.']) self.assertEqual(response.context['form']['zip_file_hash'].errors, [u'This field is required.']) # test hash mismatch kwargs = {'zip_file': self.zip_file, 'zip_file_hash': 'abc', 'sync': True} response = self.client.post(reverse('autoscotty_upload'), kwargs) self.assertEqual(460, response.status_code) self.assertEqual(response.context['form'].errors['hash_mismatch'], [u'The hash does not match the file.']) def test_valid_form(self): """ Performs a request with a valid form and checks for the proper response. """ kwargs = {'zip_file': self.zip_file, 'zip_file_hash': self.hash.hexdigest(), 'sync': False, 'model_type': 'EMOD'} response = self.client.post(reverse('autoscotty_upload'), kwargs) self.assertEqual(200, response.status_code)
class GeometryFileFieldTestCase(SimpleTestCase): def setUp(self): self.field = GeometryFileField() self.fp = SimpleUploadedFile('geom.json', json.dumps(_geom).encode('ascii')) self.fp.seek(0) def test_to_python(self): self.assertIsInstance(self.field.to_python(self.fp), OGRGeometry) fp = SimpleUploadedFile('empty.json', b'{}') self.assertRaises(forms.ValidationError, self.field.to_python, fp) def test_feature_to_python(self): feature = Feature(geometry=_geom) self.fp.write(str(feature).encode('ascii')) self.fp.seek(0) v = self.field.to_python(self.fp) self.assertIsInstance(v, OGRGeometry) def test_shapefile(self): base = 'dir/geofield.shp' path = default_storage.path(base) os.mkdir(os.path.dirname(path)) write_shp(path, _geom) b = io.BytesIO() with zipfile.ZipFile(b, 'w') as zf: for ext in ('dbf', 'prj', 'shp', 'shx'): fname = base.replace('shp', ext) with default_storage.open(fname) as fp: zf.writestr(fname, fp.read()) shutil.rmtree(os.path.dirname(path)) upfile = SimpleUploadedFile('geofield.zip', b.getvalue()) b.close() result = self.field.to_python(upfile) self.assertIsInstance(result, OGRGeometry) self.assertIsNotNone(result.srs) def test_zipfile(self): zfile = io.BytesIO() with zipfile.ZipFile(zfile, 'w') as zf: zf.writestr(self.fp.name, self.fp.read()) zfile.seek(0) upfile = SimpleUploadedFile('geofield.zip', zfile.read()) zfile.close() self.assertIsInstance(self.field.to_python(upfile), OGRGeometry) def tearDown(self): self.fp.close()
class GeometryFileFieldTestCase(SimpleTestCase): def setUp(self): self.field = GeometryFileField() self.fp = SimpleUploadedFile( 'geom.json', json.dumps(_geom).encode('ascii')) self.fp.seek(0) def test_to_python(self): self.assertIsInstance(self.field.to_python(self.fp), OGRGeometry) fp = SimpleUploadedFile('empty.json', b'{}') self.assertRaises(forms.ValidationError, self.field.to_python, fp) def test_feature_to_python(self): feature = Feature(geometry=_geom) self.fp.write(str(feature).encode('ascii')) self.fp.seek(0) v = self.field.to_python(self.fp) self.assertIsInstance(v, OGRGeometry) def test_shapefile(self): base = 'dir/geofield.shp' path = default_storage.path(base) os.mkdir(os.path.dirname(path)) write_shp(path, _geom) b = io.BytesIO() with zipfile.ZipFile(b, 'w') as zf: for ext in ('dbf', 'prj', 'shp', 'shx'): fname = base.replace('shp', ext) with default_storage.open(fname) as fp: zf.writestr(fname, fp.read()) shutil.rmtree(os.path.dirname(path)) upfile = SimpleUploadedFile('geofield.zip', b.getvalue()) b.close() result = self.field.to_python(upfile) self.assertIsInstance(result, OGRGeometry) self.assertIsNotNone(result.srs) def test_zipfile(self): zfile = io.BytesIO() with zipfile.ZipFile(zfile, 'w') as zf: zf.writestr(self.fp.name, self.fp.read()) zfile.seek(0) upfile = SimpleUploadedFile('geofield.zip', zfile.read()) zfile.close() self.assertIsInstance(self.field.to_python(upfile), OGRGeometry) def tearDown(self): self.fp.close()
def _regenerate_thumbnails(self, wallpaper): wallpaper.thumbnails.all().delete() thumbnail_file = create_thumbnail( image_file=wallpaper.file, file_extension=wallpaper.extension ) thumb_file = SimpleUploadedFile( name='t_{}.{}'.format(str(uuid.uuid4()), wallpaper.extension), content=thumbnail_file, ) Thumbnail(wallpaper=wallpaper, file=thumb_file).save() thumb_file.close()
def test_verify_javadocs_jar_valid_zip(self): temp_dir = tempfile.mkdtemp() try: temp_zip = os.path.join(temp_dir, 'foo.jar') zf = zipfile.ZipFile(temp_zip, mode='w') zf.writestr('hi.xml', 'somedata') zf.close() with open(temp_zip, 'rb') as f: zipdata = f.read() testzipfile = SimpleUploadedFile('javadoc.jar', zipdata, content_type='application/zip') testzipfile.open(mode='rb') res = views._verify_javadocs_jar(testzipfile) self.assertEqual(None, res) testzipfile.close() finally: shutil.rmtree(temp_dir)
def test_verify_javadocs_jar_with_double_dot_in_file(self): temp_dir = tempfile.mkdtemp() try: temp_zip = os.path.join(temp_dir, 'foo.jar') zf = zipfile.ZipFile(temp_zip, mode='w') zf.writestr('yo/../hi.xml', 'somedata') zf.close() with open(temp_zip, 'rb') as f: zipdata = f.read() testzipfile = SimpleUploadedFile('javadoc.jar', zipdata, content_type='application/zip') testzipfile.open(mode='rb') res = views._verify_javadocs_jar(testzipfile) self.assertTrue('path that is illegal: yo/../hi.xml' in res) testzipfile.close() finally: shutil.rmtree(temp_dir)
def handle(self, *args, **options): if GIFEntry.objects.count() > 1000: self.stdout.write('You already have 1000 gifs in db.') return dir_path = options['dir_path'][0] if os.path.exists(dir_path): for filename in glob.glob(os.path.join(dir_path, '*.gif')): with open(filename, 'rb') as f: f.seek(0) inmemory_file = SimpleUploadedFile(filename, f.read()) gif_entry = GIFEntry( title=secrets.token_hex(nbytes=16), author=get_user_model().objects.get(username='******'), gif_file=inmemory_file, ) gif_entry.save() gif_entry.tags.add('funny', 'animals', 'dogs') inmemory_file.close() self.stdout.write('Gifs created.') else: raise CommandError('Directory not exists.')
def do_upload(self, chunk_number, data_size, read_data, file_name, batch_id=None): """ custom upload function """ uploaded_chunk = SimpleUploadedFile(file_name, read_data, content_type='multipart/form-data') data = { 'resumable_chunk_number': chunk_number, 'resumable_chunk_size': self.chunk_size, 'resumable_identifier': '%s-%s' % (self.file_size, file_name), 'resumable_total_size': self.file_size, 'resumable_current_chunk_size': data_size, 'resumable_filename': file_name, 'resumable_total_chunks': self.total_chunks, 'batch_id': batch_id, } data['file'] = uploaded_chunk response = self.client.post('/api/v1/uploads/' % VERSION, data, format='multipart') json_response = response.json() LOG.info(json_response) if json_response['data']['created'] is True: self.assertEqual(response.status_code, 201) else: self.assertEqual(response.status_code, 200) uploaded_chunk.close() return response
class ImageUploadViewTest(TestCase): def setUp(self): self.user = self.make_user('testuser1') self.upload_url = reverse('attachments:upload_img') self.test_image = SimpleUploadedFile(name='testimage.jpg', content=open(TEST_IMAGE_1, 'rb').read(), content_type='image/jpeg') self.test_image2 = SimpleUploadedFile(name='aprf1.jpg', content=open(TEST_IMAGE_2, 'rb').read(), content_type='image/jpeg') self.test_image3 = SimpleUploadedFile(name='Chrysanthemum.jpg', content=open(TEST_IMAGE_3, 'rb').read(), content_type='image/jpeg') def tearDown(self): self.test_image.close() self.test_image2.close() try: if os.path.isdir(settings.TEST_MEDIA_ROOT): shutil.rmtree(settings.TEST_MEDIA_ROOT) except Exception as e: print(e) def test_post_with_authenticated_user_without_ajax(self): login(self, self.user, 'password') data = {'image': self.test_image} response = self.client.post(self.upload_url, data) self.assertEqual(response.status_code, 400) self.assertEqual(Attachment.objects.count(), 0) def test_post_with_anonymous_user_with_ajax(self): data = {'image': self.test_image} response = self.client.post(self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 302) self.assertEqual(Attachment.objects.count(), 0) def test_404_for_production(self): current_count = Attachment.objects.count() login(self, self.user, 'password') data = {'image': self.test_image} with self.settings(DEBUG=False): response = self.client.post(self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 404) self.assertEqual(Attachment.objects.count(), current_count) def test_post_with_authenticated_user_with_ajax(self): current_count = Attachment.objects.count() login(self, self.user, 'password') data = {'image': self.test_image} response = self.client.post(self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertEqual(Attachment.objects.count(), current_count + 1) def test_post_with_duplicate_images(self): current_count = Attachment.objects.count() login(self, self.user, 'password') data = {'image': self.test_image} first_response = self.client.post( self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(first_response.status_code, 200) second_response = self.client.post( self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(second_response.status_code, 200) self.assertEqual(Attachment.objects.count(), current_count + 1) path, dirs, files = next(os.walk(IMAGE_UPLOAD_DIR)) self.assertEqual(len(files), 1) def test_post_with_two_images(self): current_count = Attachment.objects.count() login(self, self.user, 'password') data = {'image': self.test_image} first_response = self.client.post( self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(first_response.status_code, 200) data2 = {'image': self.test_image2} second_response = self.client.post( self.upload_url, data2, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(second_response.status_code, 200) self.assertEqual(Attachment.objects.count(), current_count + 2) path, dirs, files = next(os.walk(IMAGE_UPLOAD_DIR)) self.assertEqual(len(files), 2) def test_with_empty_data(self): login(self, self.user, 'password') data = {} response = self.client.post(self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertFalse(response.json()['is_valid']) self.assertEqual(response.json()['message'], 'This field is required.') def test_with_invalid_data(self): login(self, self.user, 'password') data = {'image': ''} response = self.client.post(self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) attachment_qs = Attachment.objects.filter(image='') self.assertFalse(attachment_qs.exists()) self.assertFalse(response.json()['is_valid']) self.assertEqual(response.json()['message'], 'This field is required.') def test_with_large_image(self): login(self, self.user, 'password') data = {'image': self.test_image3} response = self.client.post(self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertEqual(Attachment.objects.count(), 0) self.assertFalse(response.json()['is_valid']) message = 'File too large. Size should not exceed 500 KB.' self.assertEqual(response.json()['message'], message) def test_with_valid_data(self): login(self, self.user, 'password') data = {'image': self.test_image} response = self.client.post(self.upload_url, data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) attachment_qs = Attachment.objects.filter( image=response.json()['name']) self.assertTrue(response.json()['is_valid']) self.assertTrue(attachment_qs.exists())
class CVResumeTests(APITestCase): """ Tests CVResume model. """ def setUp(self): self.user = create_user() # Create a file like objects representing uploaded data self.cv = SimpleUploadedFile('my_cv.pdf', b'Impresive CV') self.resume = SimpleUploadedFile('my_resume.pdf', b'Impresive Resume') def tearDown(self): """ Close open files. """ self.cv.close() self.resume.close() def test_cv_created(self): """ Test whether a cv is saved correctly. """ # Pass a cv file object to CVResume to save to db/disk CVResume.objects.create( user=self.user, cv=self.cv ) self.cv.open() # Reopen the cv object - set seek to 0 cv_resume = CVResume.objects.get(pk=1) self.assertEqual( self.cv.read(), cv_resume.cv.read(), # Compare file like objects 'Created cv does not match the provided one.' ) def test_resume_created(self): """ Test whether a resume is saved correctly. """ # Pass a resume file object to CVResume to save to db/disk CVResume.objects.create( user=self.user, resume=self.resume ) self.resume.open() # Reopen the resume object - set seek to 0 cv_resume = CVResume.objects.get(pk=1) self.assertEqual( self.resume.read(), cv_resume.resume.read(), # Compare file like objects 'Created reusme does not match the provided one.' ) def test_cv_and_resume_created(self): """ Test whether both cv and resume are saved correctly. """ CVResume.objects.create( user=self.user, cv=self.cv, resume=self.resume ) # Set file positions to the begining self.cv.open() self.resume.open() # Retrieve the saved object cv_resume = CVResume.objects.get(pk=1) # Check if cv match self.assertEqual( self.cv.read(), cv_resume.cv.read(), # Compare file like objects 'Created cv does not match the provided one.' ) # Check if resume match self.assertEqual( self.resume.read(), cv_resume.resume.read(), # Compare file like objects 'Created reusme does not match the provided one.' )
def _save_FIELD_file(self, field, filename, raw_field, save=True): # Create the upload directory if it doesn't already exist directory = os.path.join(settings.MEDIA_ROOT, field.get_directory_name()) if not os.path.exists(directory): os.makedirs(directory) elif not os.path.isdir(directory): raise IOError('%s exists and is not a directory' % directory) # Check for old-style usage (files-as-dictionaries). Warn here first # since there are multiple locations where we need to support both new # and old usage. if isinstance(raw_field, dict): import warnings warnings.warn( message= "Representing uploaded files as dictionaries is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.", category=DeprecationWarning, stacklevel=2) from django.core.files.uploadedfile import SimpleUploadedFile raw_field = SimpleUploadedFile.from_dict(raw_field) elif isinstance(raw_field, str): import warnings warnings.warn( message= "Representing uploaded files as strings is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.", category=DeprecationWarning, stacklevel=2) from django.core.files.uploadedfile import SimpleUploadedFile raw_field = SimpleUploadedFile(filename, raw_field) if filename is None: filename = raw_field.file_name filename = field.get_filename(filename) # If the filename already exists, keep adding an underscore to the name # of the file until the filename doesn't exist. while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)): try: dot_index = filename.rindex('.') except ValueError: # filename has no dot. filename += '_' else: filename = filename[:dot_index] + '_' + filename[dot_index:] # Save the file name on the object and write the file to disk. setattr(self, field.attname, filename) full_filename = self._get_FIELD_filename(field) if hasattr(raw_field, 'temporary_file_path'): # This file has a file path that we can move. raw_field.close() file_move_safe(raw_field.temporary_file_path(), full_filename) else: # This is a normal uploadedfile that we can stream. fp = open(full_filename, 'wb') locks.lock(fp, locks.LOCK_EX) for chunk in raw_field.chunks(): fp.write(chunk) locks.unlock(fp) fp.close() # Save the width and/or height, if applicable. if isinstance(field, ImageField) and \ (field.width_field or field.height_field): from django.utils.images import get_image_dimensions width, height = get_image_dimensions(full_filename) if field.width_field: setattr(self, field.width_field, width) if field.height_field: setattr(self, field.height_field, height) # Save the object because it has changed, unless save is False. if save: self.save()
class UserModelTest(TestCase): def setUp(self): self.user = self.make_user('test_user1') self.test_avatar = SimpleUploadedFile( name='aprf1.jpg', content=open(TEST_AVATAR_1, 'rb').read(), content_type='image/jpeg' ) def tearDown(self): self.test_avatar.close() try: if os.path.isdir(settings.TEST_MEDIA_ROOT): shutil.rmtree(settings.TEST_MEDIA_ROOT) except Exception as e: print(e) def test_str_(self): self.assertEqual(self.user.__str__(), self.user.username) def test_is_online(self): self.user.last_seen = timezone.now() self.assertTrue(self.user.is_online()) def test_is_online_with_below_10_minutes(self): self.user.last_seen = timezone.now() - timedelta(seconds=10*60) self.assertFalse(self.user.is_online()) def test_is_owner(self): user = User.objects.get(username='******') self.assertTrue(self.user.is_owner(user)) def test_not_owner(self): second_user = self.make_user('testuser2') self.assertFalse(self.user.is_owner(second_user)) def test_is_required_filter_with_owner(self): user = User.objects.get(username='******') for filter_str in ['following', 'new']: self.assertTrue( self.user.is_required_filter_owner(user, filter_str) ) def test_is_required_filter_with_not_owner(self): second_user = self.make_user('testuser2') for filter_str in ['following', 'new']: self.assertFalse( self.user.is_required_filter_owner(second_user, filter_str) ) def test_get_avatar_url_with_avatar(self): url = Attachment.objects.create_avatar(self.test_avatar, self.user) self.user.avatar_url = url self.user.save() self.assertEqual(self.user.get_avatar_url(), url) def test_get_avatar_url_without_avatar(self): self.assertEqual(self.user.get_avatar_url(), '/static/img/avatar.svg') def test_update_notification_info(self): request = RequestFactory() request.user = self.user url = '/notification_url_example/' count = 99 self.user.update_notification_info(request, url, count) self.assertEqual(request.user.notif_url, url) self.assertEqual(request.user.notif_count, count) def test_toggle_followers_with_new_follower(self): second_user = self.make_user('testuser2') self.user.toggle_followers(second_user) self.assertIn(second_user, self.user.followers.all()) self.assertNotIn(self.user, second_user.followers.all()) def test_toggle_followers_with_existing_follower(self): second_user = self.make_user('testuser2') self.user.followers.add(second_user) self.user.toggle_followers(second_user) self.assertNotIn(second_user, self.user.followers.all()) def test_get_absolute_url(self): url = '/accounts/%s/' % self.user.username self.assertEqual(self.user.get_absolute_url(), url) def test_get_user_follow_url(self): url = '/accounts/%s/follow/' % self.user.username self.assertEqual(self.user.get_user_follow_url(), url) def test_get_userprofile_update_url(self): url = '/accounts/%s/info/' % self.user.username self.assertEqual(self.user.get_userprofile_update_url(), url) def test_get_login_url(self): url = '/accounts/auth/login/' self.assertEqual(self.user.get_login_url(), url)
def _save_FIELD_file(self, field, filename, raw_field, save=True): # Create the upload directory if it doesn't already exist directory = os.path.join(settings.MEDIA_ROOT, field.get_directory_name()) if not os.path.exists(directory): os.makedirs(directory) elif not os.path.isdir(directory): raise IOError('%s exists and is not a directory' % directory) # Check for old-style usage (files-as-dictionaries). Warn here first # since there are multiple locations where we need to support both new # and old usage. if isinstance(raw_field, dict): import warnings warnings.warn( message = "Representing uploaded files as dictionaries is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.", category = DeprecationWarning, stacklevel = 2 ) from django.core.files.uploadedfile import SimpleUploadedFile raw_field = SimpleUploadedFile.from_dict(raw_field) elif isinstance(raw_field, str): import warnings warnings.warn( message = "Representing uploaded files as strings is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.", category = DeprecationWarning, stacklevel = 2 ) from django.core.files.uploadedfile import SimpleUploadedFile raw_field = SimpleUploadedFile(filename, raw_field) if filename is None: filename = raw_field.file_name filename = field.get_filename(filename) # If the filename already exists, keep adding an underscore to the name # of the file until the filename doesn't exist. while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)): try: dot_index = filename.rindex('.') except ValueError: # filename has no dot. filename += '_' else: filename = filename[:dot_index] + '_' + filename[dot_index:] # Save the file name on the object and write the file to disk. setattr(self, field.attname, filename) full_filename = self._get_FIELD_filename(field) if hasattr(raw_field, 'temporary_file_path'): # This file has a file path that we can move. raw_field.close() file_move_safe(raw_field.temporary_file_path(), full_filename) else: # This is a normal uploadedfile that we can stream. fp = open(full_filename, 'wb') locks.lock(fp, locks.LOCK_EX) for chunk in raw_field.chunks(): fp.write(chunk) locks.unlock(fp) fp.close() # Save the width and/or height, if applicable. if isinstance(field, ImageField) and \ (field.width_field or field.height_field): from django.utils.images import get_image_dimensions width, height = get_image_dimensions(full_filename) if field.width_field: setattr(self, field.width_field, width) if field.height_field: setattr(self, field.height_field, height) # Save the object because it has changed, unless save is False. if save: self.save()
class UserProfileEditTest(TestCase): def setUp(self): self.user = self.make_user('testuser1') self.user_edit_url = reverse( 'accounts:user_edit', kwargs={'username': self.user.username} ) self.test_avatar = SimpleUploadedFile( name='aprf1.jpg', content=open(TEST_AVATAR_1, 'rb').read(), content_type='image/jpeg' ) self.test_avatar_copy = SimpleUploadedFile( name='aprf1_copy.jpg', content=open(TEST_AVATAR_1_COPY, 'rb').read(), content_type='image/jpeg' ) self.test_avatar_large = SimpleUploadedFile( name='Chrysanthemum.jpg', content=open(TEST_AVATAR_LARGE, 'rb').read(), content_type='image/jpeg' ) self.valid_data = { 'image': self.test_avatar, 'gender': 'M', 'signature': 'This is a test signature', 'location': 'This is a test location', 'website': 'http://www.example.com' } def tearDown(self): self.test_avatar.close() self.test_avatar_copy.close() self.test_avatar_large.close() try: if os.path.isdir(settings.TEST_MEDIA_ROOT): shutil.rmtree(settings.TEST_MEDIA_ROOT) except Exception as e: print(e) def test_anonymous_user_redirect(self): """An anonymous user should be redirected to the login page""" redirect_url = '%s?next=%s' % ( reverse('accounts:login'), self.user_edit_url ) get_response = self.client.get(self.user_edit_url) self.assertRedirects(get_response, redirect_url) post_response = self.client.post(self.user_edit_url, self.valid_data) self.assertRedirects(post_response, redirect_url) def test_authenticated_user_with_no_permission(self): """ Only comment owner can see the comment edit form and update comment """ redirect_url = '%s?next=%s' % ( reverse('accounts:login'), self.user_edit_url ) second_user = self.make_user('testuser2') login(self, second_user.username, 'password') get_response = self.client.get(self.user_edit_url) self.assertEqual(get_response.status_code, 403) post_response = self.client.post(self.user_edit_url, self.valid_data) self.assertEqual(post_response.status_code, 403) def test_render_for_authenticated_user_with_permission(self): login(self, self.user.username, 'password') response = self.client.get(self.user_edit_url) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['userprofile'], self.user) self.assertEqual( response.context['current_profile_page'], 'settings') self.assertIsInstance(response.context['form'], UserProfileForm) def test_large_image(self): login(self, self.user, 'password') self.valid_data.update({'image': self.test_avatar_large}) data = self.valid_data with self.settings(DEBUG=True): response = self.client.post(self.user_edit_url, data) self.assertEqual(response.status_code, 200) message = 'File too large. Size should not exceed 500 KB.' form = response.context.get('form') self.assertIn(message, form.errors['image']) def test_avatar_not_accepted_in_production(self): login(self, self.user, 'password') with self.settings(DEBUG=False): response = self.client.post(self.user_edit_url, self.valid_data) self.assertEqual(response.status_code, 302) self.assertEqual(Attachment.objects.count(), 0) self.user.refresh_from_db() self.assertEqual(self.user.avatar_url, None) self.assertEqual(self.user.gender, self.valid_data['gender']) self.assertEqual(self.user.signature, self.valid_data['signature']) self.assertEqual(self.user.location, self.valid_data['location']) self.assertEqual(self.user.website, self.valid_data['website']) def test_valid_data_acceptance(self): login(self, self.user, 'password') with self.settings(DEBUG=True): response = self.client.post(self.user_edit_url, self.valid_data) self.assertEqual(response.status_code, 302) self.user.refresh_from_db() self.assertIsNotNone(self.user.avatar_url) self.assertEqual(self.user.gender, self.valid_data['gender']) self.assertEqual(self.user.signature, self.valid_data['signature']) self.assertEqual(self.user.location, self.valid_data['location']) self.assertEqual(self.user.website, self.valid_data['website']) def test_duplicate_images(self): login(self, self.user, 'password') with self.settings(DEBUG=True): response = self.client.post(self.user_edit_url, self.valid_data) self.assertEqual(response.status_code, 302) second_user = self.make_user('testuser2') client = Client() client.login(username=second_user.username, password='******') second_user_edit_url = reverse( 'accounts:user_edit', kwargs={'username': second_user.username} ) self.valid_data.update({'image': self.test_avatar_copy}) data = self.valid_data with self.settings(DEBUG=True): second_response = client.post(second_user_edit_url, data) self.assertEqual(second_response.status_code, 302) self.user.refresh_from_db() second_user.refresh_from_db() self.assertIsNotNone(second_user.avatar_url) self.assertEqual(self.user.avatar_url, second_user.avatar_url)
class ComplaintsTestCase(APITestCase): api_version = 'v1' fixtures = ['complaints', 'entities', 'accounts'] @property def complaint_list_view_name(self): return self.api_version + ':complaint-list' @property def complaint_confirm_view_name(self): return self.api_version + ':complaint-confirm' @property def complaint_clean_view_name(self): return self.api_version + ':complaint-clean' def setUp(self): self.tmp_picture = SimpleUploadedFile(name='logo.jpg', content=image_string, content_type='image/jpeg') self.complaint = { 'owner': 1, 'entity': 1, 'location': json.dumps({ 'type': 'Point', 'coordinates': [11.266675, -74.189093] }), 'picture': self.tmp_picture, } self.cloudinary_image = { 'public_id': 'x2ojoy5hc4x78y3ida1f', 'version': 1496421068, 'signature': '8aa8f1031a19f15023548967ede58b5c7ba94fd2', 'width': 1, 'height': 1, 'format': 'jpg', 'resource_type': 'image', 'created_at': '2017-06-02T16:31:08Z', 'tags': [], 'bytes': 631, 'type': 'upload', 'etag': '2775f338c469b19c338c4e0ea410271c', 'url': 'http://res.cloudinary.com/dsxvepxmc/image/upload/v1496421068/x2ojoy5hc4x78y3ida1f.jpg', 'secure_url': 'https://res.cloudinary.com/dsxvepxmc/image/upload/v1496421068/x2ojoy5hc4x78y3ida1f.jpg', 'original_filename': 'logo' } def tearDown(self): self.tmp_picture.close() def test_list_complaints_unauthenticated(self): """Fetch all the complaints""" response = self.client.get(reverse(self.complaint_list_view_name)) stored_data = json.loads(response.content.decode('utf-8')) self.assertEqual( response.status_code, status.HTTP_200_OK, 'response from {} has 200 Ok.'.format( reverse(self.complaint_list_view_name))) returned_complaint = stored_data['results'][0] self.assertIn('id', returned_complaint, 'Id is not present on the result data') complaint = Complaint.objects.get(pk=returned_complaint['id']) self.assertEqual(complaint.counter, returned_complaint['counter'], 'Name does not match') def test_create_complaint_unauthenticated(self): """Trying to create a complaint being unauthenticated""" response = self.client.post(reverse(self.complaint_list_view_name), self.complaint) self.assertEqual( response.status_code, status.HTTP_401_UNAUTHORIZED, 'response from {} is not 401 Unauthorized.'.format( reverse(self.complaint_list_view_name))) @mock.patch('utils.tasks.share.share_complaint.delay') @mock.patch('cloudinary.uploader.upload') def test_create_complaint_authenticated(self, cloudinary_mock, share_complaint_mock): """Creating a complaint being authenticated""" cloudinary_mock.return_value = self.cloudinary_image share_complaint_mock.return_value = 1 authenticated_user = Account.objects.get( username='******') self.client.force_login(authenticated_user) response = self.client.post(reverse(self.complaint_list_view_name), self.complaint) self.assertEqual( response.status_code, status.HTTP_201_CREATED, 'response from {} is not 201.'.format( reverse(self.complaint_list_view_name))) complaint = Complaint.objects.get(pk=response.data['id']) self.assertIn('location', response.data, 'Location is not being returned.') location = response.data['location'] self.assertIn('http://res.cloudinary.com/', str(response.data['picture'])) self.assertEqual(type(complaint.location), Point) for coordinate in location['coordinates']: self.assertIn(coordinate, complaint.location.coords) @mock.patch('cloudinary.uploader.upload') def test_create_complaint_invalid_cloudinary(self, cloudinary_mock): """Trying to create a complaint being authenticated, but receiving an error from cloudinary""" cloudinary_mock.return_value = {} authenticated_user = Account.objects.get( username='******') self.client.force_login(authenticated_user) response = self.client.post(reverse(self.complaint_list_view_name), self.complaint) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST, 'response from {} is not 400.'.format( reverse(self.complaint_list_view_name))) def test_create_complaint_invalid_point(self): """Trying to create a complaint with an invalid point""" authenticated_user = Account.objects.get( username='******') self.client.force_login(authenticated_user) complaint = self.complaint del complaint['location'] response = self.client.post(reverse(self.complaint_list_view_name), complaint) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST, 'response from {} is not 400.'.format( reverse(self.complaint_list_view_name))) def test_create_complaint_invalid_picture(self): """Trying to create a complaint with an invalid picture""" authenticated_user = Account.objects.get( username='******') self.client.force_login(authenticated_user) complaint = self.complaint complaint['picture'] = 'test' response = self.client.post(reverse(self.complaint_list_view_name), complaint) self.assertEqual( response.status_code, status.HTTP_400_BAD_REQUEST, 'response from {} is not 400.'.format( reverse(self.complaint_list_view_name))) def test_confirm_place_unauthenticated(self): """Trying to confirm a place being unauthenticated""" complaint = Complaint.objects.first() response = self.client.post( reverse(self.complaint_confirm_view_name, kwargs={'pk': complaint.pk})) self.assertEqual( response.status_code, status.HTTP_401_UNAUTHORIZED, 'response from {} is not 401 Unauthorized.'.format( reverse(self.complaint_confirm_view_name, kwargs={'pk': complaint.pk}))) def test_confirm_place_authenticated(self): """Confirm a place being authenticated""" authenticated_user = Account.objects.get( username='******') self.client.force_login(authenticated_user) complaint = Complaint.objects.first() response = self.client.post( reverse(self.complaint_confirm_view_name, kwargs={'pk': complaint.pk})) self.assertEqual( response.status_code, status.HTTP_204_NO_CONTENT, 'response from {} is not 204 No Content.'.format( reverse(self.complaint_confirm_view_name, kwargs={'pk': complaint.pk}))) updated_complaint = Complaint.objects.get(pk=complaint.pk) self.assertGreater(updated_complaint.counter, complaint.counter, 'The counter of the complaint is not updated') self.assertEqual(complaint.current_state, 1, 'The state of the complaint should be Active') def test_clean_place_unauthenticated(self): """Trying to clean a place being unauthenticated""" complaint = Complaint.objects.first() response = self.client.post( reverse(self.complaint_clean_view_name, kwargs={'pk': complaint.pk})) self.assertEqual( response.status_code, status.HTTP_401_UNAUTHORIZED, 'response from {} is not 401 Unauthorized.'.format( reverse(self.complaint_confirm_view_name, kwargs={'pk': complaint.pk}))) def test_clean_place_authenticated(self): """Clean a place being authenticated""" authenticated_user = Account.objects.get( username='******') self.client.force_login(authenticated_user) complaint = Complaint.objects.first() response = self.client.post( reverse(self.complaint_clean_view_name, kwargs={'pk': complaint.pk})) self.assertEqual( response.status_code, status.HTTP_204_NO_CONTENT, 'response from {} is not 204 No Content.'.format( reverse(self.complaint_clean_view_name, kwargs={'pk': complaint.pk}))) updated_complaint = Complaint.objects.get(pk=complaint.pk) self.assertEqual(complaint.counter, updated_complaint.counter, 'The counter of the complaint is different') self.assertNotEqual(complaint.current_state, 2, 'The state of the complaint should be Clean') @mock.patch('utils.social_media.twitter.Twitter.tweet') def test_status_list_success(self, tweet_mock): """ tweet() will return an array of successful tweets """ tweet_status = [123456, 123457] tweet_mock.return_value = tweet_status complaint = Complaint.objects.first() share_complaint(complaint.pk) complaint.refresh_from_db() self.assertEqual(complaint.tweet_status, tweet_status)
class ViewTestCase(APITestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create_user('example', '*****@*****.**') self.token = Token.objects.create(user=self.user) self.mp3_file_invalid = SimpleUploadedFile( './converter/test_files/wav_example.wav', b'file_content') self.mp3_data_invalid = { 'file_name': 'ble', 'file_type': 'wav', 'data_file': self.mp3_file_invalid } self.mp3_file = io.open('./converter/test_files/wav_example.wav', 'rb') self.mp3_data = { 'file_name': 'ble', 'file_type': 'wav', 'data_file': self.mp3_file } self.cover_image = io.open('./converter/test_files/smile.jpg', 'rb') self.cover_image_2 = io.open('./converter/test_files/blee.png', 'rb') def tearDown(self): self.mp3_file_invalid.close() self.mp3_file.close() self.cover_image.close() self.cover_image_2.close() def test_authorization(self): request = self.client.get('/file') self.assertEqual(request.status_code, status.HTTP_401_UNAUTHORIZED) # force_authenticate(request, user=self.user, token = self.user.auth_token) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) request = self.client.get('/file') self.assertEqual(request.status_code, status.HTTP_404_NOT_FOUND) def test_convert_procedure(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) request = self.client.post('/converter', self.mp3_data_invalid) #fail self.assertEqual(request.status_code, status.HTTP_400_BAD_REQUEST) request = self.client.post('/converter', data=self.mp3_data) #create self.assertEqual(request.status_code, status.HTTP_201_CREATED) self.assertEqual(request.content, b'{"id":"1"}') request = self.client.get('/file') #list self.assertEqual(request.status_code, status.HTTP_200_OK) self.assertEqual( request.content, b'[{"id":1,"file_name":"ble","file_type":"mp3","title":""}]') request = self.client.get('/file/1/info') #list self.assertEqual(request.status_code, status.HTTP_200_OK) self.assertEqual( request.content, b'{"file_name":"ble","file_type":"mp3","title":"","artist":"","album":"","year":"","comment":"","track":"","genre":""}' ) info_data = { "title": "bo bo", "artist": "bb", "album": "ble album", "year": "1410", "comment": "nope", "track": 1, "genre": 1 } request = self.client.put('/file/1/info', data=info_data) #update fields self.assertEqual(request.status_code, status.HTTP_204_NO_CONTENT) request = self.client.get('/file/1/info') #get 1 file info self.assertEqual(request.status_code, status.HTTP_200_OK) self.assertEqual( request.content, b'{"file_name":"ble","file_type":"mp3","title":"bo bo","artist":"bb","album":"ble album","year":"1410","comment":"nope","track":"1","genre":"1"}' ) cover_data = {"cover": self.cover_image} request = self.client.put('/file/1/cover', data=cover_data) #update cover image self.assertEqual(request.status_code, status.HTTP_204_NO_CONTENT) request = self.client.get('/converter/1', ) #get file self.assertEqual(request.status_code, status.HTTP_200_OK) self.assertEqual(request.content[0:41], b'{"data_file":"http://testserver/music/ble') cover_data = {"cover": self.cover_image_2} request = self.client.put('/file/1/cover', data=cover_data) #update cover image self.assertEqual(request.status_code, status.HTTP_204_NO_CONTENT) request = self.client.get('/converter/1', ) #get file self.assertEqual(request.status_code, status.HTTP_200_OK) self.assertEqual(request.content[0:41], b'{"data_file":"http://testserver/music/ble') request = self.client.delete('/converter/1', ) #delete file self.assertEqual(request.status_code, status.HTTP_204_NO_CONTENT) request = self.client.delete('/converter/1', ) #delete file - failed self.assertEqual(request.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(request.content, b'{"detail":"Not found."}') request = self.client.get('/converter/1', ) #get file - failed self.assertEqual(request.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(request.content, b'{"detail":"Not found."}') request = self.client.get('/file/1/info') #get 1 file info - failed self.assertEqual(request.status_code, status.HTTP_404_NOT_FOUND) self.assertEqual(request.content, b'{"detail":"Not found."}')
class AttachmentQuerySetTest(TestCase): def setUp(self): self.user = self.make_user('testuser1') self.test_image = SimpleUploadedFile( name='testimage.jpg', content=open(TEST_IMAGE_1, 'rb').read(), content_type='image/jpeg' ) self.test_image2 = SimpleUploadedFile( name='aprf1.jpg', content=open(TEST_IMAGE_2, 'rb').read(), content_type='image/jpeg' ) self.current_count = Attachment.objects.count() def tearDown(self): self.test_image.close() self.test_image2.close() try: if os.path.isdir(settings.TEST_MEDIA_ROOT): shutil.rmtree(settings.TEST_MEDIA_ROOT) except Exception as e: print(e) def test_create_avatar_with_no_image(self): url = Attachment.objects.create_avatar(None, self.user) self.assertEqual(Attachment.objects.count(), self.current_count) self.assertIsNone(url) def test_create_avatar_with_image(self): url = Attachment.objects.create_avatar(self.test_image, self.user) self.assertEqual(Attachment.objects.count(), self.current_count + 1) self.assertEqual(Attachment.objects.all().first().image.url, url) self.assertIn(self.user, Attachment.objects.all().first().users.all()) def test_create_avatar_with_duplicate_images(self): second_user = self.make_user('testuser2') url = Attachment.objects.create_avatar(self.test_image, self.user) url2 = Attachment.objects.create_avatar(self.test_image, second_user) self.assertEqual(Attachment.objects.count(), self.current_count + 1) path, dirs, files = next(os.walk(AVATAR_UPLOAD_DIR)) self.assertEqual(len(files), 1) self.assertEqual(url, url2) self.assertIn(self.user, Attachment.objects.all().first().users.all()) self.assertIn( second_user, Attachment.objects.all().first().users.all() ) def test_synchronise(self): attachment = Attachment.objects.create(image=self.test_image) category = make_category() thread = make_only_thread(self.user, category) message = f'![]({attachment.image.url})' comment = make_comment(self.user, thread, message=message) Attachment.objects.synchronise(comment) self.assertIn( comment, Attachment.objects.all().first().comments.all() ) self.assertFalse(Attachment.objects.last().is_orphaned) def test_synchronise_with_revision(self): attachment = Attachment.objects.create(image=self.test_image) category = make_category() thread = make_only_thread(self.user, category) message = f'![]({attachment.image.url})' comment = make_comment(self.user, thread, message=message) Attachment.objects.synchronise(comment) self.assertIn( comment, Attachment.objects.all().first().comments.all() ) self.assertFalse(Attachment.objects.last().is_orphaned) Comment.objects.filter(pk=comment.pk).update( message='No more image source' ) revision = CommentRevision.objects.create( comment=comment, message=comment.message ) comment.refresh_from_db() Attachment.objects.synchronise(comment, revision.message) self.assertNotIn( comment, Attachment.objects.all().first().comments.all() ) self.assertTrue(Attachment.objects.last().is_orphaned)