Example #1
2
def download_replies(modeladmin, request, queryset):
    output = BytesIO()
    workbook = Workbook(output, {"in_memory": True})
    sheet = workbook.add_worksheet("test")

    question_columns = OrderedDict()
    max_column = 0
    row = 1
    for reply in queryset:
        for question in reply.answers.keys():
            current_column = question_columns.get(question, max_column)
            if current_column == max_column:
                question_columns[question] = max_column
                max_column += 1
            sheet.write(row, current_column, reply.answers[question])
        row += 1

    responses = {}
    for reply in queryset:
        for question in reply.answers.keys():
            if responses.get(question) is None:
                responses[question] = []
            responses[question].append(reply.answers[question])
    for question in question_columns.keys():
        sheet.write(0, question_columns[question], question)

    workbook.close()
    output.seek(0)
    response = HttpResponse(
        output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )
    response["Content-Disposition"] = "attachment; filename=test.xlsx"
    return response
Example #2
0
class FakePayload(object):
    """
    A wrapper around BytesIO that restricts what can be read since data from
    the network can't be seeked and cannot be read outside of its content
    length. This makes sure that views can't do anything under the test client
    that wouldn't work in Real Life.
    """

    def __init__(self, content=None):
        self.__content = BytesIO()
        self.__len = 0
        self.read_started = False
        if content is not None:
            self.write(content)

    def __len__(self):
        return self.__len

    def read(self, num_bytes=None):
        if not self.read_started:
            self.__content.seek(0)
            self.read_started = True
        if num_bytes is None:
            num_bytes = self.__len or 0
        assert self.__len >= num_bytes, "Cannot read more than the available bytes from the HTTP incoming data."
        content = self.__content.read(num_bytes)
        self.__len -= num_bytes
        return content

    def write(self, content):
        if self.read_started:
            raise ValueError("Unable to write a payload after he's been read")
        content = force_bytes(content)
        self.__content.write(content)
        self.__len += len(content)
Example #3
0
    def getStationName(self):
        int_array = c_int * 8
        i_buf = int_array(0, 0, 0, 0, 0, 0, 0, 0)
        st_buf = create_string_buffer(128)

        log.debug("************************* getStationName START **************************")

        result = self.libfax_marvell.create_packet(GET_FAX_SETTINGS, 0, 0, 0, 0, byref(i_buf))

        buf = memoryview(i_buf)
        self.writeMarvellFax(buf)
        # self.closeMarvellFax()

        ret_buf = BytesIO()
        while self.readMarvellFax(512, ret_buf, timeout=10):
            pass

        ret_buf = ret_buf.getvalue()
        self.closeMarvellFax()

        response = self.libfax_marvell.extract_response(ret_buf)
        log.debug("getStationName: response is %d" % response)

        result = self.libfax_marvell.extract_station_name(ret_buf, st_buf)
        log.debug("getStationName: station_name=%s ; result is %d" % (st_buf.value, result))

        log.debug("************************* getStationName END **************************")
        return st_buf.value.decode("utf-8")
Example #4
0
def doImageRender(graphClass, graphOptions):
    pngData = BytesIO()
    img = graphClass(**graphOptions)
    img.output(pngData)
    imageData = pngData.getvalue()
    pngData.close()
    return imageData
Example #5
0
def add_quick_start_guide(library_view, db_images):
    from calibre.ebooks.metadata.meta import get_metadata
    from calibre.ebooks import calibre_cover
    from calibre.utils.zipfile import safe_replace
    from calibre.utils.localization import get_lang, canonicalize_lang
    from calibre.ptempfile import PersistentTemporaryFile

    l = canonicalize_lang(get_lang()) or "eng"
    gprefs["quick_start_guide_added"] = True
    imgbuf = BytesIO(calibre_cover(_("Quick Start Guide"), "", author_size=8))
    try:
        with open(P("quick_start/%s.epub" % l), "rb") as src:
            buf = BytesIO(src.read())
    except EnvironmentError as err:
        if err.errno != errno.ENOENT:
            raise
        with open(P("quick_start/eng.epub"), "rb") as src:
            buf = BytesIO(src.read())
    safe_replace(buf, "images/cover.jpg", imgbuf)
    buf.seek(0)
    mi = get_metadata(buf, "epub")
    with PersistentTemporaryFile(".epub") as tmp:
        tmp.write(buf.getvalue())
    library_view.model().add_books([tmp.name], ["epub"], [mi])
    os.remove(tmp.name)
    library_view.model().books_added(1)
    if hasattr(db_images, "reset"):
        db_images.reset()
    if library_view.model().rowCount(None) < 3:
        library_view.resizeColumnsToContents()
