Ejemplo n.º 1
0
    def test_stream(self):
        # guess content types from extension
        descriptor = AttachableDescriptor(io.BytesIO(b'Simple text'), extension='.txt')
        self.assertIsInstance(descriptor, StreamDescriptor)
        self.assertEqual(descriptor.content_type, 'text/plain')
        descriptor.seek(2)
        self.assertEqual(descriptor.tell(), 2)
        descriptor.seek(0, os.SEEK_END)
        self.assertEqual(descriptor.tell(), 11)

        # guess extension from original filename
        descriptor = AttachableDescriptor(io.BytesIO(b'Simple text'), original_filename='letter.pdf')
        self.assertEqual(descriptor.extension, '.pdf')

        # guess extension from content type
        descriptor = AttachableDescriptor(io.BytesIO(b'Simple text'), content_type='application/json')
        self.assertEqual(descriptor.extension, '.json')

        self.assertRaises(DescriptorOperationError, lambda: descriptor.filename)
Ejemplo n.º 2
0
    def test_non_seekable(self):
        class NonSeekableStream(io.BytesIO):
            def seekable(self, *args, **kwargs):
                return False

        inp = b'abcdefghijklmnopqrstuvwxyz'
        descriptor = AttachableDescriptor(NonSeekableStream(inp),
                                          header_buffer_size=10)

        # Fetching header, it forces to cache header_buffer_size bytes from
        # header.
        buffer = descriptor.get_header_buffer()
        self.assertEqual(buffer, b'abcdefghij')

        # fetching again to test the cache functionality
        buffer = descriptor.get_header_buffer()
        self.assertEqual(buffer, b'abcdefghij')

        out = b''
        out += descriptor.read(9)
        self.assertEqual(descriptor.tell(), 9)
        out += descriptor.read(11)
        self.assertEqual(descriptor.tell(), 20)
        out += descriptor.read(10)
        self.assertEqual(out, inp)

        # Max length error
        descriptor = AttachableDescriptor(NonSeekableStream(inp),
                                          header_buffer_size=24,
                                          max_length=20)
        buffer = descriptor.get_header_buffer()
        self.assertEqual(buffer, b'abcdefghijklmnopqrstuvwx')
        self.assertRaises(MaximumLengthIsReachedError, descriptor.read, 1)

        # Test getting header buffer after read on non-seekable streams.
        descriptor = AttachableDescriptor(NonSeekableStream(inp),
                                          header_buffer_size=10,
                                          max_length=20)
        self.assertEqual(descriptor.read(10), b'abcdefghij')
        self.assertRaises(DescriptorOperationError,
                          descriptor.get_header_buffer)