Ejemplo n.º 1
0
 def testCustomRow(self):
     table = texttable.TextTable()
     table.header = ('a', 'b', 'c')
     self.failUnlessEqual(type(texttable.Row()), type(table[0]))
     table = texttable.TextTable(row_class=MyRow)
     self.failUnlessEqual(MyRow, table.row_class)
     table.header = ('a', 'b', 'c')
     self.failUnlessEqual(type(MyRow()), type(table[0]))
Ejemplo n.º 2
0
    def _ParseCmdItem(self, cmd_input, template_file=None):
        """Creates Texttable with output of command.

    Args:
      cmd_input: String, Device response.
      template_file: File object, template to parse with.

    Returns:
      TextTable containing command output.

    Raises:
      CliTableError: A template was not found for the given command.
    """
        # Build FSM machine from the template.
        fsm = textfsm.TextFSM(template_file)
        if not self._keys:
            self._keys = set(fsm.GetValuesByAttrib('Key'))

        # Pass raw data through FSM.
        table = texttable.TextTable()
        table.header = fsm.header

        # Fill TextTable from record entries.
        for record in fsm.ParseText(cmd_input):
            table.Append(record)
        return table
Ejemplo n.º 3
0
def GetMaskedInputWithChoices(prompt, regex, choices):
    choiceRegex = re.compile(r'^/(\d+)$')

    table = texttable.TextTable()
    table.SetHorizontalAlignment(
        [texttable.HALIGN_RIGHT, texttable.HALIGN_LEFT, texttable.HALIGN_LEFT])
    table.SetOuterLinesMode(texttable.OUTER_LINES_ALL)
    table.SetHorizontalLinesMode(texttable.HORIZ_LINES_ALL)
    table.SetVerticalLinesMode(texttable.VERT_LINES_FIRST)
    table.AddRow(['Shortcut', 'Choice', ''])
    for curIndex in range(len(choices)):
        table.AddRow([
            '/%d' % curIndex, choices[curIndex][0],
            '(%s)' % choices[curIndex][1]
        ])
    table.Print()

    inputIsValid = False
    while not inputIsValid:
        userInput = raw_input('%s > ' % prompt)
        if (userInput == ''):
            userInput = '/0'

        choiceMatch = choiceRegex.match(userInput)
        if (choiceMatch):
            chosenIndex = int(choiceMatch.group(1))
            if (chosenIndex in range(len(choices))):
                inputIsValid = True
                userInput = choices[chosenIndex][0]
        else:
            inputIsValid = regex.match(userInput)

    return userInput
Ejemplo n.º 4
0
def GetChoice(prompt, choices):
    r'''Returns the index of the chosen choice.'''
    choiceRegex = re.compile(r'^(\d+)$')

    table = texttable.TextTable()
    table.SetHorizontalAlignment(
        [texttable.HALIGN_RIGHT, texttable.HALIGN_LEFT])
    table.SetOuterLinesMode(texttable.OUTER_LINES_ALL)
    table.SetHorizontalLinesMode(texttable.HORIZ_LINES_ALL)
    table.SetVerticalLinesMode(texttable.VERT_LINES_FIRST)

    for curIndex in range(len(choices)):
        table.AddRow(['%d' % curIndex, choices[curIndex]])
    table.Print()

    inputIsValid = False
    while not inputIsValid:
        userInput = raw_input(prompt)
        choiceMatch = choiceRegex.match(userInput)
        if (choiceMatch):
            chosenIndex = int(choiceMatch.group(1))
            if (chosenIndex in range(len(choices))):
                inputIsValid = True
                userInput = chosenIndex
    return userInput