Example #6
0
 def test_writer_flush_error(self):
     s = BytesIO()
     s = tcp.Writer(s)
     o = mock.MagicMock()
     o.flush = mock.MagicMock(side_effect=socket.error)
     s.o = o
     tutils.raises(TcpDisconnect, s.flush)
Example #7
0
 def test_simple_bytesio(self):
     f = BytesIO()
     c = Commit()
     c.committer = c.author = b"Jelmer <jelmer@samba.org>"
     c.commit_time = c.author_time = 1271350201
     c.commit_timezone = c.author_timezone = 0
     c.message = b"This is the first line\nAnd this is the second line.\n"
     c.tree = Tree().id
     write_commit_patch(f, c, b"CONTENTS", (1, 1), version="custom")
     f.seek(0)
     lines = f.readlines()
     self.assertTrue(lines[0].startswith(b"From 0b0d34d1b5b596c928adc9a727a4b9e03d025298"))
     self.assertEqual(lines[1], b"From: Jelmer <jelmer@samba.org>\n")
     self.assertTrue(lines[2].startswith(b"Date: "))
     self.assertEqual(
         [
             b"Subject: [PATCH 1/1] This is the first line\n",
             b"And this is the second line.\n",
             b"\n",
             b"\n",
             b"---\n",
         ],
         lines[3:8],
     )
     self.assertEqual([b"CONTENTS-- \n", b"custom\n"], lines[-2:])
     if len(lines) >= 12:
         # diffstat may not be present
         self.assertEqual(lines[8], b" 0 files changed\n")
Example #8
0
File: utils.py Project: jaysw/ipydb
class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        try:
            self.writer.writerow([s.decode("utf8").encode("utf-8") if isinstance(s, basestring) else s for s in row])
        except:
            self.writer.writerow([s.encode("utf-8") if isinstance(s, basestring) else s for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)
Example #9
0
def _pickle_array(arr):
    arr = arr.view(np.ndarray)

    buf = BytesIO()
    write_array(buf, arr)

    return buf.getvalue()
Example #10
0
def generar_pdf(request):
    print "Genero el PDF"
    response = HttpResponse(content_type="application/pdf")
    pdf_name = "clientes.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18)
    mercaderias = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Ingreso de Mercaderia", styles["Heading1"])
    mercaderias.append(header)
    headings = ("Codigo", "Fecha de ingreso", "Total", "Proveedor")
    allMercaderi = [
        (m.id, m.fec_mercaderia, m.tot_mercaderia, (Proveedor.objects.get(id=m.proveedor_id)))
        for m in Mercaderia.objects.all()
    ]
    print allMercaderi

    t = Table([headings] + allMercaderi)
    t.setStyle(
        TableStyle(
            [
                ("GRID", (0, 0), (3, -1), 1, colors.dodgerblue),
                ("LINEBELOW", (0, 0), (-1, 0), 2, colors.darkblue),
                ("BACKGROUND", (0, 0), (-1, 0), colors.dodgerblue),
            ]
        )
    )
    mercaderias.append(t)
    doc.build(mercaderias)
    response.write(buff.getvalue())
    buff.close()
    return response
Example #11
0
def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get("sizes", [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)])
    width, height = im.size
    filter(lambda x: False if (x[0] > width or x[1] > height or x[0] > 255 or x[1] > 255) else True, sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes) * 16
    for size in sizes:
        width, height = size
        fp.write(struct.pack("B", width))  # bWidth(1)
        fp.write(struct.pack("B", height))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = im.copy()
        tmp.thumbnail(size, Image.LANCZOS)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)
