Changeset - 5978c2f0c244
[Not reviewed]
0 2 0
Brett Smith - 4 years ago 2020-06-28 03:12:35
brettcsmith@brettcsmith.org
reports: Remove BaseODS.style_dividerline.

Obsoleted by the new border_style() method.
2 files changed with 5 insertions and 12 deletions:
0 comments (0 inline, 0 general)
conservancy_beancount/reports/core.py
Show inline comments
...
 
@@ -896,200 +896,192 @@ class BaseODS(BaseSpreadsheet[RT, ST], metaclass=abc.ABCMeta):
 
        If you pass in one style argument, returns that style unchanged.
 
        If you pass in a style that doesn't already exist in the document,
 
        or if you pass in styles that can't be merged (because they have
 
        conflicting attributes), raises ValueError.
 
        """
 
        name_map: Dict[str, odf.style.Style] = {}
 
        for name in self._merge_style_iter_names(styles):
 
            source = odf.style.Style(name=name)
 
            found = self.find_child(self.document.styles, source)
 
            if found is None:
 
                raise ValueError(f"no style named {name!r}")
 
            name_map[name] = found
 
        if not name_map:
 
            retval = None
 
        elif len(name_map) == 1:
 
            _, retval = name_map.popitem()
 
        else:
 
            new_name = f'Merge_{"_".join(sorted(name_map))}'
 
            retval = self.ensure_child(
 
                self.document.styles, odf.style.Style, name=new_name,
 
            )
 
            if retval.firstChild is None:
 
                self._merge_styles(retval, name_map.values())
 
        return retval
 

	
 
    ### Sheets
 

	
 
    def lock_first_row(self, sheet: Optional[odf.table.Table]=None) -> None:
 
        """Lock the first row of cells under the given sheet
 

	
 
        This method sets all the appropriate settings to "lock" the first row
 
        of cells in a sheet, so it stays in view even as the viewer scrolls
 
        through rows. If a sheet is not given, works on ``self.sheet``.
 
        """
 
        if sheet is None:
 
            sheet = self.sheet
 
        config_map = self.ensure_config_map_entry(
 
            self.view, 'Tables', sheet.getAttribute('name'),
 
        )
 
        self.set_config(config_map, 'PositionBottom', 1, 'int')
 
        self.set_config(config_map, 'VerticalSplitMode', 2, 'short')
 
        self.set_config(config_map, 'VerticalSplitPosition', 1, 'short')
 

	
 
    def use_sheet(self, name: str) -> odf.table.Table:
 
        """Switch the active sheet ``self.sheet`` to the one with the given name
 

	
 
        If there is no sheet with the given name, create it and append it to
 
        the spreadsheet first.
 

	
 
        If the current active sheet is empty when this method is called, it
 
        will be removed from the spreadsheet.
 
        """
 
        try:
 
            empty_sheet = not self.sheet.hasChildNodes()
 
        except AttributeError:
 
            empty_sheet = False
 
        if empty_sheet:
 
            self.document.spreadsheet.removeChild(self.sheet)
 
        self.sheet = self.ensure_child(
 
            self.document.spreadsheet, odf.table.Table, name=name,
 
        )
 
        return self.sheet
 

	
 
    ### Initialization hooks
 

	
 
    def init_settings(self) -> None:
 
        """Hook called to initialize settings
 

	
 
        This method is called by __init__ to populate
 
        ``self.document.settings``. This implementation creates the barest
 
        skeleton structure necessary to support other methods, in particular
 
        ``lock_first_row``.
 
        """
 
        view_settings = self.ensure_child(
 
            self.document.settings, odf.config.ConfigItemSet, name='ooo:view-settings',
 
        )
 
        views = self.ensure_child(
 
            view_settings, odf.config.ConfigItemMapIndexed, name='Views',
 
        )
 
        self.view = self.ensure_child(views, odf.config.ConfigItemMapEntry)
 
        self.set_config(self.view, 'ViewId', 'view1')
 

	
 
    def init_styles(self) -> None:
 
        """Hook called to initialize settings
 

	
 
        This method is called by __init__ to populate
 
        ``self.document.styles``. This implementation creates basic building
 
        block cell styles often used in financial reports.
 
        """
 
        styles = self.document.styles
 
        self.style_bold = self.ensure_child(
 
            styles, odf.style.Style, name='Bold', family='table-cell',
 
        )
 
        self.ensure_child(
 
            self.style_bold, odf.style.TextProperties, fontweight='bold',
 
        )
 
        self.style_dividerline = self.ensure_child(
 
            styles, odf.style.Style, name='DividerLine', family='table-cell',
 
        )
 
        self.ensure_child(
 
            self.style_dividerline,
 
            odf.style.TableCellProperties,
 
            borderbottom='1pt solid #0000ff',
 
        )
 

	
 
        date_style = self.replace_child(styles, odf.number.DateStyle, name='ISODate')
 
        date_style.addElement(odf.number.Year(style='long'))
 
        date_style.addElement(odf.number.Text(text='-'))
 
        date_style.addElement(odf.number.Month(style='long'))
 
        date_style.addElement(odf.number.Text(text='-'))
 
        date_style.addElement(odf.number.Day(style='long'))
 
        self.style_date = self.ensure_child(
 
            styles,
 
            odf.style.Style,
 
            name=f'{date_style.getAttribute("name")}Cell',
 
            family='table-cell',
 
            datastylename=date_style,
 
        )
 

	
 
        self.style_starttext: odf.style.Style
 
        self.style_centertext: odf.style.Style
 
        self.style_endtext: odf.style.Style
 
        for textalign in ['start', 'center', 'end']:
 
            aligned_style = self.replace_child(
 
                styles, odf.style.Style, name=f'{textalign.title()}Text',
 
            )
 
            aligned_style.setAttribute('family', 'table-cell')
 
            aligned_style.addElement(odf.style.ParagraphProperties(textalign=textalign))
 
            setattr(self, f'style_{textalign}text', aligned_style)
 

	
 
    ### Rows and cells
 

	
 
    def add_row(self, *cells: odf.table.TableCell, **attrs: Any) -> odf.table.TableRow:
 
        row = odf.table.TableRow(**attrs)
 
        for cell in cells:
 
            row.addElement(cell)
 
        self.sheet.addElement(row)
 
        return row
 

	
 
    def balance_cell(self, balance: Balance, **attrs: Any) -> odf.table.TableCell:
 
        balance = balance.clean_copy() or balance
 
        balance_currency_count = len(balance)
 
        if balance_currency_count == 0:
 
            return self.float_cell(0, **attrs)
 
        elif balance_currency_count == 1:
 
            amount = next(iter(balance.values()))
 
            attrs['stylename'] = self.merge_styles(
 
                attrs.get('stylename'), self.currency_style(amount.currency),
 
            )
 
            return self.currency_cell(amount, **attrs)
 
        else:
 
            lines = [babel.numbers.format_currency(
 
                number, currency, locale=self.locale, format_type=self.currency_fmt_key,
 
            ) for number, currency in balance.values()]
 
            attrs['stylename'] = self.merge_styles(
 
                attrs.get('stylename'), self.style_endtext,
 
            )
 
            return self.multiline_cell(lines, **attrs)
 

	
 
    def currency_cell(self, amount: data.Amount, **attrs: Any) -> odf.table.TableCell:
 
        if 'stylename' not in attrs:
 
            attrs['stylename'] = self.currency_style(amount.currency)
 
        number, currency = amount
 
        cell = odf.table.TableCell(valuetype='currency', value=number, **attrs)
 
        cell.addElement(odf.text.P(text=babel.numbers.format_currency(
 
            number, currency, locale=self.locale, format_type=self.currency_fmt_key,
 
        )))
 
        return cell
 

	
 
    def date_cell(self, date: datetime.date, **attrs: Any) -> odf.table.TableCell:
 
        attrs.setdefault('stylename', self.style_date)
 
        cell = odf.table.TableCell(valuetype='date', datevalue=date, **attrs)
 
        cell.addElement(odf.text.P(text=date.isoformat()))
 
        return cell
 

	
 
    def float_cell(self, value: Union[int, float, Decimal], **attrs: Any) -> odf.table.TableCell:
 
        cell = odf.table.TableCell(valuetype='float', value=value, **attrs)
 
        cell.addElement(odf.text.P(text=str(value)))
 
        return cell
 

	
 
    def _meta_link_pairs(self, links: Iterable[Optional[str]]) -> Iterator[Tuple[str, str]]:
 
        for href in links:
 
            if href is None:
 
                continue
 
            elif self.rt_wrapper is not None:
 
                rt_ids = self.rt_wrapper.parse(href)
 
                rt_href = rt_ids and self.rt_wrapper.url(*rt_ids)
 
            else:
 
                rt_ids = None
 
                rt_href = None
 
            if rt_ids is None or rt_href is None:
 
                # '..' pops the ODS filename off the link path. In other words,
 
                # make the link relative to the directory the ODS is in.
 
                href_path = Path('..', href)
 
                href = str(href_path)
 
                text = href_path.name
 
            else:
 
                rt_path = urlparse.urlparse(rt_href).path
 
                if rt_path.endswith('/Ticket/Display.html'):
 
                    text = rtutil.RT.unparse(*rt_ids)
tests/test_reports_spreadsheet.py
Show inline comments
...
 
@@ -208,286 +208,287 @@ def test_ods_writer_use_sheet_returns_to_prior_sheets(ods_writer):
 
    for name in names:
 
        sheets.append(ods_writer.use_sheet(name))
 
        ods_writer.write([(name,)])
 
    for name, expected in zip(names, sheets):
 
        actual = ods_writer.use_sheet(name)
 
        assert actual is expected
 
        texts = [cell.text for row in testutil.ODSCell.from_sheet(actual)
 
                 for cell in row]
 
        assert texts == [name]
 

	
 
def test_ods_writer_use_sheet_discards_unused_sheets(ods_writer):
 
    ods_writer.use_sheet('Three')
 
    ods_writer.use_sheet('Two')
 
    ods_writer.use_sheet('One')
 
    sheets = ods_writer.document.getElementsByType(odf.table.Table)
 
    assert len(sheets) == 1
 
    assert sheets[0].getAttribute('name') == 'One'
 

	
 
@pytest.mark.parametrize('width,expect_name', [
 
    ('.750', 'col_0_75in'),
 
    (2, 'col_2in'),
 
    ('2.2in', 'col_2_2in'),
 
    (3.5, 'col_3_5in'),
 
    ('4cm', 'col_4cm'),
 
])
 
def test_ods_column_style(ods_writer, width, expect_name):
 
    style = ods_writer.column_style(width)
 
    assert style.getAttribute('name') == expect_name
 
    assert style.getAttribute('family') == 'table-column'
 
    curr_style = get_child(
 
        ods_writer.document.automaticstyles,
 
        odf.style.Style,
 
        name=expect_name,
 
    )
 
    assert get_child(
 
        curr_style,
 
        odf.style.TableColumnProperties,
 
        columnwidth=expect_name[4:].replace('_', '.'),
 
    )
 

	
 
def test_ods_column_style_caches(ods_writer):
 
    int_width = ods_writer.column_style('1in')
 
    float_width = ods_writer.column_style('1.00in')
 
    assert int_width is float_width
 

	
 
@pytest.mark.parametrize('width', [
 
    '1mi',
 
    '0in',
 
    '-1cm',
 
    'in',
 
    '.cm',
 
])
 
def test_ods_column_style_invalid_width(ods_writer, width):
 
    with pytest.raises(ValueError):
 
        ods_writer.column_style(width)
 

	
 
@pytest.mark.parametrize('currency_code', [
 
    'USD',
 
    'EUR',
 
    'BRL',
 
])
 
def test_ods_currency_style(ods_writer, currency_code):
 
    style = ods_writer.currency_style(currency_code)
 
    assert style.getAttribute('family') == 'table-cell'
 
    curr_style = get_child(
 
        ods_writer.document.styles,
 
        odf.number.CurrencyStyle,
 
        name=style.getAttribute('datastylename'),
 
    )
 
    check_currency_style(curr_style)
 
    mappings = get_children(curr_style, odf.style.Map)
 
    assert mappings
 
    for mapping in mappings:
 
        check_currency_style(get_child(
 
            ods_writer.document.styles,
 
            odf.number.CurrencyStyle,
 
            name=mapping.getAttribute('applystylename'),
 
        ))
 

	
 
def test_ods_currency_style_caches(ods_writer):
 
    expected = ods_writer.currency_style('USD')
 
    _ = ods_writer.currency_style('EUR')
 
    actual = ods_writer.currency_style('USD')
 
    assert actual is expected
 

	
 
def test_ods_currency_style_cache_considers_properties(ods_writer):
 
    bold_text = odf.style.TextProperties(fontweight='bold')
 
    plain = ods_writer.currency_style('USD')
 
    bold = ods_writer.currency_style('USD', positive_properties=bold_text)
 
    assert plain is not bold
 
    assert plain.getAttribute('name') != bold.getAttribute('name')
 
    assert plain.getAttribute('datastylename') != bold.getAttribute('datastylename')
 

	
 
@pytest.mark.parametrize('attr_name,child_type,checked_attr', [
 
    ('style_bold', odf.style.TextProperties, 'fontweight'),
 
    ('style_centertext', odf.style.ParagraphProperties, 'textalign'),
 
    ('style_dividerline', odf.style.TableCellProperties, 'borderbottom'),
 
    ('style_endtext', odf.style.ParagraphProperties, 'textalign'),
 
    ('style_starttext', odf.style.ParagraphProperties, 'textalign'),
 
])
 
def test_ods_writer_style(ods_writer, attr_name, child_type, checked_attr):
 
    root = ods_writer.document.styles
 
    style = getattr(ods_writer, attr_name)
 
    actual = get_child(root, odf.style.Style, name=style.getAttribute('name'))
 
    assert actual is style
 
    child = get_child(actual, child_type)
 
    assert child.getAttribute(checked_attr)
 

	
 
@pytest.mark.parametrize('edges,width,style,color', [
 
    (core.Border.TOP,
 
     '5px', 'solid', '#ff0000'),
 
    (core.Border.RIGHT | core.Border.LEFT,
 
     '2pt', 'dashed', '#00ff00'),
 
    (core.Border.BOTTOM | core.Border.RIGHT | core.Border.LEFT,
 
     '1em', 'dotted', '#0000ff'),
 
    (core.Border.TOP | core.Border.BOTTOM | core.Border.RIGHT | core.Border.LEFT,
 
     '1cm', 'thick', '#aaaaaa'),
 
])
 
def test_ods_writer_border_style(ods_writer, edges, width, style, color):
 
    actual = ods_writer.border_style(edges, width, style, color)
 
    props, = actual.childNodes
 
    attr_s = f'{width} {style} {color}'
 
    for edge_exp, edge_name in enumerate(['top', 'right', 'bottom', 'left']):
 
        expected = attr_s if edges & (2 ** edge_exp) else None
 
        assert props.getAttribute(f'border{edge_name}') == expected
 

	
 
def test_ods_writer_border_style_caches(ods_writer):
 
    expected = ods_writer.border_style(core.Border.TOP)
 
    width, style, color = expected.childNodes[0].getAttribute('bordertop').split()
 
    actual = ods_writer.border_style(core.Border.TOP, width, style, color)
 
    assert actual is expected
 

	
 
@pytest.mark.parametrize('argname,val1,val2', [
 
    ('edges', core.Border.TOP, core.Border.LEFT),
 
    ('edges', core.Border.TOP, core.Border.TOP | core.Border.BOTTOM),
 
    ('style', 'solid', 'dashed'),
 
    ('width', '1px', '1em'),
 
    ('width', '1px', '2px'),
 
    ('color', '#0000fe', '#0000ff'),
 
])
 
def test_ods_writer_border_no_caching(ods_writer, argname, val1, val2):
 
    kwargs = {'edges': core.Border.TOP}
 
    kwargs[argname] = val1
 
    style1 = ods_writer.border_style(**kwargs)
 
    kwargs[argname] = val2
 
    style2 = ods_writer.border_style(**kwargs)
 
    assert style1 is not style2
 

	
 
def test_ods_writer_merge_styles(ods_writer):
 
    style = ods_writer.merge_styles(ods_writer.style_bold, ods_writer.style_dividerline)
 
    border_style = ods_writer.border_style(core.Border.BOTTOM)
 
    style = ods_writer.merge_styles(ods_writer.style_bold, border_style)
 
    actual = get_child(
 
        ods_writer.document.styles,
 
        odf.style.Style,
 
        name=style.getAttribute('name'),
 
    )
 
    assert actual is style
 
    assert actual.getAttribute('family') == 'table-cell'
 
    text_props = get_child(actual, odf.style.TextProperties)
 
    assert text_props.getAttribute('fontweight') == 'bold'
 
    cell_props = get_child(actual, odf.style.TableCellProperties)
 
    assert cell_props.getAttribute('borderbottom')
 

	
 
def test_ods_writer_merge_styles_with_children_and_attributes(ods_writer):
 
    jpy_style = ods_writer.currency_style('JPY')
 
    style = ods_writer.merge_styles(ods_writer.style_bold, jpy_style)
 
    actual = get_child(
 
        ods_writer.document.styles,
 
        odf.style.Style,
 
        name=style.getAttribute('name'),
 
    )
 
    assert actual is style
 
    assert actual.getAttribute('family') == 'table-cell'
 
    assert actual.getAttribute('datastylename') == jpy_style.getAttribute('datastylename')
 
    text_props = get_child(actual, odf.style.TextProperties)
 
    assert text_props.getAttribute('fontweight') == 'bold'
 

	
 
def test_ods_writer_merge_styles_caches(ods_writer):
 
    sources = [ods_writer.style_bold, ods_writer.style_dividerline]
 
    sources = [ods_writer.style_bold, ods_writer.style_centertext]
 
    style1 = ods_writer.merge_styles(*sources)
 
    style2 = ods_writer.merge_styles(*reversed(sources))
 
    assert style1 is style2
 
    assert get_child(
 
        ods_writer.document.styles,
 
        odf.style.Style,
 
        name=style1.getAttribute('name'),
 
    )
 

	
 
def test_ods_writer_layer_merge_styles(ods_writer):
 
    usd_style = ods_writer.currency_style('USD')
 
    layer1 = ods_writer.merge_styles(ods_writer.style_bold, ods_writer.style_dividerline)
 
    border_style = ods_writer.border_style(core.Border.BOTTOM)
 
    layer1 = ods_writer.merge_styles(ods_writer.style_bold, border_style)
 
    layer2 = ods_writer.merge_styles(layer1, usd_style)
 
    style_name = layer2.getAttribute('name')
 
    assert style_name.count('Merge_') == 1
 
    actual = get_child(
 
        ods_writer.document.styles,
 
        odf.style.Style,
 
        name=style_name,
 
    )
 
    assert actual is layer2
 
    assert actual.getAttribute('family') == 'table-cell'
 
    assert actual.getAttribute('datastylename') == usd_style.getAttribute('datastylename')
 
    text_props = get_child(actual, odf.style.TextProperties)
 
    assert text_props.getAttribute('fontweight') == 'bold'
 
    cell_props = get_child(actual, odf.style.TableCellProperties)
 
    assert cell_props.getAttribute('borderbottom')
 

	
 
def test_ods_writer_merge_one_style(ods_writer):
 
    actual = ods_writer.merge_styles(None, ods_writer.style_bold)
 
    assert actual is ods_writer.style_bold
 

	
 
def test_ods_writer_merge_no_styles(ods_writer):
 
    assert ods_writer.merge_styles() is None
 

	
 
def test_ods_writer_merge_nonexistent_style(ods_writer):
 
    name = 'Non Existent Style'
 
    with pytest.raises(ValueError, match=repr(name)):
 
        ods_writer.merge_styles(ods_writer.style_bold, name)
 

	
 
def test_ods_writer_merge_conflicting_styles(ods_writer):
 
    sources = [ods_writer.currency_style(code) for code in ['USD', 'EUR']]
 
    with pytest.raises(ValueError, match='conflicting datastylename'):
 
        ods_writer.merge_styles(*sources)
 

	
 
def test_ods_writer_date_style(ods_writer):
 
    data_style_name = ods_writer.style_date.getAttribute('datastylename')
 
    actual = get_child(
 
        ods_writer.document.styles,
 
        odf.style.Style,
 
        family='table-cell',
 
        datastylename=data_style_name,
 
    )
 
    assert actual is ods_writer.style_date
 
    data_style = get_child(
 
        ods_writer.document.styles,
 
        odf.number.DateStyle,
 
        name=data_style_name,
 
    )
 
    assert len(data_style.childNodes) == 5
 
    year, t1, month, t2, day = data_style.childNodes
 
    assert year.qname[1] == 'year'
 
    assert year.getAttribute('style') == 'long'
 
    assert get_text(t1) == '-'
 
    assert month.qname[1] == 'month'
 
    assert month.getAttribute('style') == 'long'
 
    assert get_text(t2) == '-'
 
    assert day.qname[1] == 'day'
 
    assert day.getAttribute('style') == 'long'
 

	
 
def test_ods_lock_first_row(ods_writer):
 
    ods_writer.lock_first_row()
 
    view_settings = get_child(
 
        ods_writer.document.settings,
 
        odf.config.ConfigItemSet,
 
        name='ooo:view-settings',
 
    )
 
    views = get_child(view_settings, odf.config.ConfigItemMapIndexed, name='Views')
 
    view1 = get_child(views, odf.config.ConfigItemMapEntry, index=0)
 
    config_map = get_child(view1, odf.config.ConfigItemMapNamed, name='Tables')
 
    sheet_name = ods_writer.sheet.getAttribute('name')
 
    config_entry = get_child(config_map, odf.config.ConfigItemMapEntry, name=sheet_name)
 
    for name, ctype, value in [
 
            ('PositionBottom', 'int', '1'),
 
            ('VerticalSplitMode', 'short', '2'),
 
            ('VerticalSplitPosition', 'short', '1'),
 
    ]:
 
        child = get_child(config_entry, odf.config.ConfigItem, name=name)
 
        assert child.getAttribute('type') == ctype
 
        assert child.firstChild.data == value
 

	
 
@pytest.mark.parametrize('style_name', XML_NAMES_LIST)
 
def test_ods_writer_add_row(ods_writer, style_name):
 
    cell1 = ods_writer.string_cell('one')
 
    cell2 = ods_writer.float_cell(42.0)
 
    row = ods_writer.add_row(cell1, cell2, defaultcellstylename=style_name)
 
    assert ods_writer.sheet.lastChild is row
 
    assert row.getAttribute('defaultcellstylename') == style_name
 
    assert row.firstChild is cell1
 
    assert row.lastChild is cell2
 

	
 
def test_ods_writer_add_row_single_cell(ods_writer):
 
    cell = ods_writer.multilink_cell(LINK_CELL_DATA[:1])
 
    row = ods_writer.add_row(cell)
 
    assert ods_writer.sheet.lastChild is row
 
    assert row.firstChild is cell
 
    assert row.lastChild is cell
 

	
0 comments (0 inline, 0 general)