Ejemplo n.º 1
0
class TestInPlace(object):
    reference_content = u(
        textwrap.dedent("""
        The quick brown fox jumped over the lazy dog.
        """.lstrip()))
    reversed_content = u(
        textwrap.dedent("""
        .god yzal eht revo depmuj xof nworb kciuq ehT
        """.lstrip()))
    alternate_content = u(
        textwrap.dedent("""
          Lorem ipsum dolor sit amet, consectetur adipisicing elit,
        sed do eiusmod tempor incididunt ut labore et dolore magna
        aliqua. Ut enim ad minim veniam, quis nostrud exercitation
        ullamco laboris nisi ut aliquip ex ea commodo consequat.
        Duis aute irure dolor in reprehenderit in voluptate velit
        esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui
        officia deserunt mollit anim id est laborum.
        """.lstrip()))

    @classmethod
    def create_reference(cls, tmpdir):
        p = Path(tmpdir) / 'document'
        with p.open('w') as stream:
            stream.write(cls.reference_content)
        return p

    def test_line_by_line_rewrite(self, tmpdir):
        doc = self.create_reference(tmpdir)
        # reverse all the text in the document, line by line
        with doc.in_place() as (reader, writer):
            for line in reader:
                r_line = ''.join(reversed(line.strip())) + '\n'
                writer.write(r_line)
        with doc.open() as stream:
            data = stream.read()
        assert data == self.reversed_content

    def test_exception_in_context(self, tmpdir):
        doc = self.create_reference(tmpdir)
        with pytest.raises(RuntimeError) as exc:
            with doc.in_place() as (reader, writer):
                writer.write(self.alternate_content)
                raise RuntimeError("some error")
        assert "some error" in str(exc)
        with doc.open() as stream:
            data = stream.read()
        assert not 'Lorem' in data
        assert 'lazy dog' in data
Ejemplo n.º 2
0
    def testStringCompatibility(self):
        """ Test compatibility with ordinary strings. """
        x = path('xyzzy')
        self.assert_(x == 'xyzzy')
        self.assert_(x == u('xyzzy'))

        # sorting
        items = [path('fhj'), path('fgh'), 'E', path('d'), 'A', path('B'), 'c']
        items.sort()
        self.assert_(items == ['A', 'B', 'E', 'c', 'd', 'fgh', 'fhj'])

        # Test p1/p1.
        p1 = path("foo")
        p2 = path("bar")
        self.assertEqual(p1 / p2, p(nt='foo\\bar', posix='foo/bar'))
Ejemplo n.º 3
0
    def testStringCompatibility(self):
        """ Test compatibility with ordinary strings. """
        x = path("xyzzy")
        self.assert_(x == "xyzzy")
        self.assert_(x == u("xyzzy"))

        # sorting
        items = [path("fhj"), path("fgh"), "E", path("d"), "A", path("B"), "c"]
        items.sort()
        self.assert_(items == ["A", "B", "E", "c", "d", "fgh", "fhj"])

        # Test p1/p1.
        p1 = path("foo")
        p2 = path("bar")
        self.assertEqual(p1 / p2, p(nt="foo\\bar", posix="foo/bar"))
Ejemplo n.º 4
0
    def testStringCompatibility(self):
        """ Test compatibility with ordinary strings. """
        x = path('xyzzy')
        self.assert_(x == 'xyzzy')
        self.assert_(x == u('xyzzy'))

        # sorting
        items = [path('fhj'),
                 path('fgh'),
                 'E',
                 path('d'),
                 'A',
                 path('B'),
                 'c']
        items.sort()
        self.assert_(items == ['A', 'B', 'E', 'c', 'd', 'fgh', 'fhj'])

        # Test p1/p1.
        p1 = path("foo")
        p2 = path("bar")
        self.assertEqual(p1/p2, p(nt='foo\\bar', posix='foo/bar'))
Ejemplo n.º 5
0
 def testLinesep(eol):
     p.write_lines(givenLines, enc, linesep=eol)
     p.write_lines(givenLines, enc, linesep=eol, append=True)
     expected = 2 * cleanNoHanging.replace(u('\n'), eol).encode(enc)
     self.assertEqual(p.bytes(), expected)
