django.core.files.uploadedfile.SimpleUploadedFile - python examples

Here are the examples of the python api django.core.files.uploadedfile.SimpleUploadedFile taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_updates_commissioning_script(self):
        request = HttpRequest()
        request.user = factory.make_User()
        script = factory.make_Script(script_type=SCRIPT_TYPE.COMMISSIONING)
        content = factory.make_script_content()
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=script.name
        )
        form = CommissioningScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        new_script = Script.objects.get(name=script.name)
        self.astertEquals(SCRIPT_TYPE.COMMISSIONING, new_script.script_type)
        self.astertEquals(content, new_script.script.data)

3 View Complete Implementation : pdfs.py
Copyright MIT License
Author : codeforamerica
    @clastmethod
    def create_with_pdf_bytes(cls, pdf_bytes, original_pdf, submission):
        """Sets the contents of `self.pdf` to `bytes_`.
        """
        filename = 'filled_{0:0>4}-{1:0>6}.pdf'.format(
            original_pdf.id, submission.id)
        file_obj = SimpleUploadedFile(
            filename, pdf_bytes, content_type='application/pdf')
        instance = cls(
            pdf=file_obj,
            original_pdf=original_pdf,
            submission=submission)
        instance.save()
        return instance

3 View Complete Implementation : test_imagefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_file_extension_validation(self):
        f = ImageField()
        img_path = get_img_path('filepath_test_files/1x1.png')
        with open(img_path, 'rb') as img_file:
            img_data = img_file.read()
        img_file = SimpleUploadedFile('1x1.txt', img_data)
        with self.astertRaisesMessage(ValidationError, "File extension 'txt' is not allowed."):
            f.clean(img_file)

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_propagates_script_form_errors(self):
        # Regression test for LP:1712422
        uploaded_file = SimpleUploadedFile(
            content=factory.make_script_content().encode("ascii"), name="none"
        )
        form = CommissioningScriptForm(files={"content": uploaded_file})
        self.astertFalse(form.is_valid())
        self.astertDictEqual(
            {"content": ['name: "none" is a reserved name.']}, form.errors
        )

3 View Complete Implementation : test_bootresource.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_prevents_reserved_centos_names(self):
        reserved_name = "centos%d" % random.randint(0, 99)
        upload_type, filetype = self.pick_filetype()
        size = random.randint(1024, 2048)
        content = factory.make_string(size).encode("utf-8")
        upload_name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(content=content, name=upload_name)
        data = {
            "name": reserved_name,
            "satle": factory.make_name("satle"),
            "architecture": make_usable_architecture(self),
            "filetype": upload_type,
        }
        form = BootResourceForm(data=data, files={"content": uploaded_file})
        self.astertFalse(form.is_valid())

3 View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_2(self):
        f = FileField(max_length=5)
        with self.astertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'"):
            f.clean(SimpleUploadedFile('test_maxlength.txt', b'hello world'))
        self.astertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
        self.astertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
        self.astertIsInstance(f.clean(SimpleUploadedFile('name', b'Some File Content')), SimpleUploadedFile)

3 View Complete Implementation : test_admin_views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
    def test_upload(self):
        response = self.client.post(reverse('wagtailvideos:chooser_upload'), {
            'satle': "Test video",
            'file': SimpleUploadedFile('small.mp4', create_test_video_file().read(), "video/mp4"),
        })

        # Check response
        self.astertEqual(response.status_code, 200)

        # Check that the video was created
        videos = Video.objects.filter(satle="Test video")
        self.astertEqual(videos.count(), 1)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_unicode_filename(self):
        # FileModel with unicode filename and data #########################
        file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode())
        f = FileForm(data={}, files={'file1': file1}, auto_id=False)
        self.astertTrue(f.is_valid())
        self.astertIn('file1', f.cleaned_data)
        m = FileModel.objects.create(file=f.cleaned_data['file1'])
        self.astertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
        m.delete()