Example #12
0
class CallbackFileWrapper(object):
    """
    Small wrapper around a fp object which will tee everything read into a
    buffer, and when that file is closed it will execute a callback with the
    contents of that buffer.

    All attributes are proxied to the underlying file object.

    This class uses members with a double underscore (__) leading prefix so as
    not to accidentally shadow an attribute.
    """

    def __init__(self, fp, callback):
        self.__buf = BytesIO()
        self.__fp = fp
        self.__callback = callback

    def __getattr__(self, name):
        # The vaguaries of garbage collection means that self.__fp is
        # not always set.  By using __getattribute__ and the private
        # name[0] allows looking up the attribute value and raising an
        # AttributeError when it doesn't exist. This stop thigns from
        # infinitely recursing calls to getattr in the case where
        # self.__fp hasn't been set.
        #
        # [0] https://docs.python.org/2/reference/expressions.html#atom-identifiers
        fp = self.__getattribute__("_CallbackFileWrapper__fp")
        return getattr(fp, name)

    def __is_fp_closed(self):
        try:
            return self.__fp.fp is None
        except AttributeError:
            pass

        try:
            return self.__fp.closed
        except AttributeError:
            pass

        # We just don't cache it then.
        # TODO: Add some logging here...
        return False

    def read(self, amt=None):
        data = self.__fp.read(amt)
        self.__buf.write(data)

        if self.__is_fp_closed():
            if self.__callback:
                self.__callback(self.__buf.getvalue())

            # We assign this to None here, because otherwise we can get into
            # really tricky problems where the CPython interpreter dead locks
            # because the callback is holding a reference to something which
            # has a __del__ method. Setting this to None breaks the cycle
            # and allows the garbage collector to do it's thing normally.
            self.__callback = None

        return data
Example #13
0
def test_read_opts():
    # tests if read is seeing option sets, at initialization and after
    # initialization
    arr = np.arange(6).reshape(1, 6)
    stream = BytesIO()
    savemat_future(stream, {"a": arr})
    rdr = MatFile5Reader_future(stream)
    back_dict = rdr.get_variables()
    rarr = back_dict["a"]
    assert_array_equal(rarr, arr)
    rdr = MatFile5Reader_future(stream, squeeze_me=True)
    assert_array_equal(rdr.get_variables()["a"], arr.reshape((6,)))
    rdr.squeeze_me = False
    assert_array_equal(rarr, arr)
    rdr = MatFile5Reader_future(stream, byte_order=boc.native_code)
    assert_array_equal(rdr.get_variables()["a"], arr)
    # inverted byte code leads to error on read because of swapped
    # header etc
    rdr = MatFile5Reader_future(stream, byte_order=boc.swapped_code)
    assert_raises(Exception, rdr.get_variables)
    rdr.byte_order = boc.native_code
    assert_array_equal(rdr.get_variables()["a"], arr)
    arr = np.array(["a string"])
    stream.truncate(0)
    stream.seek(0)
    savemat_future(stream, {"a": arr})
    rdr = MatFile5Reader_future(stream)
    assert_array_equal(rdr.get_variables()["a"], arr)
    rdr = MatFile5Reader_future(stream, chars_as_strings=False)
    carr = np.atleast_2d(np.array(list(arr.item()), dtype="U1"))
    assert_array_equal(rdr.get_variables()["a"], carr)
    rdr.chars_as_strings = True
    assert_array_equal(rdr.get_variables()["a"], arr)
Example #14
0
def test_save_dict():
    # Test that dict can be saved (as recarray), loaded as matstruct
    d = {"a": 1, "b": 2}
    stream = BytesIO()
    savemat_future(stream, {"dict": d})
    stream.seek(0)
    vals = loadmat(stream)