Ejemplo n.º 5
0
    def testFormattedTable2(self):
        t = texttable.TextTable()
        t.header = ('Host', 'Interface', 'Admin', 'Oper', 'Proto', 'Address')
        t.Append(('DeviceA', 'lo0', 'up', 'up', '', []))
        t.Append(('DeviceA', 'lo0.0', 'up', 'up', 'inet',
                  ['127.0.0.1', '10.100.100.1']))
        t.Append(('DeviceA', 'lo0.16384', 'up', 'up', 'inet', ['127.0.0.1']))
        t[-2].color = ['red']

        # pylint: disable-msg=C6310
        self.failUnlessEqual(
            ' Host     Interface  Admin  Oper  Proto  Address              \n'
            '==============================================================\n'
            ' DeviceA  lo0        up     up                                \n'
            '--------------------------------------------------------------\n'
            '\033[31m DeviceA  lo0.0      up     up    inet   127.0.0.1,           \n'
            '                                         10.100.100.1         \033[0m\n'
            '--------------------------------------------------------------\n'
            ' DeviceA  lo0.16384  up     up    inet   127.0.0.1            \n',
            t.FormattedTable(62))

        # Test with specific columns only
        self.failUnlessEqual(
            ' Host     Interface  Admin  Oper  Address                 \n'
            '==========================================================\n'
            ' DeviceA  lo0        up     up                            \n'
            '\033[31m DeviceA  lo0.0      up     up    127.0.0.1, 10.100.100.1 \033[0m\n'
            ' DeviceA  lo0.16384  up     up    127.0.0.1               \n',
            t.FormattedTable(
                62, columns=['Host', 'Interface', 'Admin', 'Oper', 'Address']))
Ejemplo n.º 6
0
    def _ParseIndex(self, preread, precompile):
        """Reads index file and stores entries in TextTable.

    For optimisation reasons, a second table is created with compiled entries.

    Args:
      preread: func, Pre-processing, applied to each field as it is read.
      precompile: func, Pre-compilation, applied to each field before compiling.

    Raises:
      IndexTableError: If the column headers has illegal column labels.
    """
        self.index = texttable.TextTable()
        self.index.CsvToTable(self._index_handle)

        if preread:
            for row in self.index:
                for col in row.header:
                    row[col] = preread(col, row[col])

        self.compiled = copy.deepcopy(self.index)

        for row in self.compiled:
            for col in row.header:
                if precompile:
                    row[col] = precompile(col, row[col])
                if row[col]:
                    row[col] = copyable_regex_object.CopyableRegexObject(
                        row[col])
Ejemplo n.º 7
0
 def Maketable():
     t = texttable.TextTable()
     t.header = ('Col1', 'Col2', 'Col3')
     t.Append(('lorem', 'ipsum', 'dolor'))
     t.Append(('ut', 'enim', 'ad'))
     t.Append(('duis', 'aute', 'irure'))
     return t
Ejemplo n.º 8
0
def print_table(tname, cname, data):
    t = texttable.TextTable()
    t.header = tname
    t.add_col_names([cname, 'Count'])
    t.add_col_align(['<', '>'])
    for d in sorted(data, key=data.get, reverse=True):
        t.add_row([d, data[d]])

    print t
Ejemplo n.º 9
0
 def testFormattedTableColoredCells(self):
     t = texttable.TextTable()
     t.header = ('LSP', 'Name')
     t.Append((terminal.AnsiText('col1', ['yellow']), 'col2'))
     t.Append(('col1', 'col2'))
     self.failUnlessEqual(
         ' LSP   Name \n'
         '============\n'
         ' \033[33mcol1\033[0m  col2 \n'
         ' col1  col2 \n', t.FormattedTable())
Ejemplo n.º 10
0
 def testFormattedTableColoredMultilineCells(self):
     t = texttable.TextTable()
     t.header = ('LSP', 'Name')
     t.Append((terminal.AnsiText('col1 boembabies', ['yellow']), 'col2'))
     t.Append(('col1', 'col2'))
     self.failUnlessEqual(
         ' LSP           Name \n'
         '====================\n'
         ' \033[33mcol1          col2 \n'
         ' boembabies\033[0m         \n'
         '--------------------\n'
         ' col1          col2 \n', t.FormattedTable(width=20))