3 View Complete Implementation : test_process_view.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ImperialCollegeLondon
    def test_process_data_invalid_different_field_name(self):
        upload_form = {'somekey': SimpleUploadedFile(
            'test.txt', self.test_data.read()), 'fp_upload_field': 'somekey2'
        }
        boundary = str(uuid.uuid4()).replace('-', '')
        enc_form = encode_multipart(boundary, upload_form)

        rf = RequestFactory()
        req = rf.post(reverse('process'), data=enc_form,
                      content_type='multipart/form-data; boundary=%s'
                      % boundary)
        pv = views.ProcessView.as_view()
        response = pv(req)
        self.astertEqual(response.status_code, 400, 'Expecting 400 error due'
                         ' to invalid data being provided.')
        self.astertTrue('detail' in response.data,
                        'Error detail missing in response.')
        self.astertIn(response.data['detail'], ('Invalid request data has '
                                                'been provided.'))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_reopen(self):
        obj = Storage.objects.create(normal=SimpleUploadedFile('reopen.txt', b'content'))
        with obj.normal as normal:
            normal.open()
        obj.normal.open()
        obj.normal.file.seek(0)
        obj.normal.close()

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_creates_test_script_from_embedded_yaml_name(self):
        request = HttpRequest()
        request.user = factory.make_User()
        name = factory.make_name("name")
        content = factory.make_script_content({"name": name})
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=factory.make_name("filename")
        )
        form = TestingScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        new_script = Script.objects.get(name=name)
        self.astertEquals(SCRIPT_TYPE.TESTING, new_script.script_type)
        self.astertEquals(content, new_script.script.data)

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_updates_test_script(self):
        request = HttpRequest()
        request.user = factory.make_User()
        script = factory.make_Script(script_type=SCRIPT_TYPE.TESTING)
        content = factory.make_script_content()
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=script.name
        )
        form = TestingScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        new_script = Script.objects.get(name=script.name)
        self.astertEquals(SCRIPT_TYPE.TESTING, new_script.script_type)
        self.astertEquals(content, new_script.script.data)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_read(self):
        # Files can be read in a little at a time, if necessary.
        obj = Storage.objects.create(
            normal=SimpleUploadedFile("astignment.txt", b"content"))
        obj.normal.open()
        self.astertEqual(obj.normal.read(3), b"con")
        self.astertEqual(obj.normal.read(), b"tent")
        self.astertEqual(list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"])
        obj.normal.close()

3 View Complete Implementation : test_bootresource.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_prevents_unsupported_osystem(self):
        reserved_name = "%s/%s" % (
            factory.make_name("osystem"),
            factory.make_name("series"),
        )
        upload_type, filetype = self.pick_filetype()
        size = random.randint(1024, 2048)
        content = factory.make_string(size).encode("utf-8")
        upload_name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(content=content, name=upload_name)
        data = {
            "name": reserved_name,
            "satle": factory.make_name("satle"),
            "architecture": make_usable_architecture(self),
            "filetype": upload_type,
        }
        form = BootResourceForm(data=data, files={"content": uploaded_file})
        self.astertFalse(form.is_valid())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_unicode_filename(self):
        # FileModel with unicode filename and data #########################
        file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode())
        f = FileForm(data={}, files={'file1': file1}, auto_id=False)
        self.astertTrue(f.is_valid())
        self.astertIn('file1', f.cleaned_data)
        m = FileModel.objects.create(file=f.cleaned_data['file1'])
        self.astertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
        m.delete()

3 View Complete Implementation : test_admin_views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
    def test_add_too_long_filename(self):
        video_file = create_test_video_file()

        name = 'a_very_long_filename_' + ('x' * 100) + '.mp4'
        response = self.post({
            'satle': "Test video",
            'file': SimpleUploadedFile(name, video_file.read(), "video/mp4"),
        })

        # Should be valid
        self.astertEqual(response.status_code, 302)
        video = Video.objects.get()

        self.astertEqual(len(video.file.name), Video._meta.get_field('file').max_length)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @unittest.skipIf(sys.platform == 'win32', "Python on Windows doesn't have working os.chmod().")
    def test_readonly_root(self):
        """Permission errors are not swallowed"""
        os.chmod(MEDIA_ROOT, 0o500)
        self.addCleanup(os.chmod, MEDIA_ROOT, 0o700)
        with self.astertRaises(PermissionError):
            self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'), save=False)