Example #15
0
    def _process_logo(self, logo, event):
        path = get_archived_file(logo, self.archive_dirs)[1]
        if path is None:
            self.print_error(cformat("%{red!}Logo not found on disk; skipping it"), event_id=event.id)
            return

        try:
            logo_image = Image.open(path)
        except IOError as e:
            self.print_warning("Cannot open {}: {}".format(path, e), event_id=event.id)
            return

        if logo_image.mode == "CMYK":
            self.print_warning("Logo is a CMYK {}; converting to RGB".format(logo_image.format), event_id=event.id)
            # this may result in wrong colors, but there's not much we can do...
            logo_image = logo_image.convert("RGB")

        logo_bytes = BytesIO()
        logo_image.save(logo_bytes, "PNG")
        logo_bytes.seek(0)
        logo_content = logo_bytes.read()
        logo_filename = secure_filename(convert_to_unicode(logo.fileName), "logo")
        logo_filename = os.path.splitext(logo_filename)[0] + ".png"
        event.logo_metadata = {
            "size": len(logo_content),
            "hash": crc32(logo_content),
            "filename": logo_filename,
            "content_type": "image/png",
        }
        event.logo = logo_content
        if not self.quiet:
            self.print_success(cformat("- %{cyan}[Logo] {}").format(logo.fileName), event_id=event.id)
Example #16
0
    def test_make_result_tag_filter(self):
        bytestream = BytesIO()
        stream = TextIOWrapper(bytestream, "utf8", line_buffering=True)
        result, summary = self.make_result(stream, filter_tags=set(["worker-0"]))
        # Generate a bunch of results with tags in the same events that
        # testtools generates them.
        tags = set(["worker-0"])
        result.startTestRun()
        result.status(test_id="pass", test_status="inprogress")
        result.status(test_id="pass", test_status="success", test_tags=tags)
        result.status(test_id="fail", test_status="inprogress")
        result.status(test_id="fail", test_status="fail", test_tags=tags)
        result.status(test_id="xfail", test_status="inprogress")
        result.status(test_id="xfail", test_status="xfail", test_tags=tags)
        result.status(test_id="uxsuccess", test_status="inprogress")
        result.status(test_id="uxsuccess", test_status="uxsuccess", test_tags=tags)
        result.status(test_id="skip", test_status="inprogress")
        result.status(test_id="skip", test_status="skip", test_tags=tags)
        result.stopTestRun()
        self.assertEqual(
            """\
======================================================================
FAIL: fail
tags: worker-0
----------------------------------------------------------------------
Ran 1 tests
FAILED (id=None, failures=1, skips=1)
""",
            bytestream.getvalue().decode("utf8"),
        )
Example #17
0
    def upload_from_string(self, data, content_type="text/plain", client=None):
        """Upload contents of this blob from the provided string.

        .. note::
           The effect of uploading to an existing blob depends on the
           "versioning" and "lifecycle" policies defined on the blob's
           bucket.  In the absence of those policies, upload will
           overwrite any existing contents.

           See the `object versioning
           <https://cloud.google.com/storage/docs/object-versioning>`_ and
           `lifecycle <https://cloud.google.com/storage/docs/lifecycle>`_
           API documents for details.

        :type data: bytes or text
        :param data: The data to store in this blob.  If the value is
                     text, it will be encoded as UTF-8.

        :type content_type: str
        :param content_type: Optional type of content being uploaded. Defaults
                             to ``'text/plain'``.

        :type client: :class:`~google.cloud.storage.client.Client` or
                      ``NoneType``
        :param client: Optional. The client to use.  If not passed, falls back
                       to the ``client`` stored on the blob's bucket.
        """
        if isinstance(data, six.text_type):
            data = data.encode("utf-8")
        string_buffer = BytesIO()
        string_buffer.write(data)
        self.upload_from_file(
            file_obj=string_buffer, rewind=True, size=len(data), content_type=content_type, client=client
        )