Ejemplo n.º 6
0
        def test(enc):
            """ Test that path works with the specified encoding,
            which must be capable of representing the entire range of
            Unicode codepoints.
            """

            given = u('Hello world\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\r\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\x85'
                      '\u0d0a\u0a0d\u0d15\u0a15\u2028'
                      '\r'
                      'hanging')
            clean = u('Hello world\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\n'
                      '\n'
                      'hanging')
            givenLines = [
                u('Hello world\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\r\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\x85'),
                u('\u0d0a\u0a0d\u0d15\u0a15\u2028'),
                u('\r'),
                u('hanging')]
            expectedLines = [
                u('Hello world\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\n'),
                u('\n'),
                u('hanging')]
            expectedLines2 = [
                u('Hello world'),
                u('\u0d0a\u0a0d\u0d15\u0a15'),
                u('\u0d0a\u0a0d\u0d15\u0a15'),
                u('\u0d0a\u0a0d\u0d15\u0a15'),
                u(''),
                u('hanging')]

            # write bytes manually to file
            f = codecs.open(p, 'w', enc)
            f.write(given)
            f.close()

            # test all 3 path read-fully functions, including
            # path.lines() in unicode mode.
            self.assertEqual(p.bytes(), given.encode(enc))
            self.assertEqual(p.text(enc), clean)
            self.assertEqual(p.lines(enc), expectedLines)
            self.assertEqual(p.lines(enc, retain=False), expectedLines2)

            # If this is UTF-16, that's enough.
            # The rest of these will unfortunately fail because append=True
            # mode causes an extra BOM to be written in the middle of the file.
            # UTF-16 is the only encoding that has this problem.
            if enc == 'UTF-16':
                return

            # Write Unicode to file using path.write_text().
            cleanNoHanging = clean + u('\n')  # This test doesn't work with a
                                              # hanging line.
            p.write_text(cleanNoHanging, enc)
            p.write_text(cleanNoHanging, enc, append=True)
            # Check the result.
            expectedBytes = 2 * cleanNoHanging.replace('\n',
                                                       os.linesep).encode(enc)
            expectedLinesNoHanging = expectedLines[:]
            expectedLinesNoHanging[-1] += '\n'
            self.assertEqual(p.bytes(), expectedBytes)
            self.assertEqual(p.text(enc), 2 * cleanNoHanging)
            self.assertEqual(p.lines(enc), 2 * expectedLinesNoHanging)
            self.assertEqual(p.lines(enc, retain=False), 2 * expectedLines2)

            # Write Unicode to file using path.write_lines().
            # The output in the file should be exactly the same as last time.
            p.write_lines(expectedLines, enc)
            p.write_lines(expectedLines2, enc, append=True)
            # Check the result.
            self.assertEqual(p.bytes(), expectedBytes)

            # Now: same test, but using various newline sequences.
            # If linesep is being properly applied, these will be converted
            # to the platform standard newline sequence.
            p.write_lines(givenLines, enc)
            p.write_lines(givenLines, enc, append=True)
            # Check the result.
            self.assertEqual(p.bytes(), expectedBytes)

            # Same test, using newline sequences that are different
            # from the platform default.
            def testLinesep(eol):
                p.write_lines(givenLines, enc, linesep=eol)
                p.write_lines(givenLines, enc, linesep=eol, append=True)
                expected = 2 * cleanNoHanging.replace(u('\n'), eol).encode(enc)
                self.assertEqual(p.bytes(), expected)

            testLinesep(u('\n'))
            testLinesep(u('\r'))
            testLinesep(u('\r\n'))
            testLinesep(u('\x0d\x85'))

            # Again, but with linesep=None.
            p.write_lines(givenLines, enc, linesep=None)
            p.write_lines(givenLines, enc, linesep=None, append=True)
            # Check the result.
            expectedBytes = 2 * given.encode(enc)
            self.assertEqual(p.bytes(), expectedBytes)
            self.assertEqual(p.text(enc), 2 * clean)
            expectedResultLines = expectedLines[:]
            expectedResultLines[-1] += expectedLines[0]
            expectedResultLines += expectedLines[1:]
            self.assertEqual(p.lines(enc), expectedResultLines)
Ejemplo n.º 7
0
 def testLinesep(eol):
     p.write_lines(givenLines, enc, linesep=eol)
     p.write_lines(givenLines, enc, linesep=eol, append=True)
     expected = 2 * cleanNoHanging.replace(u('\n'), eol).encode(enc)
     self.assertEqual(p.bytes(), expected)
