Python django.core.files.uploadedfile.SimpleUploadedFile() Examples

The following are 30 code examples of django.core.files.uploadedfile.SimpleUploadedFile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.files.uploadedfile , or try the search function .
Example #1
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.target = TargetFactory.create()
        self.observation_record = ObservingRecordFactory.create(
            target_id=self.target.id,
            facility=FakeRoboticFacility.name,
            parameters='{}'
        )
        self.data_product = DataProduct.objects.create(
            product_id='testproductid',
            target=self.target,
            observation_record=self.observation_record,
            data=SimpleUploadedFile('afile.fits', b'somedata')
        )
        self.user = User.objects.create_user(username='test', email='test@example.com')
        assign_perm('tom_targets.view_target', self.user, self.target)
        self.client.force_login(self.user) 
Example #2
Source File: test_api.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_set_hero_cover_image(self):
        """
        Test uploading a hero cover image
        """
        self.client.force_login(self.user_with_instance)
        self._setup_user_instance()
        self.assertFalse(self.instance_config.hero_cover_image)

        # Load test cover image
        cover_image = create_image('cover.png')
        cover_image_file = SimpleUploadedFile('cover.png', cover_image.getvalue())

        # Request
        response = self.client.post(
            reverse(f"api:v2:openedx-instance-config-image", args=(self.instance_config.pk,)),
            data={'hero_cover_image': cover_image_file},
            format='multipart',
        )
        self.assertTrue(response.status_code, 200)
        self.instance_config.refresh_from_db()
        self.assertTrue(self.instance_config.hero_cover_image) 
Example #3
Source File: test_api.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_change_logo(self):
        """
        Test uploading logo
        """
        self.client.force_login(self.user_with_instance)
        self._setup_user_instance()

        # Load test logo image
        logo = create_image('logo.png')
        logo_file = SimpleUploadedFile('logo.png', logo.getvalue())

        # Request
        response = self.client.post(
            reverse(f"api:v2:openedx-instance-config-image", args=(self.instance_config.pk,)),
            data={'logo': logo_file},
            format='multipart',
        )
        self.assertEqual(response.status_code, 200) 
Example #4
Source File: test_forms.py    From conf_site with MIT License 6 votes vote down vote up
def test_build_schedule(self):
        """
        Test successful schedule build based off ingested CSV
        """
        self.assertEqual(0, Day.objects.all().count())
        self.assertEqual(0, Room.objects.all().count())
        self.assertEqual(0, Slot.objects.all().count())
        self.assertEqual(0, SlotKind.objects.all().count())
        schedule_csv = open(os.path.join(DATA_DIR, "schedule.csv"), "rb")
        file_data = {
            "filename": SimpleUploadedFile(
                schedule_csv.name, schedule_csv.read()
            )
        }
        data = {"submit": "Submit"}
        form = ScheduleSectionForm(data, file_data, schedule=self.schedule)
        form.is_valid()
        msg_type, msg = form.build_schedule()
        self.assertEqual(25, msg_type)
        self.assertIn("imported", msg)
        self.assertEqual(2, Day.objects.all().count())
        self.assertEqual(2, Room.objects.all().count())
        self.assertEqual(8, Slot.objects.all().count())
        self.assertEqual(2, SlotKind.objects.all().count()) 
Example #5
Source File: test_views.py    From kboard with MIT License 6 votes vote down vote up
def test_record_edited_attachment_if_attachment_is_modified(self):
        uploaded_file = SimpleUploadedFile(AttachmentModelTest.SAVED_TEST_FILE_NAME_1,
                                           open(AttachmentModelTest.UPLOAD_TEST_FILE_NAME, 'rb').read())
        origin_attachment = Attachment.objects.create(post=self.default_post, attachment=uploaded_file)

        upload_file = open(os.path.join(settings.BASE_DIR, 'test_file/attachment_test_2.txt'))
        self.client.post(reverse('board:edit_post', args=[self.default_post.id]), {
            'title': 'NEW POST TITLE',
            'content': 'NEW POST CONTENT',
            'attachment': upload_file,
        })

        origin_attachment.refresh_from_db()
        new_attachment = Attachment.objects.get(post=self.default_post)
        edtied_post_history = EditedPostHistory.objects.get(post=self.default_post)

        self.assertEqual(origin_attachment.post, None)
        self.assertEqual(origin_attachment.editedPostHistory, edtied_post_history)
        self.assertEqual(new_attachment.post, self.default_post)
        self.assertEqual(new_attachment.editedPostHistory, None) 