Ejemplo n.º 11
0
 def testSmallestColSize(self):
     t = texttable.TextTable()
     self.failUnlessEqual(1, t._SmallestColSize('a'))
     self.failUnlessEqual(2, t._SmallestColSize('a bb'))
     self.failUnlessEqual(4, t._SmallestColSize('a cccc bb'))
     self.failUnlessEqual(0, t._SmallestColSize(''))
     self.failUnlessEqual(1, t._SmallestColSize('a\tb'))
     self.failUnlessEqual(1, t._SmallestColSize('a\nb\tc'))
     self.failUnlessEqual(3, t._SmallestColSize('a\nbbb\n\nc'))
     # Check if _SmallestColSize is not influenced by ANSI colors.
     self.failUnlessEqual(
         3, t._SmallestColSize('bbb ' + terminal.AnsiText('bb', ['red'])))
Ejemplo n.º 12
0
 def testTextJustify(self):
     t = texttable.TextTable()
     self.failUnlessEqual([' a    '], t._TextJustify('a', 6))
     self.failUnlessEqual([' a b  '], t._TextJustify('a b', 6))
     self.failUnlessEqual([' a  b '], t._TextJustify('a  b', 6))
     self.failUnlessEqual([' a ', ' b '], t._TextJustify('a b', 3))
     self.failUnlessEqual([' a ', ' b '], t._TextJustify('a  b', 3))
     self.failUnlessRaises(texttable.TableError, t._TextJustify, 'a', 2)
     self.failUnlessRaises(texttable.TableError, t._TextJustify, 'a bb', 3)
     self.failUnlessEqual([' a b  '], t._TextJustify('a\tb', 6))
     self.failUnlessEqual([' a  b '], t._TextJustify('a\t\tb', 6))
     self.failUnlessEqual([' a    ', ' b    '], t._TextJustify('a\nb\t', 6))
Ejemplo n.º 13
0
    def testFormattedTableColoredHeaders(self):
        t = texttable.TextTable()
        t.header = (terminal.AnsiText('LSP', ['yellow']), 'Name')
        t.Append(('col1', 'col2'))
        t.Append(('col1', 'col2'))
        self.failUnlessEqual(
            ' \033[33mLSP\033[0m   Name \n'
            '============\n'
            ' col1  col2 \n'
            ' col1  col2 \n', t.FormattedTable())

        self.failUnlessEqual(' col1  col2 \n'
                             ' col1  col2 \n',
                             t.FormattedTable(display_header=False))
Ejemplo n.º 14
0
 def testFormattedTableColor(self):
     # Test to sepcify the color defined in terminal.FG_COLOR_WORDS
     t = texttable.TextTable()
     t.header = ('LSP', 'Name')
     t.Append(('col1', 'col2'))
     for color_key in terminal.FG_COLOR_WORDS:
         t[0].color = terminal.FG_COLOR_WORDS[color_key]
         t.FormattedTable()
         self.failUnlessEqual(sorted(t[0].color),
                              sorted(terminal.FG_COLOR_WORDS[color_key]))
     for color_key in terminal.BG_COLOR_WORDS:
         t[0].color = terminal.BG_COLOR_WORDS[color_key]
         t.FormattedTable()
         self.failUnlessEqual(sorted(t[0].color),
                              sorted(terminal.BG_COLOR_WORDS[color_key]))
Ejemplo n.º 15
0
    def testCsvToTable(self):
        buf = """
    # A comment
a,b, c, d  # Trim comment
# Inline comment
# 1,2,3,4
1,2,3,4
5, 6, 7, 8
10, 11
# More comments.
"""
        f = StringIO.StringIO(buf)
        t = texttable.TextTable()
        self.failUnlessEqual(2, t.CsvToTable(f))
        # pylint: disable-msg=E1101
        self.failUnlessEqual(['a', 'b', 'c', 'd'], t.header.values)
        self.failUnlessEqual(['1', '2', '3', '4'], t[1].values)
        self.failUnlessEqual(['5', '6', '7', '8'], t[2].values)
        self.failUnlessEqual(2, t.size)