Ejemplo n.º 8
0
        def test(enc):
            """ Test that path works with the specified encoding,
            which must be capable of representing the entire range of
            Unicode codepoints.
            """

            given = u('Hello world\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\r\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\x85'
                      '\u0d0a\u0a0d\u0d15\u0a15\u2028'
                      '\r'
                      'hanging')
            clean = u('Hello world\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\n'
                      '\u0d0a\u0a0d\u0d15\u0a15\n'
                      '\n'
                      'hanging')
            givenLines = [
                u('Hello world\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\r\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\x85'),
                u('\u0d0a\u0a0d\u0d15\u0a15\u2028'),
                u('\r'),
                u('hanging')
            ]
            expectedLines = [
                u('Hello world\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\n'),
                u('\u0d0a\u0a0d\u0d15\u0a15\n'),
                u('\n'),
                u('hanging')
            ]
            expectedLines2 = [
                u('Hello world'),
                u('\u0d0a\u0a0d\u0d15\u0a15'),
                u('\u0d0a\u0a0d\u0d15\u0a15'),
                u('\u0d0a\u0a0d\u0d15\u0a15'),
                u(''),
                u('hanging')
            ]

            # write bytes manually to file
            f = codecs.open(p, 'w', enc)
            f.write(given)
            f.close()

            # test all 3 path read-fully functions, including
            # path.lines() in unicode mode.
            self.assertEqual(p.bytes(), given.encode(enc))
            self.assertEqual(p.text(enc), clean)
            self.assertEqual(p.lines(enc), expectedLines)
            self.assertEqual(p.lines(enc, retain=False), expectedLines2)

            # If this is UTF-16, that's enough.
            # The rest of these will unfortunately fail because append=True
            # mode causes an extra BOM to be written in the middle of the file.
            # UTF-16 is the only encoding that has this problem.
            if enc == 'UTF-16':
                return

            # Write Unicode to file using path.write_text().
            cleanNoHanging = clean + u('\n')  # This test doesn't work with a
            # hanging line.
            p.write_text(cleanNoHanging, enc)
            p.write_text(cleanNoHanging, enc, append=True)
            # Check the result.
            expectedBytes = 2 * cleanNoHanging.replace('\n',
                                                       os.linesep).encode(enc)
            expectedLinesNoHanging = expectedLines[:]
            expectedLinesNoHanging[-1] += '\n'
            self.assertEqual(p.bytes(), expectedBytes)
            self.assertEqual(p.text(enc), 2 * cleanNoHanging)
            self.assertEqual(p.lines(enc), 2 * expectedLinesNoHanging)
            self.assertEqual(p.lines(enc, retain=False), 2 * expectedLines2)

            # Write Unicode to file using path.write_lines().
            # The output in the file should be exactly the same as last time.
            p.write_lines(expectedLines, enc)
            p.write_lines(expectedLines2, enc, append=True)
            # Check the result.
            self.assertEqual(p.bytes(), expectedBytes)

            # Now: same test, but using various newline sequences.
            # If linesep is being properly applied, these will be converted
            # to the platform standard newline sequence.
            p.write_lines(givenLines, enc)
            p.write_lines(givenLines, enc, append=True)
            # Check the result.
            self.assertEqual(p.bytes(), expectedBytes)

            # Same test, using newline sequences that are different
            # from the platform default.
            def testLinesep(eol):
                p.write_lines(givenLines, enc, linesep=eol)
                p.write_lines(givenLines, enc, linesep=eol, append=True)
                expected = 2 * cleanNoHanging.replace(u('\n'), eol).encode(enc)
                self.assertEqual(p.bytes(), expected)

            testLinesep(u('\n'))
            testLinesep(u('\r'))
            testLinesep(u('\r\n'))
            testLinesep(u('\x0d\x85'))

            # Again, but with linesep=None.
            p.write_lines(givenLines, enc, linesep=None)
            p.write_lines(givenLines, enc, linesep=None, append=True)
            # Check the result.
            expectedBytes = 2 * given.encode(enc)
            self.assertEqual(p.bytes(), expectedBytes)
            self.assertEqual(p.text(enc), 2 * clean)
            expectedResultLines = expectedLines[:]
            expectedResultLines[-1] += expectedLines[0]
            expectedResultLines += expectedLines[1:]
            self.assertEqual(p.lines(enc), expectedResultLines)