Example #6
Source File: individual_api_2_3_tests.py    From seqr with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_hpo_term_number_table_handler(self):
        url = reverse(receive_hpo_table_handler, args=['R0001_1kg'])
        self.check_collaborator_login(url)

        header = 'family_id,individual_id,affected,hpo_number,hpo_number'
        rows = [
            '1,NA19675_1,yes,HP:0002017,',
            '1,NA19675_1,no,HP:0012469,',
            '1,NA19675_1,no,,HP:0004322',
            '1,NA19678,,,',
            '1,NA19679,yes,HP:0100258,',
            '1,HG00731,yes,HP:0002017,',
            '1,HG00731,no,HP:0012469,HP:0011675',
        ]
        f = SimpleUploadedFile('updates.csv', "{}\n{}".format(header, '\n'.join(rows)).encode('utf-8'))
        response = self.client.post(url, data={'f': f})
        self._is_expected_hpo_upload(response) 
Example #7
Source File: test_views.py    From kboard with MIT License 6 votes vote down vote up
def test_view_edited_attachment_in_post_history_list(self):
        edited_post_history = EditedPostHistory.objects.create(
            post=self.default_post,
            title='edited post title',
            content='edited post content',
        )
        uploaded_file = SimpleUploadedFile(AttachmentModelTest.SAVED_TEST_FILE_NAME_1,
                                           open(AttachmentModelTest.UPLOAD_TEST_FILE_NAME, 'rb').read())
        attachment = Attachment.objects.create(
            post=None,
            editedPostHistory=edited_post_history,
            attachment=uploaded_file,
        )

        response = self.client.get(reverse('board:post_history_list', args=[self.default_post.id]))
        self.assertContains(response, 'edited post title')
        self.assertContains(response, attachment.attachment.name) 
Example #8
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.target = TargetFactory.create()
        self.observation_record = ObservingRecordFactory.create(
            target_id=self.target.id,
            facility=FakeRoboticFacility.name,
            parameters='{}'
        )
        self.data_product = DataProduct.objects.create(
            product_id='testproductid',
            target=self.target,
            observation_record=self.observation_record,
            data=SimpleUploadedFile('afile.fits', b'somedata')
        )
        self.user = User.objects.create_user(username='aaronrodgers', email='aaron.rodgers@packers.com')
        self.user2 = User.objects.create_user(username='timboyle', email='tim.boyle@packers.com')
        assign_perm('tom_targets.view_target', self.user, self.target)
        assign_perm('tom_targets.view_target', self.user2, self.target)
        assign_perm('tom_targets.view_dataproduct', self.user, self.data_product)
        self.client.force_login(self.user) 
Example #9
Source File: test_api.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_change_logo_wrong_size(self):
        """
        Test uploading logo with wrong size
        """
        self.client.force_login(self.user_with_instance)
        self._setup_user_instance()

        # Load test logo image
        logo = create_image('logo.png', size=(100, 100))
        logo_file = SimpleUploadedFile('logo.png', logo.getvalue())

        # Request
        response = self.client.post(
            reverse(f"api:v2:openedx-instance-config-image", args=(self.instance_config.pk,)),
            data={'logo': logo_file},
            format='multipart',
        )
        self.assertEqual(response.status_code, 400)
        self.assertDictEqual(
            response.data,
            {
                'logo': ['The logo image must be 48px tall to fit into the header.']
            }
        ) 
