prettytable_test.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. #!/usr/bin/env python
  2. # coding=UTF-8
  3. import sys
  4. import unittest
  5. from math import e, pi, sqrt
  6. from prettytable import (
  7. ALL,
  8. MARKDOWN,
  9. MSWORD_FRIENDLY,
  10. NONE,
  11. ORGMODE,
  12. PrettyTable,
  13. from_csv,
  14. from_db_cursor,
  15. from_html,
  16. from_html_one,
  17. from_json,
  18. )
  19. py3k = sys.version_info[0] >= 3
  20. try:
  21. import sqlite3
  22. _have_sqlite = True
  23. except ImportError:
  24. _have_sqlite = False
  25. if py3k:
  26. import io as StringIO
  27. else:
  28. import StringIO
  29. class BuildEquivalenceTest(unittest.TestCase):
  30. """Make sure that building a table row-by-row and column-by-column yield the same
  31. results"""
  32. def setUp(self):
  33. # Row by row...
  34. self.row = PrettyTable()
  35. self.row.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
  36. self.row.add_row(["Adelaide", 1295, 1158259, 600.5])
  37. self.row.add_row(["Brisbane", 5905, 1857594, 1146.4])
  38. self.row.add_row(["Darwin", 112, 120900, 1714.7])
  39. self.row.add_row(["Hobart", 1357, 205556, 619.5])
  40. self.row.add_row(["Sydney", 2058, 4336374, 1214.8])
  41. self.row.add_row(["Melbourne", 1566, 3806092, 646.9])
  42. self.row.add_row(["Perth", 5386, 1554769, 869.4])
  43. # Column by column...
  44. self.col = PrettyTable()
  45. self.col.add_column(
  46. "City name",
  47. [
  48. "Adelaide",
  49. "Brisbane",
  50. "Darwin",
  51. "Hobart",
  52. "Sydney",
  53. "Melbourne",
  54. "Perth",
  55. ],
  56. )
  57. self.col.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386])
  58. self.col.add_column(
  59. "Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]
  60. )
  61. self.col.add_column(
  62. "Annual Rainfall", [600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]
  63. )
  64. # A mix of both!
  65. self.mix = PrettyTable()
  66. self.mix.field_names = ["City name", "Area"]
  67. self.mix.add_row(["Adelaide", 1295])
  68. self.mix.add_row(["Brisbane", 5905])
  69. self.mix.add_row(["Darwin", 112])
  70. self.mix.add_row(["Hobart", 1357])
  71. self.mix.add_row(["Sydney", 2058])
  72. self.mix.add_row(["Melbourne", 1566])
  73. self.mix.add_row(["Perth", 5386])
  74. self.mix.add_column(
  75. "Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]
  76. )
  77. self.mix.add_column(
  78. "Annual Rainfall", [600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]
  79. )
  80. def testRowColEquivalenceASCII(self):
  81. self.assertEqual(self.row.get_string(), self.col.get_string())
  82. def testRowMixEquivalenceASCII(self):
  83. self.assertEqual(self.row.get_string(), self.mix.get_string())
  84. def testRowColEquivalenceHTML(self):
  85. self.assertEqual(self.row.get_html_string(), self.col.get_html_string())
  86. def testRowMixEquivalenceHTML(self):
  87. self.assertEqual(self.row.get_html_string(), self.mix.get_html_string())
  88. class DeleteColumnTest(unittest.TestCase):
  89. def testDeleteColumn(self):
  90. with_del = PrettyTable()
  91. with_del.add_column("City name", ["Adelaide", "Brisbane", "Darwin"])
  92. with_del.add_column("Area", [1295, 5905, 112])
  93. with_del.add_column("Population", [1158259, 1857594, 120900])
  94. with_del.del_column("Area")
  95. without_row = PrettyTable()
  96. without_row.add_column("City name", ["Adelaide", "Brisbane", "Darwin"])
  97. without_row.add_column("Population", [1158259, 1857594, 120900])
  98. self.assertEqual(with_del.get_string(), without_row.get_string())
  99. def testDeleteIllegalColumnRaisesException(self):
  100. table = PrettyTable()
  101. table.add_column("City name", ["Adelaide", "Brisbane", "Darwin"])
  102. with self.assertRaises(Exception):
  103. table.del_column("City not-a-name")
  104. # class FieldnamelessTableTest(unittest.TestCase):
  105. #
  106. # """Make sure that building and stringing a table with no fieldnames works fine"""
  107. #
  108. # def setUp(self):
  109. # self.x = PrettyTable()
  110. # self.x.add_row(["Adelaide",1295, 1158259, 600.5])
  111. # self.x.add_row(["Brisbane",5905, 1857594, 1146.4])
  112. # self.x.add_row(["Darwin", 112, 120900, 1714.7])
  113. # self.x.add_row(["Hobart", 1357, 205556, 619.5])
  114. # self.x.add_row(["Sydney", 2058, 4336374, 1214.8])
  115. # self.x.add_row(["Melbourne", 1566, 3806092, 646.9])
  116. # self.x.add_row(["Perth", 5386, 1554769, 869.4])
  117. #
  118. # def testCanStringASCII(self):
  119. # self.x.get_string()
  120. #
  121. # def testCanStringHTML(self):
  122. # self.x.get_html_string()
  123. #
  124. # def testAddFieldnamesLater(self):
  125. # self.x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
  126. # self.x.get_string()
  127. class CityDataTest(unittest.TestCase):
  128. """Just build the Australian capital city data example table."""
  129. def setUp(self):
  130. self.x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
  131. self.x.add_row(["Adelaide", 1295, 1158259, 600.5])
  132. self.x.add_row(["Brisbane", 5905, 1857594, 1146.4])
  133. self.x.add_row(["Darwin", 112, 120900, 1714.7])
  134. self.x.add_row(["Hobart", 1357, 205556, 619.5])
  135. self.x.add_row(["Sydney", 2058, 4336374, 1214.8])
  136. self.x.add_row(["Melbourne", 1566, 3806092, 646.9])
  137. self.x.add_row(["Perth", 5386, 1554769, 869.4])
  138. class OptionOverrideTests(CityDataTest):
  139. """Make sure all options are properly overwritten by get_string."""
  140. def testBorder(self):
  141. default = self.x.get_string()
  142. override = self.x.get_string(border=False)
  143. self.assertNotEqual(default, override)
  144. def testHeader(self):
  145. default = self.x.get_string()
  146. override = self.x.get_string(header=False)
  147. self.assertNotEqual(default, override)
  148. def testHrulesAll(self):
  149. default = self.x.get_string()
  150. override = self.x.get_string(hrules=ALL)
  151. self.assertNotEqual(default, override)
  152. def testHrulesNone(self):
  153. default = self.x.get_string()
  154. override = self.x.get_string(hrules=NONE)
  155. self.assertNotEqual(default, override)
  156. class OptionAttributeTests(CityDataTest):
  157. """Make sure all options which have an attribute interface work as they should.
  158. Also make sure option settings are copied correctly when a table is cloned by
  159. slicing."""
  160. def testSetForAllColumns(self):
  161. self.x.field_names = sorted(self.x.field_names)
  162. self.x.align = "l"
  163. self.x.max_width = 10
  164. self.x.start = 2
  165. self.x.end = 4
  166. self.x.sortby = "Area"
  167. self.x.reversesort = True
  168. self.x.header = True
  169. self.x.border = False
  170. self.x.hrule = True
  171. self.x.int_format = "4"
  172. self.x.float_format = "2.2"
  173. self.x.padding_width = 2
  174. self.x.left_padding_width = 2
  175. self.x.right_padding_width = 2
  176. self.x.vertical_char = "!"
  177. self.x.horizontal_char = "~"
  178. self.x.junction_char = "*"
  179. self.x.format = True
  180. self.x.attributes = {"class": "prettytable"}
  181. assert self.x.get_string() == self.x[:].get_string()
  182. def testSetForOneColumn(self):
  183. self.x.align["Rainfall"] = "l"
  184. self.x.max_width["Name"] = 10
  185. self.x.int_format["Population"] = "4"
  186. self.x.float_format["Area"] = "2.2"
  187. assert self.x.get_string() == self.x[:].get_string()
  188. class BasicTests(CityDataTest):
  189. """Some very basic tests."""
  190. def testNoBlankLines(self):
  191. """No table should ever have blank lines in it."""
  192. string = self.x.get_string()
  193. lines = string.split("\n")
  194. self.assertNotIn("", lines)
  195. def testAllLengthsEqual(self):
  196. """All lines in a table should be of the same length."""
  197. string = self.x.get_string()
  198. lines = string.split("\n")
  199. lengths = [len(line) for line in lines]
  200. lengths = set(lengths)
  201. self.assertEqual(len(lengths), 1)
  202. class TitleBasicTests(BasicTests):
  203. """Run the basic tests with a title"""
  204. def setUp(self):
  205. BasicTests.setUp(self)
  206. self.x.title = "My table"
  207. class NoBorderBasicTests(BasicTests):
  208. """Run the basic tests with border = False"""
  209. def setUp(self):
  210. BasicTests.setUp(self)
  211. self.x.border = False
  212. class NoHeaderBasicTests(BasicTests):
  213. """Run the basic tests with header = False"""
  214. def setUp(self):
  215. BasicTests.setUp(self)
  216. self.x.header = False
  217. class HrulesNoneBasicTests(BasicTests):
  218. """Run the basic tests with hrules = NONE"""
  219. def setUp(self):
  220. BasicTests.setUp(self)
  221. self.x.hrules = NONE
  222. class HrulesAllBasicTests(BasicTests):
  223. """Run the basic tests with hrules = ALL"""
  224. def setUp(self):
  225. BasicTests.setUp(self)
  226. self.x.hrules = ALL
  227. class EmptyTableTests(CityDataTest):
  228. """Make sure the print_empty option works"""
  229. def setUp(self):
  230. CityDataTest.setUp(self)
  231. self.y = PrettyTable()
  232. self.y.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
  233. def testPrintEmptyTrue(self):
  234. assert self.y.get_string(print_empty=True) != ""
  235. assert self.x.get_string(print_empty=True) != self.y.get_string(
  236. print_empty=True
  237. )
  238. def testPrintEmptyFalse(self):
  239. assert self.y.get_string(print_empty=False) == ""
  240. assert self.y.get_string(print_empty=False) != self.x.get_string(
  241. print_empty=False
  242. )
  243. def testInteractionWithBorder(self):
  244. assert self.y.get_string(border=False, print_empty=True) == ""
  245. class PresetBasicTests(BasicTests):
  246. """Run the basic tests after using set_style"""
  247. def setUp(self):
  248. BasicTests.setUp(self)
  249. self.x.set_style(MSWORD_FRIENDLY)
  250. class SlicingTests(CityDataTest):
  251. def setUp(self):
  252. CityDataTest.setUp(self)
  253. def testSliceAll(self):
  254. y = self.x[:]
  255. assert self.x.get_string() == y.get_string()
  256. def testSliceFirstTwoRows(self):
  257. y = self.x[0:2]
  258. string = y.get_string()
  259. assert len(string.split("\n")) == 6
  260. assert "Adelaide" in string
  261. assert "Brisbane" in string
  262. assert "Melbourne" not in string
  263. assert "Perth" not in string
  264. def testSliceLastTwoRows(self):
  265. y = self.x[-2:]
  266. string = y.get_string()
  267. assert len(string.split("\n")) == 6
  268. assert "Adelaide" not in string
  269. assert "Brisbane" not in string
  270. assert "Melbourne" in string
  271. assert "Perth" in string
  272. class SortingTests(CityDataTest):
  273. def setUp(self):
  274. CityDataTest.setUp(self)
  275. def testSortBy(self):
  276. self.x.sortby = self.x.field_names[0]
  277. old = self.x.get_string()
  278. for field in self.x.field_names[1:]:
  279. self.x.sortby = field
  280. new = self.x.get_string()
  281. assert new != old
  282. def testReverseSort(self):
  283. for field in self.x.field_names:
  284. self.x.sortby = field
  285. self.x.reversesort = False
  286. forward = self.x.get_string()
  287. self.x.reversesort = True
  288. backward = self.x.get_string()
  289. forward_lines = forward.split("\n")[2:] # Discard header lines
  290. backward_lines = backward.split("\n")[2:]
  291. backward_lines.reverse()
  292. assert forward_lines == backward_lines
  293. def testSortKey(self):
  294. # Test sorting by length of city name
  295. def key(vals):
  296. vals[0] = len(vals[0])
  297. return vals
  298. self.x.sortby = "City name"
  299. self.x.sort_key = key
  300. assert (
  301. self.x.get_string().strip()
  302. == """+-----------+------+------------+-----------------+
  303. | City name | Area | Population | Annual Rainfall |
  304. +-----------+------+------------+-----------------+
  305. | Perth | 5386 | 1554769 | 869.4 |
  306. | Darwin | 112 | 120900 | 1714.7 |
  307. | Hobart | 1357 | 205556 | 619.5 |
  308. | Sydney | 2058 | 4336374 | 1214.8 |
  309. | Adelaide | 1295 | 1158259 | 600.5 |
  310. | Brisbane | 5905 | 1857594 | 1146.4 |
  311. | Melbourne | 1566 | 3806092 | 646.9 |
  312. +-----------+------+------------+-----------------+
  313. """.strip()
  314. )
  315. def testSortSlice(self):
  316. """Make sure sorting and slicing interact in the expected way"""
  317. x = PrettyTable(["Foo"])
  318. for i in range(20, 0, -1):
  319. x.add_row([i])
  320. newstyle = x.get_string(sortby="Foo", end=10)
  321. assert "10" in newstyle
  322. assert "20" not in newstyle
  323. oldstyle = x.get_string(sortby="Foo", end=10, oldsortslice=True)
  324. assert "10" not in oldstyle
  325. assert "20" in oldstyle
  326. class IntegerFormatBasicTests(BasicTests):
  327. """Run the basic tests after setting an integer format string"""
  328. def setUp(self):
  329. BasicTests.setUp(self)
  330. self.x.int_format = "04"
  331. class FloatFormatBasicTests(BasicTests):
  332. """Run the basic tests after setting a float format string"""
  333. def setUp(self):
  334. BasicTests.setUp(self)
  335. self.x.float_format = "6.2f"
  336. class FloatFormatTests(unittest.TestCase):
  337. def setUp(self):
  338. self.x = PrettyTable(["Constant", "Value"])
  339. self.x.add_row(["Pi", pi])
  340. self.x.add_row(["e", e])
  341. self.x.add_row(["sqrt(2)", sqrt(2)])
  342. def testNoDecimals(self):
  343. self.x.float_format = ".0f"
  344. self.x.caching = False
  345. assert "." not in self.x.get_string()
  346. def testRoundTo5DP(self):
  347. self.x.float_format = ".5f"
  348. string = self.x.get_string()
  349. assert "3.14159" in string
  350. assert "3.141592" not in string
  351. assert "2.71828" in string
  352. assert "2.718281" not in string
  353. assert "2.718282" not in string
  354. assert "1.41421" in string
  355. assert "1.414213" not in string
  356. def testPadWith2Zeroes(self):
  357. self.x.float_format = "06.2f"
  358. string = self.x.get_string()
  359. assert "003.14" in string
  360. assert "002.72" in string
  361. assert "001.41" in string
  362. class BreakLineTests(unittest.TestCase):
  363. def testAsciiBreakLine(self):
  364. t = PrettyTable(["Field 1", "Field 2"])
  365. t.add_row(["value 1", "value2\nsecond line"])
  366. t.add_row(["value 3", "value4"])
  367. result = t.get_string(hrules=ALL)
  368. assert (
  369. result.strip()
  370. == """
  371. +---------+-------------+
  372. | Field 1 | Field 2 |
  373. +---------+-------------+
  374. | value 1 | value2 |
  375. | | second line |
  376. +---------+-------------+
  377. | value 3 | value4 |
  378. +---------+-------------+
  379. """.strip()
  380. )
  381. t = PrettyTable(["Field 1", "Field 2"])
  382. t.add_row(["value 1", "value2\nsecond line"])
  383. t.add_row(["value 3\n\nother line", "value4\n\n\nvalue5"])
  384. result = t.get_string(hrules=ALL)
  385. assert (
  386. result.strip()
  387. == """
  388. +------------+-------------+
  389. | Field 1 | Field 2 |
  390. +------------+-------------+
  391. | value 1 | value2 |
  392. | | second line |
  393. +------------+-------------+
  394. | value 3 | value4 |
  395. | | |
  396. | other line | |
  397. | | value5 |
  398. +------------+-------------+
  399. """.strip()
  400. )
  401. t = PrettyTable(["Field 1", "Field 2"])
  402. t.add_row(["value 1", "value2\nsecond line"])
  403. t.add_row(["value 3\n\nother line", "value4\n\n\nvalue5"])
  404. result = t.get_string()
  405. assert (
  406. result.strip()
  407. == """
  408. +------------+-------------+
  409. | Field 1 | Field 2 |
  410. +------------+-------------+
  411. | value 1 | value2 |
  412. | | second line |
  413. | value 3 | value4 |
  414. | | |
  415. | other line | |
  416. | | value5 |
  417. +------------+-------------+
  418. """.strip()
  419. )
  420. def testHtmlBreakLine(self):
  421. t = PrettyTable(["Field 1", "Field 2"])
  422. t.add_row(["value 1", "value2\nsecond line"])
  423. t.add_row(["value 3", "value4"])
  424. result = t.get_html_string(hrules=ALL)
  425. assert (
  426. result.strip()
  427. == """
  428. <table>
  429. <tr>
  430. <th>Field 1</th>
  431. <th>Field 2</th>
  432. </tr>
  433. <tr>
  434. <td>value 1</td>
  435. <td>value2<br>second line</td>
  436. </tr>
  437. <tr>
  438. <td>value 3</td>
  439. <td>value4</td>
  440. </tr>
  441. </table>
  442. """.strip()
  443. )
  444. class JSONOutputTests(unittest.TestCase):
  445. def testJSONOutput(self):
  446. t = PrettyTable(["Field 1", "Field 2", "Field 3"])
  447. t.add_row(["value 1", "value2", "value3"])
  448. t.add_row(["value 4", "value5", "value6"])
  449. t.add_row(["value 7", "value8", "value9"])
  450. result = t.get_json_string()
  451. assert (
  452. result.strip()
  453. == """[
  454. [
  455. "Field 1",
  456. "Field 2",
  457. "Field 3"
  458. ],
  459. {
  460. "Field 1": "value 1",
  461. "Field 2": "value2",
  462. "Field 3": "value3"
  463. },
  464. {
  465. "Field 1": "value 4",
  466. "Field 2": "value5",
  467. "Field 3": "value6"
  468. },
  469. {
  470. "Field 1": "value 7",
  471. "Field 2": "value8",
  472. "Field 3": "value9"
  473. }
  474. ]""".strip()
  475. )
  476. class HtmlOutputTests(unittest.TestCase):
  477. def testHtmlOutput(self):
  478. t = PrettyTable(["Field 1", "Field 2", "Field 3"])
  479. t.add_row(["value 1", "value2", "value3"])
  480. t.add_row(["value 4", "value5", "value6"])
  481. t.add_row(["value 7", "value8", "value9"])
  482. result = t.get_html_string()
  483. assert (
  484. result.strip()
  485. == """
  486. <table>
  487. <tr>
  488. <th>Field 1</th>
  489. <th>Field 2</th>
  490. <th>Field 3</th>
  491. </tr>
  492. <tr>
  493. <td>value 1</td>
  494. <td>value2</td>
  495. <td>value3</td>
  496. </tr>
  497. <tr>
  498. <td>value 4</td>
  499. <td>value5</td>
  500. <td>value6</td>
  501. </tr>
  502. <tr>
  503. <td>value 7</td>
  504. <td>value8</td>
  505. <td>value9</td>
  506. </tr>
  507. </table>
  508. """.strip()
  509. )
  510. def testHtmlOutputFormated(self):
  511. t = PrettyTable(["Field 1", "Field 2", "Field 3"])
  512. t.add_row(["value 1", "value2", "value3"])
  513. t.add_row(["value 4", "value5", "value6"])
  514. t.add_row(["value 7", "value8", "value9"])
  515. result = t.get_html_string(format=True)
  516. assert (
  517. result.strip()
  518. == """
  519. <table frame="box" rules="cols">
  520. <tr>
  521. <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 1</th>
  522. <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 2</th>
  523. <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 3</th>
  524. </tr>
  525. <tr>
  526. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 1</td>
  527. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value2</td>
  528. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value3</td>
  529. </tr>
  530. <tr>
  531. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 4</td>
  532. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value5</td>
  533. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value6</td>
  534. </tr>
  535. <tr>
  536. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 7</td>
  537. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value8</td>
  538. <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value9</td>
  539. </tr>
  540. </table>
  541. """.strip() # noqa: E501
  542. )
  543. class MarkdownStyleTest(BasicTests):
  544. def testMarkdownStyle(self):
  545. t = PrettyTable(["Field 1", "Field 2", "Field 3"])
  546. t.add_row(["value 1", "value2", "value3"])
  547. t.add_row(["value 4", "value5", "value6"])
  548. t.add_row(["value 7", "value8", "value9"])
  549. t.set_style(MARKDOWN)
  550. result = t.get_string()
  551. assert (
  552. result.strip()
  553. == """
  554. | Field 1 | Field 2 | Field 3 |
  555. |---------|---------|---------|
  556. | value 1 | value2 | value3 |
  557. | value 4 | value5 | value6 |
  558. | value 7 | value8 | value9 |
  559. """.strip()
  560. )
  561. class OrgmodeStyleTest(BasicTests):
  562. def testOrgmodeStyle(self):
  563. t = PrettyTable(["Field 1", "Field 2", "Field 3"])
  564. t.add_row(["value 1", "value2", "value3"])
  565. t.add_row(["value 4", "value5", "value6"])
  566. t.add_row(["value 7", "value8", "value9"])
  567. t.set_style(ORGMODE)
  568. result = t.get_string()
  569. assert (
  570. result.strip()
  571. == """
  572. |---------+---------+---------|
  573. | Field 1 | Field 2 | Field 3 |
  574. |---------+---------+---------|
  575. | value 1 | value2 | value3 |
  576. | value 4 | value5 | value6 |
  577. | value 7 | value8 | value9 |
  578. |---------+---------+---------|
  579. """.strip()
  580. )
  581. class CsvConstructorTest(BasicTests):
  582. def setUp(self):
  583. csv_string = """City name, Area , Population , Annual Rainfall
  584. Sydney, 2058 , 4336374 , 1214.8
  585. Melbourne, 1566 , 3806092 , 646.9
  586. Brisbane, 5905 , 1857594 , 1146.4
  587. Perth, 5386 , 1554769 , 869.4
  588. Adelaide, 1295 , 1158259 , 600.5
  589. Hobart, 1357 , 205556 , 619.5
  590. Darwin, 0112 , 120900 , 1714.7"""
  591. csv_fp = StringIO.StringIO(csv_string)
  592. self.x = from_csv(csv_fp)
  593. class CsvOutputTests(unittest.TestCase):
  594. def testCsvOutput(self):
  595. t = PrettyTable(["Field 1", "Field 2", "Field 3"])
  596. t.add_row(["value 1", "value2", "value3"])
  597. t.add_row(["value 4", "value5", "value6"])
  598. t.add_row(["value 7", "value8", "value9"])
  599. self.assertEqual(
  600. t.get_csv_string(delimiter="\t", header=False),
  601. "value 1\tvalue2\tvalue3\r\n"
  602. "value 4\tvalue5\tvalue6\r\n"
  603. "value 7\tvalue8\tvalue9\r\n",
  604. )
  605. self.assertEqual(
  606. t.get_csv_string(),
  607. "Field 1,Field 2,Field 3\r\n"
  608. "value 1,value2,value3\r\n"
  609. "value 4,value5,value6\r\n"
  610. "value 7,value8,value9\r\n",
  611. )
  612. if _have_sqlite:
  613. class DatabaseConstructorTest(BasicTests):
  614. def setUp(self):
  615. self.conn = sqlite3.connect(":memory:")
  616. self.cur = self.conn.cursor()
  617. self.cur.execute(
  618. "CREATE TABLE cities "
  619. "(name TEXT, area INTEGER, population INTEGER, rainfall REAL)"
  620. )
  621. self.cur.execute(
  622. 'INSERT INTO cities VALUES ("Adelaide", 1295, 1158259, 600.5)'
  623. )
  624. self.cur.execute(
  625. 'INSERT INTO cities VALUES ("Brisbane", 5905, 1857594, 1146.4)'
  626. )
  627. self.cur.execute(
  628. 'INSERT INTO cities VALUES ("Darwin", 112, 120900, 1714.7)'
  629. )
  630. self.cur.execute(
  631. 'INSERT INTO cities VALUES ("Hobart", 1357, 205556, 619.5)'
  632. )
  633. self.cur.execute(
  634. 'INSERT INTO cities VALUES ("Sydney", 2058, 4336374, 1214.8)'
  635. )
  636. self.cur.execute(
  637. 'INSERT INTO cities VALUES ("Melbourne", 1566, 3806092, 646.9)'
  638. )
  639. self.cur.execute(
  640. 'INSERT INTO cities VALUES ("Perth", 5386, 1554769, 869.4)'
  641. )
  642. self.cur.execute("SELECT * FROM cities")
  643. self.x = from_db_cursor(self.cur)
  644. def testNonSelectCursor(self):
  645. self.cur.execute(
  646. 'INSERT INTO cities VALUES ("Adelaide", 1295, 1158259, 600.5)'
  647. )
  648. assert from_db_cursor(self.cur) is None
  649. class JSONConstructorTest(CityDataTest):
  650. def testJSONAndBack(self):
  651. json_string = self.x.get_json_string()
  652. new_table = from_json(json_string)
  653. assert new_table.get_string() == self.x.get_string()
  654. class HtmlConstructorTest(CityDataTest):
  655. def testHtmlAndBack(self):
  656. html_string = self.x.get_html_string()
  657. new_table = from_html(html_string)[0]
  658. assert new_table.get_string() == self.x.get_string()
  659. def testHtmlOneAndBack(self):
  660. html_string = self.x.get_html_string()
  661. new_table = from_html_one(html_string)
  662. assert new_table.get_string() == self.x.get_string()
  663. def testHtmlOneFailOnMany(self):
  664. html_string = self.x.get_html_string()
  665. html_string += self.x.get_html_string()
  666. self.assertRaises(Exception, from_html_one, html_string)
  667. class PrintEnglishTest(CityDataTest):
  668. def testPrint(self):
  669. print()
  670. print(self.x)
  671. class PrintJapaneseTest(unittest.TestCase):
  672. def setUp(self):
  673. self.x = PrettyTable(["Kanji", "Hiragana", "English"])
  674. self.x.add_row(["神戸", "こうべ", "Kobe"])
  675. self.x.add_row(["京都", "きょうと", "Kyoto"])
  676. self.x.add_row(["長崎", "ながさき", "Nagasaki"])
  677. self.x.add_row(["名古屋", "なごや", "Nagoya"])
  678. self.x.add_row(["大阪", "おおさか", "Osaka"])
  679. self.x.add_row(["札幌", "さっぽろ", "Sapporo"])
  680. self.x.add_row(["東京", "とうきょう", "Tokyo"])
  681. self.x.add_row(["横浜", "よこはま", "Yokohama"])
  682. def testPrint(self):
  683. print()
  684. print(self.x)
  685. class PrintEmojiTest(unittest.TestCase):
  686. def setUp(self):
  687. thunder1 = [
  688. '\033[38;5;226m _`/""\033[38;5;250m.-. \033[0m',
  689. "\033[38;5;226m ,\\_\033[38;5;250m( ). \033[0m",
  690. "\033[38;5;226m /\033[38;5;250m(___(__) \033[0m",
  691. "\033[38;5;228;5m ⚡\033[38;5;111;25mʻ ʻ\033[38;5;228;5m"
  692. "⚡\033[38;5;111;25mʻ ʻ \033[0m",
  693. "\033[38;5;111m ʻ ʻ ʻ ʻ \033[0m",
  694. ]
  695. thunder2 = [
  696. "\033[38;5;240;1m .-. \033[0m",
  697. "\033[38;5;240;1m ( ). \033[0m",
  698. "\033[38;5;240;1m (___(__) \033[0m",
  699. "\033[38;5;21;1m ‚ʻ\033[38;5;228;5m⚡\033[38;5;21;25mʻ‚\033[38;5;228;5m"
  700. "⚡\033[38;5;21;25m‚ʻ \033[0m",
  701. "\033[38;5;21;1m ‚ʻ‚ʻ\033[38;5;228;5m⚡\033[38;5;21;25mʻ‚ʻ \033[0m",
  702. ]
  703. self.x = PrettyTable(["Thunderbolt", "Lightning"])
  704. for i in range(len(thunder1)):
  705. self.x.add_row([thunder1[i], thunder2[i]])
  706. def testPrint(self):
  707. print()
  708. print(self.x)
  709. if __name__ == "__main__":
  710. unittest.main()