Example #18
0
    def _3(self):
        """ python 3 method"""
        boundary = self.boundary
        buf = BytesIO()
        textwriter = io.TextIOWrapper(buf, "utf8", newline="", write_through=True)

        for (key, value) in self.form_fields:
            textwriter.write(
                "--{boundary}\r\n"
                'Content-Disposition: form-data; name="{key}"\r\n\r\n'
                "{value}\r\n".format(boundary=boundary, key=key, value=value)
            )
        for (key, filename, mimetype, filepath) in self.files:
            if os.path.isfile(filepath):
                textwriter.write(
                    "--{boundary}\r\n"
                    'Content-Disposition: form-data; name="{key}"; '
                    'filename="{filename}"\r\n'
                    "Content-Type: {content_type}\r\n\r\n".format(
                        boundary=boundary, key=key, filename=filename, content_type=mimetype
                    )
                )
                with open(filepath, "rb") as f:
                    shutil.copyfileobj(f, buf)
                textwriter.write("\r\n")
        textwriter.write("--{}--\r\n\r\n".format(boundary))
        self.form_data = buf.getvalue()
Example #19
0
def create_epub(manifest, spine=(), guide=(), meta_cover=None, ver=3):
    mo = []
    for name, data, properties in manifest:
        mo.append(
            '<item id="%s" href="%s" media-type="%s" %s/>'
            % (name, name, guess_type(name), ('properties="%s"' % properties if properties else ""))
        )
    mo = "".join(mo)
    metadata = ""
    if meta_cover:
        metadata = '<meta name="cover" content="%s"/>' % meta_cover
    if not spine:
        spine = [x[0] for x in manifest if guess_type(x[0]) in OEB_DOCS]
    spine = "".join('<itemref idref="%s"/>' % name for name in spine)
    guide = "".join('<reference href="%s" type="%s" title="%s"/>' % (name, typ, title) for name, typ, title in guide)
    opf = OPF_TEMPLATE.format(manifest=mo, ver="%d.0" % ver, metadata=metadata, spine=spine, guide=guide)
    buf = BytesIO()
    with ZipFile(buf, "w", ZIP_STORED) as zf:
        zf.writestr(
            "META-INF/container.xml",
            b"""
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
   <rootfiles>
      <rootfile full-path="content.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>""",
        )
        zf.writestr("content.opf", opf.encode("utf-8"))
        for name, data, properties in manifest:
            if isinstance(data, type("")):
                data = data.encode("utf-8")
            zf.writestr(name, data)
    buf.seek(0)
    return buf
Example #20
0
def get_printable_message_args(msg, buff=None, prefix=""):
    """
    Get string representation of msg arguments
    :param msg: msg message to fill, ``Message``
    :param prefix: field name prefix (for verbose printing), ``str``
    :returns: printable representation of  msg args, ``str``
    """
    try:
        from cStringIO import StringIO  # Python 2.x

        python3 = 0
    except ImportError:
        from io import BytesIO  # Python 3.x

        python3 = 1

    if buff is None:
        if python3 == 1:
            buff = BytesIO()
        else:
            buff = StringIO()
    for f in msg.__slots__:
        if isinstance(getattr(msg, f), Message):
            get_printable_message_args(getattr(msg, f), buff=buff, prefix=(prefix + f + "."))
        else:
            buff.write(prefix + f + " ")
    return buff.getvalue().rstrip()