Example #10
Source File: test_views.py    From pinax-documents with MIT License 6 votes vote down vote up
def test_download(self):
        """
        Ensure the requested Document file is served.
        """
        simple_file = SimpleUploadedFile("delicious.txt", self.file_contents)
        document = Document.objects.create(name="Honeycrisp",
                                           author=self.user,
                                           file=simple_file,
                                           )
        document.save()

        with self.login(self.user):
            # Verify `django.views.static.serve` is called to serve up the file.
            # See related note in .views.DocumentDownload.get().
            with mock.patch("django.views.static.serve") as serve:
                serve.return_value = HttpResponse()
                self.get_check_200(self.download_urlname, pk=document.pk)
                self.assertTrue(serve.called) 
Example #11
Source File: test_views.py    From pinax-documents with MIT License 6 votes vote down vote up
def test_valid_delete(self, mock_messages):
        """
        Ensure we can delete a valid Document.
        """
        simple_file = SimpleUploadedFile("delicious.txt", self.file_contents)
        document = Document.objects.create(name="Honeycrisp",
                                           author=self.user,
                                           file=simple_file,
                                           )

        doc_pk = document.pk
        with self.login(self.user):
            response = self.get(document.delete_url())
            self.response_200(response)
            self.assertTrue("pinax/documents/document_confirm_delete.html" in response.template_name)

            response = self.post("pinax_documents:document_delete", pk=doc_pk, follow=True)
            self.response_200(response)
            self.assertFalse(Document.objects.filter(pk=doc_pk))
            self.assertTrue(mock_messages.called)

            response = self.get(self.download_urlname, pk=document.pk)
            self.response_404(response) 
Example #12
Source File: test_api.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_change_favicon(self):
        """
        Test uploading favicon
        """
        self.client.force_login(self.user_with_instance)
        self._setup_user_instance()

        # Load test logo image
        logo = create_image('logo.ico', size=(10, 10))
        logo_file = SimpleUploadedFile('logo.ico', logo.getvalue())

        # Request
        response = self.client.post(
            reverse(f"api:v2:openedx-instance-config-image", args=(self.instance_config.pk,)),
            data={'favicon': logo_file},
            format='multipart',
        )
        self.assertEqual(response.status_code, 200) 
Example #13
Source File: odlc_test.py    From interop with Apache License 2.0 6 votes vote down vote up
def test_valid(self):
        """Test creating a valid odlc."""
        with open(os.path.join(settings.BASE_DIR, 'auvsi_suas/testdata/S.jpg'),
                  'rb') as f:
            thumb = SimpleUploadedFile('thumb.jpg', f.read())

        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Odlc(mission=self.mission,
                 user=self.user,
                 odlc_type=interop_api_pb2.Odlc.STANDARD,
                 location=l,
                 orientation=interop_api_pb2.Odlc.S,
                 shape=interop_api_pb2.Odlc.SQUARE,
                 shape_color=interop_api_pb2.Odlc.WHITE,
                 alphanumeric='ABC',
                 alphanumeric_color=interop_api_pb2.Odlc.BLACK,
                 description='Test odlc',
                 thumbnail=thumb)
        t.save() 
Example #14
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.target = TargetFactory.create()
        self.observation_record = ObservingRecordFactory.create(
            target_id=self.target.id,
            facility=FakeRoboticFacility.name,
            parameters='{}'
        )
        self.data_product = DataProduct.objects.create(
            product_id='testproductid',
            target=self.target,
            observation_record=self.observation_record,
            data=SimpleUploadedFile('afile.fits', b'somedata')
        )
        user = User.objects.create_user(username='test', email='test@example.com')
        assign_perm('tom_targets.view_target', user, self.target)
        self.client.force_login(user) 