3 View Complete Implementation : prebuilt_pdf_bundle.py
Copyright MIT License
Author : codeforamerica
    def set_bytes(self, bytes_):
        if not bytes_:
            self.pdf = None
        else:
            now_str = timezone.now().astimezone(
                PACIFIC_TIME).strftime('%Y-%m-%d_%H:%M')
            filename = '{}_newapps_{}.pdf'.format(
                self.organization.slug, now_str)
            self.pdf = SimpleUploadedFile(
                filename, bytes_, content_type='application/pdf')

3 View Complete Implementation : test_imagefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_imagefield_annotate_with_image_after_clean(self):
        f = ImageField()

        img_path = get_img_path('filepath_test_files/1x1.png')
        with open(img_path, 'rb') as img_file:
            img_data = img_file.read()

        img_file = SimpleUploadedFile('1x1.png', img_data)
        img_file.content_type = 'text/plain'

        uploaded_file = f.clean(img_file)

        self.astertEqual('PNG', uploaded_file.image.format)
        self.astertEqual('image/png', uploaded_file.content_type)

3 View Complete Implementation : test_process_view.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ImperialCollegeLondon
    def _get_encoded_form(self, filename, upload_field_name=None):
        f = SimpleUploadedFile(filename, self.test_data.read())
        if upload_field_name:
            upload_form = {upload_field_name: f,
                           'fp_upload_field': upload_field_name}
        else:
            upload_form = {'filepond': f}

        boundary = str(uuid.uuid4()).replace('-', '')

        encoded_form = encode_multipart(boundary, upload_form)

        content_type = ('multipart/form-data; boundary=%s' % (boundary))

        return (encoded_form, content_type)

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_creates_test_script_from_filename(self):
        request = HttpRequest()
        request.user = factory.make_User()
        content = factory.make_script_content()
        name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=name
        )
        form = TestingScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        new_script = Script.objects.get(name=name)
        self.astertEquals(SCRIPT_TYPE.TESTING, new_script.script_type)
        self.astertEquals(content, new_script.script.data)

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_creates_audit_event(self):
        request = HttpRequest()
        request.user = factory.make_User()
        content = factory.make_script_content()
        name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=name
        )
        form = TestingScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        new_script = Script.objects.get(name=name)
        event = Event.objects.get(type__level=AUDIT)
        self.astertIsNotNone(event)
        self.astertEqual(
            event.description, "Saved script '%s'." % new_script.name
        )

3 View Complete Implementation : test_clearablefileinput.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_clear_input_checked_returns_false_only_if_not_required(self):
        """
        ClearableFileInput.value_from_datadict never returns False if the field
        is required.
        """
        widget = ClearableFileInput()
        widget.is_required = True
        field = SimpleUploadedFile('something.txt', b'content')

        value = widget.value_from_datadict(
            data={'myfile-clear': True},
            files={'myfile': field},
            name='myfile',
        )
        self.astertEqual(value, field)

3 View Complete Implementation : test_bootresource.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_prevents_reserved_name(self):
        bsc = factory.make_BootSourceCache()
        upload_type, filetype = self.pick_filetype()
        size = random.randint(1024, 2048)
        content = factory.make_string(size).encode("utf-8")
        upload_name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(content=content, name=upload_name)
        data = {
            "name": "%s/%s" % (bsc.os, bsc.release),
            "satle": factory.make_name("satle"),
            "architecture": make_usable_architecture(self),
            "filetype": upload_type,
        }
        form = BootResourceForm(data=data, files={"content": uploaded_file})
        self.astertFalse(form.is_valid())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @unittest.skipIf(sys.platform == 'win32', "Python on Windows doesn't have working os.chmod().")
    def test_readonly_root(self):
        """Permission errors are not swallowed"""
        os.chmod(MEDIA_ROOT, 0o500)
        self.addCleanup(os.chmod, MEDIA_ROOT, 0o700)
        with self.astertRaises(PermissionError):
            self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'), save=False)