Example #21
0
 def test_object_diff_bin_blob_force(self):
     f = BytesIO()
     # Prepare two slightly different PNG headers
     b1 = Blob.from_string(
         b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52"
         b"\x00\x00\x01\xd5\x00\x00\x00\x9f\x08\x04\x00\x00\x00\x05\x04\x8b"
     )
     b2 = Blob.from_string(
         b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52"
         b"\x00\x00\x01\xd5\x00\x00\x00\x9f\x08\x03\x00\x00\x00\x98\xd3\xb3"
     )
     store = MemoryObjectStore()
     store.add_objects([(b1, None), (b2, None)])
     write_object_diff(f, store, (b"foo.png", 0o644, b1.id), (b"bar.png", 0o644, b2.id), diff_binary=True)
     self.assertEqual(
         [
             b"diff --git a/foo.png b/bar.png",
             b"index f73e47d..06364b7 644",
             b"--- a/foo.png",
             b"+++ b/bar.png",
             b"@@ -1,4 +1,4 @@",
             b" \x89PNG",
             b" \x1a",
             b" \x00\x00\x00",
             b"-IHDR\x00\x00\x01\xd5\x00\x00\x00\x9f\x08\x04\x00\x00\x00\x05\x04\x8b",
             b"\\ No newline at end of file",
             b"+IHDR\x00\x00\x01\xd5\x00\x00\x00\x9f\x08\x03\x00\x00\x00\x98\xd3\xb3",
             b"\\ No newline at end of file",
         ],
         f.getvalue().splitlines(),
     )
Example #22
0
    def testSeekable(self):
        bz2f = BZ2File(fileobj=BytesIO(self.DATA))
        try:
            self.assertTrue(bz2f.seekable())
            bz2f.read()
            self.assertTrue(bz2f.seekable())
        finally:
            bz2f.close()
        self.assertRaises(ValueError, bz2f.seekable)

        bz2f = BZ2File(fileobj=BytesIO(), mode="w")
        try:
            self.assertFalse(bz2f.seekable())
        finally:
            bz2f.close()
        self.assertRaises(ValueError, bz2f.seekable)

        src = BytesIO(self.DATA)
        src.seekable = lambda: False
        bz2f = BZ2File(fileobj=src)
        try:
            self.assertFalse(bz2f.seekable())
        finally:
            bz2f.close()
        self.assertRaises(ValueError, bz2f.seekable)
Example #23
0
 def test_reader_read_error(self):
     s = BytesIO(b"foobar\nfoobar")
     s = tcp.Reader(s)
     o = mock.MagicMock()
     o.read = mock.MagicMock(side_effect=socket.error)
     s.o = o
     tutils.raises(TcpDisconnect, s.read, 10)
Example #24
0
    def encryptPGP(self, mail, keys):
        # initialize variables for encryption
        plaintext = BytesIO(self._extractMIMEPayload(mail))
        ciphertext = BytesIO()
        ctx = gpgme.Context()
        ctx.armor = True
        recipients = list()

        # find public keys
        for key in keys:
            try:
                recipients.append(ctx.get_key(key))
            except:
                print >>sys.stderr, "Couldn't find GPG Key"
                sys.exit(1)
                # encrypt data
        try:
            ctx.encrypt(recipients, gpgme.ENCRYPT_ALWAYS_TRUST, plaintext, ciphertext)
        except:
            print >>sys.stderr, "Encryption failed."
            sys.exit(1)

            # package encrypted data in valid PGP/MIME
        ciphertext.seek(0)
        return self._generatePGPMIME(mail, ciphertext.getvalue())
Example #25
0
File: region.py Project: Zemoj/NBT
 def write_chunk(self, x, z, nbt_file):
     """
     Pack the NBT file as binary data, and write to file in a compressed format.
     """
     data = BytesIO()
     nbt_file.write_file(buffer=data)  # render to buffer; uncompressed
     self.write_blockdata(x, z, data.getvalue())
Example #26
0
def install_icon_theme(theme, f):
    icdir = os.path.abspath(os.path.join(config_dir, "resources", "images"))
    if not os.path.exists(icdir):
        os.makedirs(icdir)
    theme["files"] = set()
    metadata_file = os.path.join(icdir, "icon-theme.json")
    with ZipFile(f) as zf:
        for name in zf.namelist():
            if ".." in name or name == "blank.png":
                continue
            base = icdir
            if "/" in name:
                base = os.path.join(icdir, os.path.dirname(name))
                if not os.path.exists(base):
                    os.makedirs(base)
            destpath = os.path.abspath(os.path.join(base, os.path.basename(name)))
            if not destpath.startswith(icdir):
                continue
            with zf.open(name) as src:
                safe_copy(src, destpath)
            theme["files"].add(name)

    theme["files"] = tuple(theme["files"])
    buf = BytesIO()
    json.dump(theme, buf, indent=2)
    buf.seek(0)
    safe_copy(buf, metadata_file)