Example #15
Source File: test_api.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def test_search_with_imagefile(self):
        from django.core.files.uploadedfile import SimpleUploadedFile

        models.SpeedRun.objects.create(
            event=self.event,
            name='Test Run',
            run_time='5:00',
            setup_time='5:00',
            order=1,
        ).clean()
        prize = models.Prize.objects.create(
            event=self.event,
            handler=self.add_user,
            name='Prize With Image',
            state='ACCEPTED',
            startrun=self.event.speedrun_set.first(),
            endrun=self.event.speedrun_set.first(),
            imagefile=SimpleUploadedFile('test.jpg', b''),
        )
        prize.refresh_from_db()
        request = self.factory.get('/api/v1/search', dict(type='prize',),)
        request.user = self.user
        data = self.parseJSON(tracker.views.api.search(request))
        self.assertEqual(len(data), 1)
        self.assertEqual(data[0], self.format_prize(prize, request)) 
Example #16
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def test_upload_data_extended_permissions(self, dp_mock):
        group = Group.objects.create(name='permitted')
        group.user_set.add(self.user)
        response = self.client.post(
            reverse('dataproducts:upload'),
            {
                'facility': 'LCO',
                'files': SimpleUploadedFile('afile.fits', b'afile'),
                'target': self.target.id,
                'groups': Group.objects.filter(name='permitted'),
                'data_product_type': settings.DATA_PRODUCT_TYPES['spectroscopy'][0],
                'observation_timestamp_0': date(2019, 6, 1),
                'observation_timestamp_1': time(12, 0, 0),
                'referrer': reverse('targets:detail', kwargs={'pk': self.target.id})
            },
            follow=True
        )
        self.assertContains(response, 'afile.fits')
        self.client.force_login(self.user2)
        response = self.client.get(reverse('targets:detail', kwargs={'pk': self.target.id}))
        self.assertNotContains(response, 'afile.fits') 
Example #17
Source File: tests.py    From readux with MIT License 6 votes vote down vote up
def test_collection_images(self):
        image_path = "{p}test_vert.jpg".format(p=self.fixture_path)
        self.collection.original = SimpleUploadedFile(name='test_vert.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')
        self.collection.save()
        # NOTE pytest uses some arbitrary tmp file naming structure.
        assert self.collection.original.path.split('/')[-1] == 'test_vert.jpg'
        # assert self.collection.upload.path.split('/')[-1] == 'test_vert.jpg'
        assert self.collection.header.path.split('/')[-1] == 'test_vert_header.jpg'
        assert self.collection.thumbnail.path.split('/')[-1] == 'test_vert_thumb.jpg'
        assert self.collection.original.url == "%soriginals/test_vert.jpg" % (settings.MEDIA_URL)
        # assert self.collection.upload.url == "%s/uploads/test_vert.jpg" % (settings.MEDIA_URL)
        assert self.collection.header.url == "%sheaders/test_vert_header.jpg" % (settings.MEDIA_URL)
        assert self.collection.thumbnail.url == "%sthumbnails/test_vert_thumb.jpg" % (settings.MEDIA_URL)
        assert path.isfile(self.collection.original.path)
        # assert path.isfile(self.collection.upload.path)
        assert path.isfile(self.collection.header.path)
        assert path.isfile(self.collection.thumbnail.path) 
Example #18
Source File: test_views.py    From kboard with MIT License 6 votes vote down vote up
def test_can_modify_uploaded_file_with_edit_post(self):
        uploaded_file = SimpleUploadedFile(AttachmentModelTest.SAVED_TEST_FILE_NAME_1,
                                           open(AttachmentModelTest.UPLOAD_TEST_FILE_NAME, 'rb').read())
        Attachment.objects.create(post=self.default_post, attachment=uploaded_file)

        self.assertEqual(Attachment.objects.get(post=self.default_post).attachment.name,
                         AttachmentModelTest.SAVED_TEST_FILE_NAME_1)

        upload_file = open(os.path.join(settings.BASE_DIR, 'test_file/attachment_test_2.txt'))
        self.client.post(reverse('board:edit_post', args=[self.default_post.id]), {
            'title': 'some post title',
            'content': 'some post content',
            'attachment': upload_file,
        })

        self.assertEqual(Attachment.objects.get(post=self.default_post).attachment.name,
                         AttachmentModelTest.SAVED_TEST_FILE_NAME_2) 