3 View Complete Implementation : test_bootresource.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_prevents_reserved_osystem(self):
        bsc = factory.make_BootSourceCache()
        upload_type, filetype = self.pick_filetype()
        size = random.randint(1024, 2048)
        content = factory.make_string(size).encode("utf-8")
        upload_name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(content=content, name=upload_name)
        data = {
            "name": bsc.os,
            "satle": factory.make_name("satle"),
            "architecture": make_usable_architecture(self),
            "filetype": upload_type,
        }
        form = BootResourceForm(data=data, files={"content": uploaded_file})
        self.astertFalse(form.is_valid())

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_propagates_script_form_errors(self):
        # Regression test for LP:1712422
        uploaded_file = SimpleUploadedFile(
            content=factory.make_script_content().encode("ascii"), name="none"
        )
        form = TestingScriptForm(files={"content": uploaded_file})
        self.astertFalse(form.is_valid())
        self.astertDictEqual(
            {"content": ['name: "none" is a reserved name.']}, form.errors
        )

3 View Complete Implementation : test_imagefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_file_extension_validation(self):
        f = ImageField()
        img_path = get_img_path('filepath_test_files/1x1.png')
        with open(img_path, 'rb') as img_file:
            img_data = img_file.read()
        img_file = SimpleUploadedFile('1x1.txt', img_data)
        with self.astertRaisesMessage(ValidationError, "File extension 'txt' is not allowed."):
            f.clean(img_file)

3 View Complete Implementation : test_bootresource.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_prevents_reversed_osystem_from_driver(self):
        reserved_name = factory.make_name("name")
        OperatingSystemRegistry.register_item(reserved_name, CustomOS())
        upload_type, filetype = self.pick_filetype()
        size = random.randint(1024, 2048)
        content = factory.make_string(size).encode("utf-8")
        upload_name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(content=content, name=upload_name)
        data = {
            "name": reserved_name,
            "satle": factory.make_name("satle"),
            "architecture": make_usable_architecture(self),
            "filetype": upload_type,
        }
        form = BootResourceForm(data=data, files={"content": uploaded_file})
        self.astertFalse(form.is_valid())

3 View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield(self):
        e = {
            'required': 'REQUIRED',
            'invalid': 'INVALID',
            'missing': 'MISSING',
            'empty': 'EMPTY FILE',
        }
        f = FileField(error_messages=e)
        self.astertFormErrors(['REQUIRED'], f.clean, '')
        self.astertFormErrors(['INVALID'], f.clean, 'abc')
        self.astertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None))
        self.astertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', ''))

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_creates_commissioning_script_from_filename(self):
        request = HttpRequest()
        request.user = factory.make_User()
        content = factory.make_script_content()
        name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=name
        )
        form = CommissioningScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        new_script = Script.objects.get(name=name)
        self.astertEquals(SCRIPT_TYPE.COMMISSIONING, new_script.script_type)
        self.astertEquals(content, new_script.script.data)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_reopen(self):
        obj = Storage.objects.create(normal=SimpleUploadedFile('reopen.txt', b'content'))
        with obj.normal as normal:
            normal.open()
        obj.normal.open()
        obj.normal.file.seek(0)
        obj.normal.close()

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_creates_commissioning_script_from_embedded_yaml_name(self):
        request = HttpRequest()
        request.user = factory.make_User()
        name = factory.make_name("name")
        content = factory.make_script_content({"name": name})
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=factory.make_name("filename")
        )
        form = CommissioningScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        new_script = Script.objects.get(name=name)
        self.astertEquals(SCRIPT_TYPE.COMMISSIONING, new_script.script_type)
        self.astertEquals(content, new_script.script.data)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_not_a_directory(self):
        """The correct IOError is raised when the upload directory name exists but isn't a directory"""
        # Create a file with the upload directory name
        open(UPLOAD_TO, 'wb').close()
        self.addCleanup(os.remove, UPLOAD_TO)
        with self.astertRaises(IOError) as exc_info:
            with SimpleUploadedFile('foo.txt', b'x') as file:
                self.obj.testfile.save('foo.txt', file, save=False)
        # The test needs to be done on a specific string as IOError
        # is raised even without the patch (just not early enough)
        self.astertEqual(exc_info.exception.args[0], "%s exists and is not a directory." % UPLOAD_TO)

