1#!/usr/local/bin/python3.8
2# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
3#
4# This file is part of the LibreOffice project.
5#
6# This Source Code Form is subject to the terms of the Mozilla Public
7# License, v. 2.0. If a copy of the MPL was not distributed with this
8# file, You can obtain one at http://mozilla.org/MPL/2.0/.
9#
10
11import unittest
12
13from org.libreoffice.unotest import UnoInProcess
14from com.sun.star.lang import IllegalArgumentException
15
16class TestXTextContent(unittest.TestCase):
17
18    @classmethod
19    def setUpClass(cls):
20        cls._uno = UnoInProcess()
21        cls._uno.setUp()
22
23    @classmethod
24    def tearDownClass(cls):
25        cls._uno.tearDown()
26
27    def test_anchor_operations(self):
28        x_doc = self._uno.openDocFromTDOC("xtextcontent.odt")
29        self.assertIsNotNone(x_doc)
30
31        # getAnchor for both text frames and ensure we receive ranges we expect
32        x_frame_1 = self.get_text_frame("Frame1")
33        x_range_1 = x_frame_1.getAnchor()
34        self.assertIsNotNone(x_range_1)
35        self.compare_range(x_range_1, "String1")
36
37        x_frame_2 = self.get_text_frame("Frame2")
38        x_range_2 = x_frame_2.getAnchor()
39        self.assertIsNotNone(x_range_2)
40        self.compare_range(x_range_2, "String2")
41
42        # Check how XTextContent::attach works. Try to exchange anchors
43        x_frame_1.attach(x_range_2)
44        x_frame_2.attach(x_range_1)
45        self.compare_range(x_frame_1.getAnchor(), "String2")
46        self.compare_range(x_frame_2.getAnchor(), "String1")
47
48        # Try to attach to None
49        with self.assertRaises(IllegalArgumentException):
50            x_frame_1.attach(None)
51
52        # Trying to attach frame to range from other document
53        x_doc_2 = self._uno.openDocFromTDOC("xcontrolshape.odt")
54        with self.assertRaises(IllegalArgumentException):
55            x_frame_1.attach(x_doc_2.getText())
56
57        x_doc_2.close(True)
58        x_doc.close(True)
59
60    def get_text_frame(self, frame_name):
61        x_test_frames = self._uno.getDoc().getTextFrames()
62        self.assertIsNotNone(x_test_frames)
63
64        x_test_frame = x_test_frames[frame_name]
65        self.assertIsNotNone(x_test_frame)
66
67        return x_test_frame
68
69    # Helper to extract text content from range and compare to expected string
70    def compare_range(self, x_range, expected_content):
71        x_cursor = x_range.getText().createTextCursor()
72        self.assertIsNotNone(x_cursor)
73
74        x_cursor.collapseToStart()
75        x_cursor.goRight(len(expected_content), True)
76        self.assertEqual(x_cursor.getString(), expected_content)
77
78if __name__ == '__main__':
79    unittest.main()
80
81# vim: set shiftwidth=4 softtabstop=4 expandtab:
82