Example #19
Source File: test_query_execution.py    From ariadne with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multipart_form_request_fails_if_map_is_not_valid_json(
    view, request_factory, snapshot
):
    request = request_factory.post(
        "/",
        {
            "operations": json.dumps(
                {
                    "query": "mutation($file: Upload!) { upload(file: $file) }",
                    "variables": {"file": None},
                }
            ),
            "map": "not a valid json",
            "0": SimpleUploadedFile("test.txt", b"test"),
        },
    )
    response = view(request)
    assert response.status_code == 400
    snapshot.assert_match(response.content) 
Example #20
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def test_upload_data_for_observation(self, run_data_processor_mock):
        response = self.client.post(
            reverse('dataproducts:upload'),
            {
                'facility': 'LCO',
                'files': SimpleUploadedFile('bfile.fits', b'afile'),
                'observation_record': self.observation_record.id,
                'data_product_type': settings.DATA_PRODUCT_TYPES['spectroscopy'][0],
                'observation_timestamp_0': date(2019, 6, 1),
                'observation_timestamp_1': time(12, 0, 0),
                'referrer': reverse('targets:detail', kwargs={'pk': self.target.id})
            },
            follow=True
        )
        self.assertContains(response, 'Successfully uploaded: {0}/{1}/bfile.fits'.format(
            self.target.name, FakeRoboticFacility.name)
        ) 
Example #21
Source File: test_query_execution.py    From ariadne with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_query_is_executed_for_multipart_form_request_with_file(
    view, request_factory, snapshot
):
    request = request_factory.post(
        "/",
        {
            "operations": json.dumps(
                {
                    "query": "mutation($file: Upload!) { upload(file: $file) }",
                    "variables": {"file": None},
                }
            ),
            "map": json.dumps({"0": ["variables.file"]}),
            "0": SimpleUploadedFile("test.txt", b"test"),
        },
    )
    response = view(request)
    assert response.status_code == 200
    snapshot.assert_match(response.content) 
Example #22
Source File: test_views.py    From django-private-storage with Apache License 2.0 6 votes vote down vote up
def test_private_file_view_utf8(self):
        """
        Test the detail view that returns the object
        """
        obj = CustomerDossier.objects.create(
            customer='cust2',
            file=SimpleUploadedFile(u'Heizölrückstoßabdämpfung.txt', b'test5')
        )
        self.assertExists('CustomerDossier', 'cust2', u'Heizölrückstoßabdämpfung.txt')

        # Initialize locally, no need for urls.py etc..
        # This behaves like a standard DetailView
        view = PrivateStorageView.as_view(
            content_disposition='attachment',
        )
        superuser = User.objects.create_superuser('admin', 'admin@example.com', 'admin')

        for user_agent, expect_header in [
                ('Firefox', "attachment; filename*=UTF-8''Heiz%C3%B6lr%C3%BCcksto%C3%9Fabd%C3%A4mpfung.txt"),
                ('WebKit', 'attachment; filename=Heiz\xc3\xb6lr\xc3\xbccksto\xc3\x9fabd\xc3\xa4mpfung.txt'),
                ('MSIE', 'attachment; filename=Heiz%C3%B6lr%C3%BCcksto%C3%9Fabd%C3%A4mpfung.txt'),
                ]:

            for method in ('GET', 'HEAD'):
                request = RequestFactory().generic(method, '/cust1/file/')
                request.user = superuser
                request.META['HTTP_USER_AGENT'] = user_agent

                response = view(
                    request,
                    path=u'CustomerDossier/cust2/Heizölrückstoßabdämpfung.txt'
                )
                if method == 'HEAD':
                    self.assertNotIsInstance(response, FileResponse)
                    self.assertEqual(response.content, b'')
                else:
                    self.assertEqual(list(response.streaming_content), [b'test5'])
                self.assertEqual(response['Content-Type'], 'text/plain')
                self.assertEqual(response['Content-Length'], '5')
                self.assertEqual(response['Content-Disposition'], expect_header, user_agent)
                self.assertIn('Last-Modified', response) 
