PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/resources/lib/twisted/twisted/test/test_usage.py

https://github.com/analogue/mythbox
Python | 372 lines | 361 code | 5 blank | 6 comment | 0 complexity | f89a673d94192f11dd63707e28599078 MD5 | raw file
  1. # Copyright (c) 2001-2007 Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. from twisted.trial import unittest
  4. from twisted.python import usage
  5. class WellBehaved(usage.Options):
  6. optParameters = [['long', 'w', 'default', 'and a docstring'],
  7. ['another', 'n', 'no docstring'],
  8. ['longonly', None, 'noshort'],
  9. ['shortless', None, 'except',
  10. 'this one got docstring'],
  11. ]
  12. optFlags = [['aflag', 'f',
  13. """
  14. flagallicious docstringness for this here
  15. """],
  16. ['flout', 'o'],
  17. ]
  18. def opt_myflag(self):
  19. self.opts['myflag'] = "PONY!"
  20. def opt_myparam(self, value):
  21. self.opts['myparam'] = "%s WITH A PONY!" % (value,)
  22. class ParseCorrectnessTest(unittest.TestCase):
  23. """
  24. Test Options.parseArgs for correct values under good conditions.
  25. """
  26. def setUp(self):
  27. """
  28. Instantiate and parseOptions a well-behaved Options class.
  29. """
  30. self.niceArgV = ("--long Alpha -n Beta "
  31. "--shortless Gamma -f --myflag "
  32. "--myparam Tofu").split()
  33. self.nice = WellBehaved()
  34. self.nice.parseOptions(self.niceArgV)
  35. def test_checkParameters(self):
  36. """
  37. Checking that parameters have correct values.
  38. """
  39. self.failUnlessEqual(self.nice.opts['long'], "Alpha")
  40. self.failUnlessEqual(self.nice.opts['another'], "Beta")
  41. self.failUnlessEqual(self.nice.opts['longonly'], "noshort")
  42. self.failUnlessEqual(self.nice.opts['shortless'], "Gamma")
  43. def test_checkFlags(self):
  44. """
  45. Checking that flags have correct values.
  46. """
  47. self.failUnlessEqual(self.nice.opts['aflag'], 1)
  48. self.failUnlessEqual(self.nice.opts['flout'], 0)
  49. def test_checkCustoms(self):
  50. """
  51. Checking that custom flags and parameters have correct values.
  52. """
  53. self.failUnlessEqual(self.nice.opts['myflag'], "PONY!")
  54. self.failUnlessEqual(self.nice.opts['myparam'], "Tofu WITH A PONY!")
  55. class TypedOptions(usage.Options):
  56. optParameters = [
  57. ['fooint', None, 392, 'Foo int', int],
  58. ['foofloat', None, 4.23, 'Foo float', float],
  59. ['eggint', None, None, 'Egg int without default', int],
  60. ['eggfloat', None, None, 'Egg float without default', float],
  61. ]
  62. class TypedTestCase(unittest.TestCase):
  63. """
  64. Test Options.parseArgs for options with forced types.
  65. """
  66. def setUp(self):
  67. self.usage = TypedOptions()
  68. def test_defaultValues(self):
  69. """
  70. Test parsing of default values.
  71. """
  72. argV = []
  73. self.usage.parseOptions(argV)
  74. self.failUnlessEqual(self.usage.opts['fooint'], 392)
  75. self.assert_(isinstance(self.usage.opts['fooint'], int))
  76. self.failUnlessEqual(self.usage.opts['foofloat'], 4.23)
  77. self.assert_(isinstance(self.usage.opts['foofloat'], float))
  78. self.failUnlessEqual(self.usage.opts['eggint'], None)
  79. self.failUnlessEqual(self.usage.opts['eggfloat'], None)
  80. def test_parsingValues(self):
  81. """
  82. Test basic parsing of int and float values.
  83. """
  84. argV = ("--fooint 912 --foofloat -823.1 "
  85. "--eggint 32 --eggfloat 21").split()
  86. self.usage.parseOptions(argV)
  87. self.failUnlessEqual(self.usage.opts['fooint'], 912)
  88. self.assert_(isinstance(self.usage.opts['fooint'], int))
  89. self.failUnlessEqual(self.usage.opts['foofloat'], -823.1)
  90. self.assert_(isinstance(self.usage.opts['foofloat'], float))
  91. self.failUnlessEqual(self.usage.opts['eggint'], 32)
  92. self.assert_(isinstance(self.usage.opts['eggint'], int))
  93. self.failUnlessEqual(self.usage.opts['eggfloat'], 21.)
  94. self.assert_(isinstance(self.usage.opts['eggfloat'], float))
  95. def test_invalidValues(self):
  96. """
  97. Check that passing wrong values raises an error.
  98. """
  99. argV = "--fooint egg".split()
  100. self.assertRaises(usage.UsageError, self.usage.parseOptions, argV)
  101. class WrongTypedOptions(usage.Options):
  102. optParameters = [
  103. ['barwrong', None, None, 'Bar with wrong coerce', 'he']
  104. ]
  105. class WeirdCallableOptions(usage.Options):
  106. def _bar(value):
  107. raise RuntimeError("Ouch")
  108. def _foo(value):
  109. raise ValueError("Yay")
  110. optParameters = [
  111. ['barwrong', None, None, 'Bar with strange callable', _bar],
  112. ['foowrong', None, None, 'Foo with strange callable', _foo]
  113. ]
  114. class WrongTypedTestCase(unittest.TestCase):
  115. """
  116. Test Options.parseArgs for wrong coerce options.
  117. """
  118. def test_nonCallable(self):
  119. """
  120. Check that using a non callable type fails.
  121. """
  122. us = WrongTypedOptions()
  123. argV = "--barwrong egg".split()
  124. self.assertRaises(TypeError, us.parseOptions, argV)
  125. def test_notCalledInDefault(self):
  126. """
  127. Test that the coerce functions are not called if no values are
  128. provided.
  129. """
  130. us = WeirdCallableOptions()
  131. argV = []
  132. us.parseOptions(argV)
  133. def test_weirdCallable(self):
  134. """
  135. Test what happens when coerce functions raise errors.
  136. """
  137. us = WeirdCallableOptions()
  138. argV = "--foowrong blah".split()
  139. # ValueError is swallowed as UsageError
  140. e = self.assertRaises(usage.UsageError, us.parseOptions, argV)
  141. self.assertEquals(str(e), "Parameter type enforcement failed: Yay")
  142. us = WeirdCallableOptions()
  143. argV = "--barwrong blah".split()
  144. # RuntimeError is not swallowed
  145. self.assertRaises(RuntimeError, us.parseOptions, argV)
  146. class OutputTest(unittest.TestCase):
  147. def test_uppercasing(self):
  148. """
  149. Error output case adjustment does not mangle options
  150. """
  151. opt = WellBehaved()
  152. e = self.assertRaises(usage.UsageError,
  153. opt.parseOptions, ['-Z'])
  154. self.assertEquals(str(e), 'option -Z not recognized')
  155. class InquisitionOptions(usage.Options):
  156. optFlags = [
  157. ('expect', 'e'),
  158. ]
  159. optParameters = [
  160. ('torture-device', 't',
  161. 'comfy-chair',
  162. 'set preferred torture device'),
  163. ]
  164. class HolyQuestOptions(usage.Options):
  165. optFlags = [('horseback', 'h',
  166. 'use a horse'),
  167. ('for-grail', 'g'),
  168. ]
  169. class SubCommandOptions(usage.Options):
  170. optFlags = [('europian-swallow', None,
  171. 'set default swallow type to Europian'),
  172. ]
  173. subCommands = [
  174. ('inquisition', 'inquest', InquisitionOptions,
  175. 'Perform an inquisition'),
  176. ('holyquest', 'quest', HolyQuestOptions,
  177. 'Embark upon a holy quest'),
  178. ]
  179. class SubCommandTest(unittest.TestCase):
  180. def test_simpleSubcommand(self):
  181. o = SubCommandOptions()
  182. o.parseOptions(['--europian-swallow', 'inquisition'])
  183. self.failUnlessEqual(o['europian-swallow'], True)
  184. self.failUnlessEqual(o.subCommand, 'inquisition')
  185. self.failUnless(isinstance(o.subOptions, InquisitionOptions))
  186. self.failUnlessEqual(o.subOptions['expect'], False)
  187. self.failUnlessEqual(o.subOptions['torture-device'], 'comfy-chair')
  188. def test_subcommandWithFlagsAndOptions(self):
  189. o = SubCommandOptions()
  190. o.parseOptions(['inquisition', '--expect', '--torture-device=feather'])
  191. self.failUnlessEqual(o['europian-swallow'], False)
  192. self.failUnlessEqual(o.subCommand, 'inquisition')
  193. self.failUnless(isinstance(o.subOptions, InquisitionOptions))
  194. self.failUnlessEqual(o.subOptions['expect'], True)
  195. self.failUnlessEqual(o.subOptions['torture-device'], 'feather')
  196. def test_subcommandAliasWithFlagsAndOptions(self):
  197. o = SubCommandOptions()
  198. o.parseOptions(['inquest', '--expect', '--torture-device=feather'])
  199. self.failUnlessEqual(o['europian-swallow'], False)
  200. self.failUnlessEqual(o.subCommand, 'inquisition')
  201. self.failUnless(isinstance(o.subOptions, InquisitionOptions))
  202. self.failUnlessEqual(o.subOptions['expect'], True)
  203. self.failUnlessEqual(o.subOptions['torture-device'], 'feather')
  204. def test_anotherSubcommandWithFlagsAndOptions(self):
  205. o = SubCommandOptions()
  206. o.parseOptions(['holyquest', '--for-grail'])
  207. self.failUnlessEqual(o['europian-swallow'], False)
  208. self.failUnlessEqual(o.subCommand, 'holyquest')
  209. self.failUnless(isinstance(o.subOptions, HolyQuestOptions))
  210. self.failUnlessEqual(o.subOptions['horseback'], False)
  211. self.failUnlessEqual(o.subOptions['for-grail'], True)
  212. def test_noSubcommand(self):
  213. o = SubCommandOptions()
  214. o.parseOptions(['--europian-swallow'])
  215. self.failUnlessEqual(o['europian-swallow'], True)
  216. self.failUnlessEqual(o.subCommand, None)
  217. self.failIf(hasattr(o, 'subOptions'))
  218. def test_defaultSubcommand(self):
  219. o = SubCommandOptions()
  220. o.defaultSubCommand = 'inquest'
  221. o.parseOptions(['--europian-swallow'])
  222. self.failUnlessEqual(o['europian-swallow'], True)
  223. self.failUnlessEqual(o.subCommand, 'inquisition')
  224. self.failUnless(isinstance(o.subOptions, InquisitionOptions))
  225. self.failUnlessEqual(o.subOptions['expect'], False)
  226. self.failUnlessEqual(o.subOptions['torture-device'], 'comfy-chair')
  227. def test_subCommandParseOptionsHasParent(self):
  228. class SubOpt(usage.Options):
  229. def parseOptions(self, *a, **kw):
  230. self.sawParent = self.parent
  231. usage.Options.parseOptions(self, *a, **kw)
  232. class Opt(usage.Options):
  233. subCommands = [
  234. ('foo', 'f', SubOpt, 'bar'),
  235. ]
  236. o = Opt()
  237. o.parseOptions(['foo'])
  238. self.failUnless(hasattr(o.subOptions, 'sawParent'))
  239. self.failUnlessEqual(o.subOptions.sawParent , o)
  240. def test_subCommandInTwoPlaces(self):
  241. """
  242. The .parent pointer is correct even when the same Options class is
  243. used twice.
  244. """
  245. class SubOpt(usage.Options):
  246. pass
  247. class OptFoo(usage.Options):
  248. subCommands = [
  249. ('foo', 'f', SubOpt, 'quux'),
  250. ]
  251. class OptBar(usage.Options):
  252. subCommands = [
  253. ('bar', 'b', SubOpt, 'quux'),
  254. ]
  255. oFoo = OptFoo()
  256. oFoo.parseOptions(['foo'])
  257. oBar=OptBar()
  258. oBar.parseOptions(['bar'])
  259. self.failUnless(hasattr(oFoo.subOptions, 'parent'))
  260. self.failUnless(hasattr(oBar.subOptions, 'parent'))
  261. self.failUnlessIdentical(oFoo.subOptions.parent, oFoo)
  262. self.failUnlessIdentical(oBar.subOptions.parent, oBar)
  263. class HelpStringTest(unittest.TestCase):
  264. def setUp(self):
  265. """
  266. Instantiate a well-behaved Options class.
  267. """
  268. self.niceArgV = ("--long Alpha -n Beta "
  269. "--shortless Gamma -f --myflag "
  270. "--myparam Tofu").split()
  271. self.nice = WellBehaved()
  272. def test_noGoBoom(self):
  273. """
  274. __str__ shouldn't go boom.
  275. """
  276. try:
  277. self.nice.__str__()
  278. except Exception, e:
  279. self.fail(e)
  280. def test_whitespaceStripFlagsAndParameters(self):
  281. """
  282. Extra whitespace in flag and parameters docs is stripped.
  283. """
  284. # We test this by making sure aflag and it's help string are on the
  285. # same line.
  286. lines = [s for s in str(self.nice).splitlines() if s.find("aflag")>=0]
  287. self.failUnless(len(lines) > 0)
  288. self.failUnless(lines[0].find("flagallicious") >= 0)
  289. class PortCoerceTestCase(unittest.TestCase):
  290. """
  291. Test the behavior of L{usage.portCoerce}.
  292. """
  293. def test_validCoerce(self):
  294. """
  295. Test the answers with valid input.
  296. """
  297. self.assertEquals(0, usage.portCoerce("0"))
  298. self.assertEquals(3210, usage.portCoerce("3210"))
  299. self.assertEquals(65535, usage.portCoerce("65535"))
  300. def test_errorCoerce(self):
  301. """
  302. Test error path.
  303. """
  304. self.assertRaises(ValueError, usage.portCoerce, "")
  305. self.assertRaises(ValueError, usage.portCoerce, "-21")
  306. self.assertRaises(ValueError, usage.portCoerce, "212189")
  307. self.assertRaises(ValueError, usage.portCoerce, "foo")
  308. if __name__ == '__main__':
  309. unittest.main()