Ejemplo n.º 16
0
    def testExtendTable(self):
        t2 = self._BasicTable()
        t2.AddColumn('Beer')
        t2[1]['Beer'] = 'Lager'
        t2[1]['three'] = 'three'
        t2.Append(('one', 'two', 'three', 'Stout'))

        t = self._BasicTable()
        # Explicit key, use first column.
        t.extend(t2, ('a', ))
        # pylint: disable-msg=E1101
        self.failUnlessEqual(['a', 'b', 'c', 'Beer'], t.header.values)
        # Only new columns have updated values.
        self.failUnlessEqual(['1', '2', '3', 'Lager'], t[1].values)
        # All rows are extended.
        self.failUnlessEqual(['10', '20', '30', ''], t[2].values)
        # The third row of 't2', is not included as there is no matching
        # row with the same key in the first table 't'.
        self.failUnlessEqual(2, t.size)

        # pylint: disable-msg=E1101
        t = self._BasicTable()
        # If a Key is non-unique (which is a soft-error), then the first instance
        # on the RHS is used for and applied to all non-unique entries on the LHS.
        t.Append(('1', '2b', '3b'))
        t2.Append(('1', 'two', '', 'Ale'))
        t.extend(t2, ('a', ))
        self.failUnlessEqual(['1', '2', '3', 'Lager'], t[1].values)
        self.failUnlessEqual(['1', '2b', '3b', 'Lager'], t[3].values)

        t = self._BasicTable()
        # No explicit key, row number is used as the key.
        t.extend(t2)
        self.failUnlessEqual(['a', 'b', 'c', 'Beer'], t.header.values)
        # Since row is key we pick up new values from corresponding row number.
        self.failUnlessEqual(['1', '2', '3', 'Lager'], t[1].values)
        # All rows are still extended.
        self.failUnlessEqual(['10', '20', '30', ''], t[2].values)
        # The third/fourth row of 't2', is not included as there is no corresponding
        # row in the first table 't'.
        self.failUnlessEqual(2, t.size)

        t = self._BasicTable()
        t.Append(('1', 'two', '3'))
        t.Append(('two', '1', 'three'))
        t2 = texttable.TextTable()
        t2.header = ('a', 'b', 'c', 'Beer')
        t2.Append(('1', 'two', 'three', 'Stout'))
        # Explicitly declare which columns constitute the key.
        # Sometimes more than one row is needed to define a unique key (superkey).
        t.extend(t2, ('a', 'b'))

        self.failUnlessEqual(['a', 'b', 'c', 'Beer'], t.header.values)
        # key '1', '2' does not equal '1', 'two', so column unmatched.
        self.failUnlessEqual(['1', '2', '3', ''], t[1].values)
        # '1', 'two' matches but 'two', '1' does not as order is important.
        self.failUnlessEqual(['1', 'two', '3', 'Stout'], t[3].values)
        self.failUnlessEqual(['two', '1', 'three', ''], t[4].values)
        self.failUnlessEqual(4, t.size)

        # Expects a texttable as the argument.
        self.failUnlessRaises(AttributeError, t.extend, ['a', 'list'])
        # All Key column Names must be valid.
        self.failUnlessRaises(IndexError, t.extend, ['a', 'list'],
                              ('a', 'bogus'))
 def testFilterNone(self):
   t = texttable.TextTable()
   t.header = ('a', 'b', 'c')
   t.Append(('', '', []))
   filtered_table = t.Filter()
   self.assertEqual(0, filtered_table.size)
Ejemplo n.º 18
0
 def _BasicTable(self):
     t = texttable.TextTable()
     t.header = ('a', 'b', 'c')
     t.Append(('1', '2', '3'))
     t.Append(('10', '20', '30'))
     return t