3 View Complete Implementation : test_bootresource.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_prevents_reserved_release(self):
        bsc = factory.make_BootSourceCache()
        upload_type, filetype = self.pick_filetype()
        size = random.randint(1024, 2048)
        content = factory.make_string(size).encode("utf-8")
        upload_name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(content=content, name=upload_name)
        data = {
            "name": bsc.release,
            "satle": factory.make_name("satle"),
            "architecture": make_usable_architecture(self),
            "filetype": upload_type,
        }
        form = BootResourceForm(data=data, files={"content": uploaded_file})
        self.astertFalse(form.is_valid())

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_write(self):
        # Files can be written to.
        obj = Storage.objects.create(normal=SimpleUploadedFile('rewritten.txt', b'content'))
        with obj.normal as normal:
            normal.open('wb')
            normal.write(b'updated')
        obj.refresh_from_db()
        self.astertEqual(obj.normal.read(), b'updated')
        obj.normal.close()

3 View Complete Implementation : test_admin_views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
    def test_edit_with_new_video_file(self):
        # Change the file size of the video
        self.video.file_size = 100000
        self.video.save()

        new_file = create_test_video_file()
        response = self.post({
            'satle': "Edited",
            'file': SimpleUploadedFile('new.mp4', new_file.read(), "video/mp4"),
        })

        # Should redirect back to index
        self.astertRedirects(response, reverse('wagtailvideos:index'))

        # Check that the video file size changed (astume it changed to the correct value)
        video = Video.objects.get(id=self.video.id)
        self.astertNotEqual(video.file_size, 100000)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_write(self):
        # Files can be written to.
        obj = Storage.objects.create(normal=SimpleUploadedFile('rewritten.txt', b'content'))
        with obj.normal as normal:
            normal.open('wb')
            normal.write(b'updated')
        obj.refresh_from_db()
        self.astertEqual(obj.normal.read(), b'updated')
        obj.normal.close()

3 View Complete Implementation : test_pdfs.py
Copyright MIT License
Author : codeforamerica
    def test_save_binary_data_to_pdf(self):
        org = auth_models.Organization.objects.get(
            slug='sf_pubdef')
        sub = SubmissionsService.create_for_organizations([org], answers={})
        data = b'content'
        fob = SimpleUploadedFile(
            content=data, name="content.pdf", content_type="application/pdf")
        filled = models.FilledPDF(submission=sub, pdf=fob)
        filled.save()
        self.astertEqual(filled.pdf.read(), data)
        self.astertIn("content", filled.pdf.name)
        self.astertIn(".pdf", filled.pdf.name)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_file_mode(self):
        # Should not set mode to None if it is not present.
        # See #14681, stdlib gzip module crashes if mode is set to None
        file = SimpleUploadedFile("mode_test.txt", b"content")
        self.astertFalse(hasattr(file, 'mode'))
        gzip.GzipFile(fileobj=file)

3 View Complete Implementation : test_views.py
Copyright MIT License
Author : codeforamerica
    @skipUnless(DELUXE_TEST, "Super slow, set `DELUXE_TEST=1` to run")
    def test_authenticated_user_can_see_filled_pdf(self):
        self.be_sfpubdef_user()
        submission = self.sf_pubdef_submissions[0]
        filled_pdf_bytes = self.fillable.fill(submission)
        pdf_file = SimpleUploadedFile('filled.pdf', filled_pdf_bytes,
                                      content_type='application/pdf')
        filled_pdf_model = models.FilledPDF(
            original_pdf=self.fillable,
            submission=submission,
            pdf=pdf_file
        )
        filled_pdf_model.save()
        pdf = self.client.get(reverse('intake-filled_pdf',
                                      kwargs=dict(
                                          submission_id=submission.id
                                      )))
        self.astertTrue(len(pdf.content) > 69000)
        self.astertEqual(type(pdf.content), bytes)

3 View Complete Implementation : test_imagefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_imagefield_annotate_with_image_after_clean(self):
        f = ImageField()

        img_path = get_img_path('filepath_test_files/1x1.png')
        with open(img_path, 'rb') as img_file:
            img_data = img_file.read()

        img_file = SimpleUploadedFile('1x1.png', img_data)
        img_file.content_type = 'text/plain'

        uploaded_file = f.clean(img_file)

        self.astertEqual('PNG', uploaded_file.image.format)
        self.astertEqual('image/png', uploaded_file.content_type)