Example #23
Source File: test_views.py    From django-private-storage with Apache License 2.0 6 votes vote down vote up
def test_private_file_view(self):
        """
        Test the detail view that returns the object
        """
        obj = CustomerDossier.objects.create(
            customer='cust2',
            file=SimpleUploadedFile('test5.txt', b'test5')
        )
        self.assertExists('CustomerDossier', 'cust2', 'test5.txt')

        # Initialize locally, no need for urls.py etc..
        # This behaves like a standard DetailView
        view = PrivateStorageView.as_view(
            content_disposition='attachment',
        )
        superuser = User.objects.create_superuser('admin', 'admin@example.com', 'admin')

        # Test HEAD calls too
        for method in ('GET', 'HEAD'):
            request = RequestFactory().generic(method, '/cust1/file/')
            request.user = superuser
            request.META['HTTP_USER_AGENT'] = 'Test'

            response = view(
                request,
                path='CustomerDossier/cust2/test5.txt'
            )
            if method == 'HEAD':
                self.assertNotIsInstance(response, FileResponse)
                self.assertEqual(response.content, b'')
            else:
                self.assertEqual(list(response.streaming_content), [b'test5'])
            self.assertEqual(response['Content-Type'], 'text/plain')
            self.assertEqual(response['Content-Length'], '5')
            self.assertEqual(response['Content-Disposition'], "attachment; filename*=UTF-8''test5.txt")
            self.assertIn('Last-Modified', response) 
