1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
|
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
"""Unittest for clitable script."""
import copy
import io
import os
import re
import unittest
from textfsm import clitable
class UnitTestIndexTable(unittest.TestCase):
"""Tests the IndexTable class."""
def testParseIndex(self):
"""Test reading and index and parsing to index and compiled tables."""
file_path = os.path.join('testdata', 'parseindex_index')
indx = clitable.IndexTable(file_path=file_path)
# Compare number of entries found in the index table.
self.assertEqual(indx.index.size, 3)
self.assertEqual(indx.index[2]['Template'], 'clitable_templateC')
self.assertEqual(indx.index[3]['Template'], 'clitable_templateD')
self.assertEqual(indx.index[1]['Command'], 'sh[[ow]] ve[[rsion]]')
self.assertEqual(indx.index[1]['Hostname'], '.*')
self.assertEqual(indx.compiled.size, 3)
for col in ('Command', 'Vendor', 'Template', 'Hostname'):
self.assertIsInstance(indx.compiled[1][col], re.Pattern)
self.assertTrue(indx.compiled[1]['Hostname'].match('random string'))
def _PreParse(key, value):
if key == 'Template':
return value.upper()
return value
def _PreCompile(key, value):
if key in ('Template', 'Command'):
return None
return value
self.assertEqual(indx.compiled.size, 3)
indx = clitable.IndexTable(_PreParse, _PreCompile, file_path)
self.assertEqual(indx.index[2]['Template'], 'CLITABLE_TEMPLATEC')
self.assertEqual(indx.index[1]['Command'], 'sh[[ow]] ve[[rsion]]')
self.assertIsInstance(indx.compiled[1]['Hostname'], re.Pattern)
self.assertFalse(indx.compiled[1]['Command'])
def testGetRowMatch(self):
"""Tests retreiving rows from table."""
file_path = os.path.join('testdata', 'parseindex_index')
indx = clitable.IndexTable(file_path=file_path)
self.assertEqual(1, indx.GetRowMatch({'Hostname': 'abc'}))
self.assertEqual(2, indx.GetRowMatch({'Hostname': 'abc',
'Vendor': 'VendorB'}))
def testCopy(self):
"""Tests copy of IndexTable object."""
file_path = os.path.join('testdata', 'parseindex_index')
indx = clitable.IndexTable(file_path=file_path)
copy.deepcopy(indx)
class UnitTestCliTable(unittest.TestCase):
"""Tests the CliTable class."""
def setUp(self):
super(UnitTestCliTable, self).setUp()
clitable.CliTable.INDEX = {}
self.clitable = clitable.CliTable('default_index', 'testdata')
self.input_data = ('a b c\n'
'd e f\n')
self.template = ('Value Key Col1 (.)\n'
'Value Col2 (.)\n'
'Value Col3 (.)\n'
'\n'
'Start\n'
' ^${Col1} ${Col2} ${Col3} -> Record\n'
'\n')
self.template_file = io.StringIO(self.template)
def testCompletion(self):
"""Tests '[[]]' syntax replacement."""
indx = clitable.CliTable()
self.assertEqual('abc', re.sub(r'(\[\[.+?\]\])', indx._Completion, 'abc'))
self.assertEqual('a(b(c)?)?',
re.sub(r'(\[\[.+?\]\])', indx._Completion, 'a[[bc]]'))
self.assertEqual('a(b(c)?)? de(f)?',
re.sub(r'(\[\[.+?\]\])', indx._Completion,
'a[[bc]] de[[f]]'))
def testRepeatRead(self):
"""Tests that index file is read only once at the class level."""
new_clitable = clitable.CliTable('default_index', 'testdata')
self.assertEqual(self.clitable.index, new_clitable.index)
def testCliCompile(self):
"""Tests PreParse and PreCompile."""
self.assertEqual('sh(o(w)?)? ve(r(s(i(o(n)?)?)?)?)?',
self.clitable.index.index[1]['Command'])
self.assertIsNone(self.clitable.index.compiled[1]['Template'])
self.assertTrue(
self.clitable.index.compiled[1]['Command'].match('sho vers'))
def testParseCmdItem(self):
"""Tests parsing data with a single specific template."""
t = self.clitable._ParseCmdItem(self.input_data,
template_file=self.template_file)
self.assertEqual(t.table, 'Col1, Col2, Col3\na, b, c\nd, e, f\n')
def testParseCmd(self):
"""Tests parsing data with a mocked template."""
# Stub out the conversion of filename to file handle.
self.clitable._TemplateNamesToFiles = lambda t: [self.template_file]
self.clitable.ParseCmd(self.input_data, attributes={'Command': 'sh vers'})
self.assertEqual(
self.clitable.table, 'Col1, Col2, Col3\na, b, c\nd, e, f\n')
def testParseWithTemplate(self):
"""Tests parsing with an explicitly declared the template."""
self.clitable.ParseCmd(self.input_data,
attributes={'Command': 'sh vers'},
templates='clitable_templateB')
self.assertEqual(
self.clitable.table, 'Col1, Col4\na, b\nd, e\n')
def testParseCmdFromIndex(self):
"""Tests parsing with a template found in the index."""
self.clitable.ParseCmd(self.input_data,
attributes={'Command': 'sh vers',
'Vendor': 'VendorB'})
self.assertEqual(
self.clitable.table, 'Col1, Col2, Col3\na, b, c\n')
self.clitable.ParseCmd(self.input_data,
attributes={'Command': 'sh int',
'Vendor': 'VendorA'})
self.assertEqual(
self.clitable.table, 'Col1, Col2, Col3\nd, e, f\n')
self.assertRaises(clitable.CliTableError, self.clitable.ParseCmd,
self.input_data,
attributes={'Command': 'show vers',
'Vendor': 'bogus'})
self.assertRaises(clitable.CliTableError, self.clitable.ParseCmd,
self.input_data,
attributes={'Command': 'unknown command',
'Vendor': 'VendorA'})
def testParseWithMultiTemplates(self):
"""Tests that multiple matching templates extend the table."""
self.clitable.ParseCmd(self.input_data,
attributes={'Command': 'sh ver',
'Vendor': 'VendorA'})
self.assertEqual(
self.clitable.table,
'Col1, Col2, Col3, Col4\na, b, c, b\nd, e, f, e\n')
self.clitable.ParseCmd(self.input_data,
attributes={'Command': 'sh vers'},
templates='clitable_templateB:clitable_templateA')
self.assertEqual(
self.clitable.table,
'Col1, Col4, Col2, Col3\na, b, b, c\nd, e, e, f\n')
self.assertRaises(IOError, self.clitable.ParseCmd,
self.input_data,
attributes={'Command': 'sh vers'},
templates='clitable_templateB:clitable_bogus')
def testRequireCols(self):
"""Tests that CliTable expects a 'Template' row to be present."""
self.assertRaises(clitable.CliTableError, clitable.CliTable,
'nondefault_index', 'testdata')
def testSuperKey(self):
"""Tests that superkey is derived from the template and is extensible."""
# Stub out the conversion of filename to file handle.
self.clitable._TemplateNamesToFiles = lambda t: [self.template_file]
self.clitable.ParseCmd(self.input_data, attributes={'Command': 'sh ver'})
self.assertEqual(self.clitable.superkey, ['Col1'])
self.assertEqual(
self.clitable.LabelValueTable(),
'# LABEL Col1\n'
'a.Col2 b\n'
'a.Col3 c\n'
'd.Col2 e\n'
'd.Col3 f\n')
self.clitable.AddKeys(['Col2'])
self.assertEqual(
self.clitable.LabelValueTable(),
'# LABEL Col1.Col2\n'
'a.b.Col3 c\n'
'd.e.Col3 f\n')
def testAddKey(self):
"""Tests that new keys are not duplicated and non-existant columns."""
self.assertEqual(self.clitable.superkey, [])
# Stub out the conversion of filename to file handle.
self.clitable._TemplateNamesToFiles = lambda t: [self.template_file]
self.clitable.ParseCmd(self.input_data, attributes={'Command': 'sh ver'})
self.assertEqual(self.clitable.superkey, ['Col1'])
self.clitable.AddKeys(['Col1', 'Col2', 'Col3'])
self.assertEqual(self.clitable.superkey, ['Col1', 'Col2', 'Col3'])
self.assertRaises(KeyError, self.clitable.AddKeys, ['Bogus'])
def testKeyValue(self):
"""Tests retrieving row value that corresponds to the key."""
# Stub out the conversion of filename to file handle.
self.clitable._TemplateNamesToFiles = lambda t: [self.template_file]
self.clitable.ParseCmd(self.input_data, attributes={'Command': 'sh ver'})
self.assertEqual(self.clitable.KeyValue(), ['a'])
self.clitable.row_index = 2
self.assertEqual(self.clitable.KeyValue(), ['d'])
self.clitable.row_index = 1
self.clitable.AddKeys(['Col3'])
self.assertEqual(self.clitable.KeyValue(), ['a', 'c'])
# With no key it falls back to row number.
self.clitable._keys = set()
for rownum, row in enumerate(self.clitable, start=1):
self.assertEqual(row.table.KeyValue(), ['%s' % rownum])
def testTableSort(self):
"""Tests sorting of table based on superkey."""
self.clitable._TemplateNamesToFiles = lambda t: [self.template_file]
input_data2 = ('a e c\n'
'd b f\n')
self.clitable.ParseCmd(self.input_data + input_data2,
attributes={'Command': 'sh ver'})
self.assertEqual(
self.clitable.table,
'Col1, Col2, Col3\na, b, c\nd, e, f\na, e, c\nd, b, f\n')
self.clitable.sort()
# Key was non-unique, columns outside of the key do not count.
self.assertEqual(
self.clitable.table,
'Col1, Col2, Col3\na, b, c\na, e, c\nd, e, f\nd, b, f\n')
# Create a new table with no explicit key.
self.template = ('Value Col1 (.)\n'
'Value Col2 (.)\n'
'Value Col3 (.)\n'
'\n'
'Start\n'
' ^${Col1} ${Col2} ${Col3} -> Record\n'
'\n')
self.template_file = io.StringIO(self.template)
self.clitable._TemplateNamesToFiles = lambda t: [self.template_file]
self.clitable.ParseCmd(self.input_data + input_data2,
attributes={'Command': 'sh ver'})
# Add a manual key.
self.clitable.AddKeys(['Col2'])
self.clitable.sort()
self.assertEqual(
self.clitable.table,
'Col1, Col2, Col3\na, b, c\nd, b, f\nd, e, f\na, e, c\n')
# Clear the keys.
self.clitable._keys = set()
# With no key, sort based on whole row.
self.clitable.sort()
self.assertEqual(
self.clitable.table,
'Col1, Col2, Col3\na, b, c\na, e, c\nd, b, f\nd, e, f\n')
def testCopy(self):
"""Tests copying of clitable object."""
copy.deepcopy(self.clitable)
if __name__ == '__main__':
unittest.main()
|