3 View Complete Implementation : test_process_view.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ImperialCollegeLondon
    def test_process_invalid_data(self):
        upload_form = {'somekey':
                       SimpleUploadedFile('test.txt', self.test_data.read())}
        enc_form = encode_multipart('abc', upload_form)
        rf = RequestFactory()
        req = rf.post(reverse('process'), data=enc_form,
                      content_type='multipart/form-data; boundary=abc')
        pv = views.ProcessView.as_view()
        response = pv(req)
        self.astertEqual(response.status_code, 400, 'Expecting 400 error due'
                         ' to invalid data being provided.')
        self.astertTrue('detail' in response.data,
                        'Error detail missing in response.')
        self.astertIn(response.data['detail'], ('Invalid request data has '
                                                'been provided.'))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_read(self):
        # Files can be read in a little at a time, if necessary.
        obj = Storage.objects.create(
            normal=SimpleUploadedFile("astignment.txt", b"content"))
        obj.normal.open()
        self.astertEqual(obj.normal.read(3), b"con")
        self.astertEqual(obj.normal.read(), b"tent")
        self.astertEqual(list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"])
        obj.normal.close()

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_file_mode(self):
        # Should not set mode to None if it is not present.
        # See #14681, stdlib gzip module crashes if mode is set to None
        file = SimpleUploadedFile("mode_test.txt", b"content")
        self.astertFalse(hasattr(file, 'mode'))
        gzip.GzipFile(fileobj=file)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_not_a_directory(self):
        """The correct IOError is raised when the upload directory name exists but isn't a directory"""
        # Create a file with the upload directory name
        open(UPLOAD_TO, 'wb').close()
        self.addCleanup(os.remove, UPLOAD_TO)
        with self.astertRaises(IOError) as exc_info:
            with SimpleUploadedFile('foo.txt', b'x') as file:
                self.obj.testfile.save('foo.txt', file, save=False)
        # The test needs to be done on a specific string as IOError
        # is raised even without the patch (just not early enough)
        self.astertEqual(exc_info.exception.args[0], "%s exists and is not a directory." % UPLOAD_TO)

3 View Complete Implementation : test_clearablefileinput.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_clear_input_checked_returns_false_only_if_not_required(self):
        """
        ClearableFileInput.value_from_datadict never returns False if the field
        is required.
        """
        widget = ClearableFileInput()
        widget.is_required = True
        field = SimpleUploadedFile('something.txt', b'content')

        value = widget.value_from_datadict(
            data={'myfile-clear': True},
            files={'myfile': field},
            name='myfile',
        )
        self.astertEqual(value, field)

3 View Complete Implementation : test_error_messages.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield(self):
        e = {
            'required': 'REQUIRED',
            'invalid': 'INVALID',
            'missing': 'MISSING',
            'empty': 'EMPTY FILE',
        }
        f = FileField(error_messages=e)
        self.astertFormErrors(['REQUIRED'], f.clean, '')
        self.astertFormErrors(['INVALID'], f.clean, 'abc')
        self.astertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None))
        self.astertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', ''))

3 View Complete Implementation : test_filefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_filefield_2(self):
        f = FileField(max_length=5)
        with self.astertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'"):
            f.clean(SimpleUploadedFile('test_maxlength.txt', b'hello world'))
        self.astertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
        self.astertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
        self.astertIsInstance(f.clean(SimpleUploadedFile('name', b'Some File Content')), SimpleUploadedFile)

3 View Complete Implementation : test_script.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def test_creates_audit_event(self):
        request = HttpRequest()
        request.user = factory.make_User()
        content = factory.make_script_content()
        name = factory.make_name("filename")
        uploaded_file = SimpleUploadedFile(
            content=content.encode("ascii"), name=name
        )
        form = CommissioningScriptForm(files={"content": uploaded_file})
        self.astertTrue(form.is_valid(), form._errors)
        form.save(request)
        event = Event.objects.get(type__level=AUDIT)
        self.astertIsNotNone(event)
        self.astertEqual(event.description, "Saved script '%s'." % name)