Example #27
0
    def test_dash_dash_help_shows_help(self):
        bytestream = BytesIO()
        stdout = TextIOWrapper(bytestream, "utf8", line_buffering=True)
        stdin = StringIO()
        stderr = StringIO()
        ui = cli.UI(["--help"], stdin, stdout, stderr)
        cmd = commands.Command(ui)
        cmd.args = [arguments.string.StringArgument("foo")]
        cmd.name = "bar"
        # By definition SystemExit is not caught by 'except Exception'.
        try:
            ui.set_command(cmd)
        except SystemExit:
            exc_info = sys.exc_info()
            self.assertThat(exc_info, MatchesException(SystemExit(0)))
        else:
            self.fail("ui.set_command did not raise")
        self.assertThat(
            bytestream.getvalue().decode("utf8"),
            DocTestMatches(
                """Usage: run.py bar [options] foo
...
A command that can be run...
...
  -d HERE, --here=HERE...
...""",
                doctest.ELLIPSIS,
            ),
        )
Example #28
0
 def test_subunit_output(self):
     bytestream = BytesIO()
     stream = TextIOWrapper(bytestream, "utf8", line_buffering=True)
     result = self.make_result(stream, argv=["--subunit"])[0]
     result.startTestRun()
     result.stopTestRun()
     self.assertEqual(b"", bytestream.getvalue())
Example #29
0
    def flush(self):
        if not self.isOpen():
            self.open()

        data = self.__wbuf.getvalue()
        self.__wbuf = BytesIO()

        self._session.headers["Accept"] = "application/vnd.apache.thrift.binary"
        self._session.headers["Content-Type"] = "application/vnd.apache.thrift.binary"
        self._session.headers["Content-Length"] = str(len(data))
        self._session.headers["Host"] = self.__urlparse.hostname

        try:
            response = self._session.post(self.__uri, data=data, timeout=self.__timeout, auth=self.__auth)
            response.raise_for_status()
            self.__rbuf = BytesIO(response.content)
        except request_exceptions.Timeout:
            raise TTransportException(
                type=TTransportException.TIMED_OUT, message="Timed out talking to %s" % self.__uri
            )
        except request_exceptions.RequestException as e:
            if e.response is not None:
                log.debug("Request failed, response headers:")
                for field_name, field_value in e.response.headers.items():
                    log.debug("  %s: %s" % (field_name, field_value))
                if e.response.status_code in (401, 403):
                    raise self.AuthError(e)
            raise TTransportException(
                type=TTransportException.UNKNOWN, message="Unknown error talking to %s: %s" % (self.__uri, e)
            )
class TestFileUploadParser(TestCase):
    def setUp(self):
        class MockRequest(object):
            pass

        from io import BytesIO

        self.stream = BytesIO("Test text file".encode("utf-8"))
        request = MockRequest()
        request.upload_handlers = (MemoryFileUploadHandler(),)
        request.META = {
            "HTTP_CONTENT_DISPOSITION": "Content-Disposition: inline; filename=file.txt",
            "HTTP_CONTENT_LENGTH": 14,
        }
        self.parser_context = {"request": request, "kwargs": {}}

    def test_parse(self):
        """ Make sure the `QueryDict` works OK """
        parser = FileUploadParser()
        self.stream.seek(0)
        data_and_files = parser.parse(self.stream, None, self.parser_context)
        file_obj = data_and_files.files["file"]
        self.assertEqual(file_obj._size, 14)

    def test_get_filename(self):
        parser = FileUploadParser()
        filename = parser.get_filename(self.stream, None, self.parser_context)
        self.assertEqual(filename, "file.txt")