Example #24
Source File: tests.py    From anytask with MIT License 6 votes vote down vote up
def test_check_submission_ok(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student
        contest_submition.run_id = "1"

        event_create_file = Event.objects.create(issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile('test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        comment = contest_submition.check_submission()
        self.assertIn(u'<p>{0}: ok</p>'.format(_(u'verdikt_jakontest')), comment)
        self.assertTrue(contest_submition.got_verdict) 
Example #25
Source File: tests.py    From anytask with MIT License 6 votes vote down vote up
def test_check_submission_precompile_check_failed(self):
        contest_submition = ContestSubmission()
        contest_submition.issue = self.issue
        contest_submition.author = self.student
        contest_submition.run_id = "2"

        event_create_file = Event.objects.create(issue=self.issue, field=IssueField.objects.get(name='file'))
        f = File.objects.create(file=SimpleUploadedFile('test_fail_rb.py', b'print "_failed_"'),
                                event=event_create_file)
        contest_submition.file = f

        contest_submition.save()

        comment = contest_submition.check_submission()
        self.assertIn(u'<p>{0}: precompile-check-failed</p>'.format(_(u'verdikt_jakontest')), comment)
        self.assertTrue(contest_submition.got_verdict)
        self.assertIn('precompile-check-failed-1', comment)
        self.assertIn('precompile-check-failed-2', comment)
        self.assertIn('precompile-check-failed-3', comment) 
Example #26
Source File: test_views.py    From django-private-storage with Apache License 2.0 6 votes vote down vote up
def test_detail_view(self):
        """
        Test the detail view that returns the object
        """
        CustomerDossier.objects.create(
            customer='cust1',
            file=SimpleUploadedFile('test4.txt', b'test4')
        )

        superuser = User.objects.create_superuser('admin', 'admin@example.com', 'admin')

        # Test HEAD calls too
        for method in ('GET', 'HEAD'):
            request = RequestFactory().generic(method, '/cust1/file/')
            request.user = superuser

            # Initialize locally, no need for urls.py etc..
            # This behaves like a standard DetailView
            view = PrivateStorageDetailView.as_view(
                model=CustomerDossier,
                slug_url_kwarg='customer',
                slug_field='customer',
                model_file_field='file'
            )

            response = view(
                request,
                customer='cust1',
            )
            if method == 'HEAD':
                self.assertNotIsInstance(response, FileResponse)
                self.assertEqual(response.content, b'')
            else:
                self.assertEqual(list(response.streaming_content), [b'test4'])
            self.assertEqual(response['Content-Type'], 'text/plain')
            self.assertEqual(response['Content-Length'], '5')
            self.assertIn('Last-Modified', response) 
Example #27
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.target = TargetFactory.create()
        self.observation_record = ObservingRecordFactory.create(
            target_id=self.target.id,
            facility=FakeRoboticFacility.name,
            parameters='{}'
        )
        self.spectroscopy_form_data = {
            'target': self.target.id,
            'data_product_type': settings.DATA_PRODUCT_TYPES['spectroscopy'][0],
            'facility': 'LCO',
            'observation_timestamp_0': date(2019, 6, 1),
            'observation_timestamp_1': time(12, 0, 0),
            'referrer': 'referrer'
        }
        self.photometry_form_data = {
            'target': self.target.id,
            'data_product_type': settings.DATA_PRODUCT_TYPES['photometry'][0],
            'referrer': 'referrer'
        }
        self.file_data = {
            'files': SimpleUploadedFile('afile.fits', b'afile')
        } 
Example #28
Source File: test_statement_csv_import.py    From django-hordak with MIT License 6 votes vote down vote up
def create_import(self, year=b"2000"):
        f = SimpleUploadedFile(
            "data.csv",
            six.binary_type(
                b"Number,Date,Account,Amount,Subcategory,Memo\n"
                b"1,1/1/" + year + b",123456789,123,OTH,Some random notes"
            ),
        )
        self.transaction_import = TransactionCsvImport.objects.create(
            has_headings=True, file=f, date_format="%d/%m/%Y", hordak_import=self.statement_import()
        )
        self.view_url = reverse("hordak:import_execute", args=[self.transaction_import.uuid])
        self.transaction_import.create_columns()

        self.transaction_import.columns.filter(column_number=2).update(to_field="date")
        self.transaction_import.columns.filter(column_number=4).update(to_field="amount")
        self.transaction_import.columns.filter(column_number=6).update(to_field="description") 
Example #29
Source File: test_statement_csv_import.py    From django-hordak with MIT License 6 votes vote down vote up
def create_import(self, year=b"2000"):
        f = SimpleUploadedFile(
            "data.csv",
            six.binary_type(
                b"Number,Date,Account,Amount,Subcategory,Memo\n"
                b"1,1/1/" + year + b",123456789,123,OTH,Some random notes"
            ),
        )
        self.transaction_import = TransactionCsvImport.objects.create(
            has_headings=True, file=f, date_format="%d/%m/%Y", hordak_import=self.statement_import()
        )
        self.view_url = reverse("hordak:import_dry_run", args=[self.transaction_import.uuid])
        self.transaction_import.create_columns()

        self.transaction_import.columns.filter(column_number=2).update(to_field="date")
        self.transaction_import.columns.filter(column_number=4).update(to_field="amount")
        self.transaction_import.columns.filter(column_number=6).update(to_field="description") 
Example #30
Source File: test_event_images_v1.py    From linkedevents with MIT License 6 votes vote down vote up
def test__delete_an_image(api_client, settings, user, organization):
    api_client.force_authenticate(user)

    image_file = create_in_memory_image_file(name='existing_test_image')
    uploaded_image = SimpleUploadedFile(
        'existing_test_image.png',
        image_file.read(),
        'image/png',
    )
    existing_image = Image.objects.create(image=uploaded_image,
                                          publisher=organization)
    assert Image.objects.all().count() == 1

    # verify that the image file exists at first just in case
    image_path = os.path.join(settings.MEDIA_ROOT, existing_image.image.url)
    assert os.path.isfile(image_path)

    detail_url = reverse('image-detail', kwargs={'pk': existing_image.pk})
    response = api_client.delete(detail_url)
    assert response.status_code == 204
    assert Image.objects.all().count() == 0

    # check that the image file is deleted
    assert not os.path.isfile(image_path)