util.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. """Utility functions and classes used by nose internally.
  2. """
  3. import inspect
  4. import itertools
  5. import logging
  6. import os
  7. import re
  8. import sys
  9. import types
  10. import unittest
  11. from nose.pyversion import ClassType, TypeType, isgenerator, ismethod
  12. log = logging.getLogger('nose')
  13. ident_re = re.compile(r'^[A-Za-z_][A-Za-z0-9_.]*$')
  14. class_types = (ClassType, TypeType)
  15. skip_pattern = r"(?:\.svn)|(?:[^.]+\.py[co])|(?:.*~)|(?:.*\$py\.class)|(?:__pycache__)"
  16. try:
  17. set()
  18. set = set # make from nose.util import set happy
  19. except NameError:
  20. try:
  21. from sets import Set as set
  22. except ImportError:
  23. pass
  24. def ls_tree(dir_path="",
  25. skip_pattern=skip_pattern,
  26. indent="|-- ", branch_indent="| ",
  27. last_indent="`-- ", last_branch_indent=" "):
  28. # TODO: empty directories look like non-directory files
  29. return "\n".join(_ls_tree_lines(dir_path, skip_pattern,
  30. indent, branch_indent,
  31. last_indent, last_branch_indent))
  32. def _ls_tree_lines(dir_path, skip_pattern,
  33. indent, branch_indent, last_indent, last_branch_indent):
  34. if dir_path == "":
  35. dir_path = os.getcwd()
  36. lines = []
  37. names = os.listdir(dir_path)
  38. names.sort()
  39. dirs, nondirs = [], []
  40. for name in names:
  41. if re.match(skip_pattern, name):
  42. continue
  43. if os.path.isdir(os.path.join(dir_path, name)):
  44. dirs.append(name)
  45. else:
  46. nondirs.append(name)
  47. # list non-directories first
  48. entries = list(itertools.chain([(name, False) for name in nondirs],
  49. [(name, True) for name in dirs]))
  50. def ls_entry(name, is_dir, ind, branch_ind):
  51. if not is_dir:
  52. yield ind + name
  53. else:
  54. path = os.path.join(dir_path, name)
  55. if not os.path.islink(path):
  56. yield ind + name
  57. subtree = _ls_tree_lines(path, skip_pattern,
  58. indent, branch_indent,
  59. last_indent, last_branch_indent)
  60. for x in subtree:
  61. yield branch_ind + x
  62. for name, is_dir in entries[:-1]:
  63. for line in ls_entry(name, is_dir, indent, branch_indent):
  64. yield line
  65. if entries:
  66. name, is_dir = entries[-1]
  67. for line in ls_entry(name, is_dir, last_indent, last_branch_indent):
  68. yield line
  69. def absdir(path):
  70. """Return absolute, normalized path to directory, if it exists; None
  71. otherwise.
  72. """
  73. if not os.path.isabs(path):
  74. path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),
  75. path)))
  76. if path is None or not os.path.isdir(path):
  77. return None
  78. return path
  79. def absfile(path, where=None):
  80. """Return absolute, normalized path to file (optionally in directory
  81. where), or None if the file can't be found either in where or the current
  82. working directory.
  83. """
  84. orig = path
  85. if where is None:
  86. where = os.getcwd()
  87. if isinstance(where, list) or isinstance(where, tuple):
  88. for maybe_path in where:
  89. maybe_abs = absfile(path, maybe_path)
  90. if maybe_abs is not None:
  91. return maybe_abs
  92. return None
  93. if not os.path.isabs(path):
  94. path = os.path.normpath(os.path.abspath(os.path.join(where, path)))
  95. if path is None or not os.path.exists(path):
  96. if where != os.getcwd():
  97. # try the cwd instead
  98. path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(),
  99. orig)))
  100. if path is None or not os.path.exists(path):
  101. return None
  102. if os.path.isdir(path):
  103. # might want an __init__.py from pacakge
  104. init = os.path.join(path,'__init__.py')
  105. if os.path.isfile(init):
  106. return init
  107. elif os.path.isfile(path):
  108. return path
  109. return None
  110. def anyp(predicate, iterable):
  111. for item in iterable:
  112. if predicate(item):
  113. return True
  114. return False
  115. def file_like(name):
  116. """A name is file-like if it is a path that exists, or it has a
  117. directory part, or it ends in .py, or it isn't a legal python
  118. identifier.
  119. """
  120. return (os.path.exists(name)
  121. or os.path.dirname(name)
  122. or name.endswith('.py')
  123. or not ident_re.match(os.path.splitext(name)[0]))
  124. def func_lineno(func):
  125. """Get the line number of a function. First looks for
  126. compat_co_firstlineno, then func_code.co_first_lineno.
  127. """
  128. try:
  129. return func.compat_co_firstlineno
  130. except AttributeError:
  131. try:
  132. return func.func_code.co_firstlineno
  133. except AttributeError:
  134. return -1
  135. def isclass(obj):
  136. """Is obj a class? Inspect's isclass is too liberal and returns True
  137. for objects that can't be subclasses of anything.
  138. """
  139. obj_type = type(obj)
  140. return obj_type in class_types or issubclass(obj_type, type)
  141. # backwards compat (issue #64)
  142. is_generator = isgenerator
  143. def ispackage(path):
  144. """
  145. Is this path a package directory?
  146. >>> ispackage('nose')
  147. True
  148. >>> ispackage('unit_tests')
  149. False
  150. >>> ispackage('nose/plugins')
  151. True
  152. >>> ispackage('nose/loader.py')
  153. False
  154. """
  155. if os.path.isdir(path):
  156. # at least the end of the path must be a legal python identifier
  157. # and __init__.py[co] must exist
  158. end = os.path.basename(path)
  159. if ident_re.match(end):
  160. for init in ('__init__.py', '__init__.pyc', '__init__.pyo'):
  161. if os.path.isfile(os.path.join(path, init)):
  162. return True
  163. if sys.platform.startswith('java') and \
  164. os.path.isfile(os.path.join(path, '__init__$py.class')):
  165. return True
  166. return False
  167. def isproperty(obj):
  168. """
  169. Is this a property?
  170. >>> class Foo:
  171. ... def got(self):
  172. ... return 2
  173. ... def get(self):
  174. ... return 1
  175. ... get = property(get)
  176. >>> isproperty(Foo.got)
  177. False
  178. >>> isproperty(Foo.get)
  179. True
  180. """
  181. return type(obj) == property
  182. def getfilename(package, relativeTo=None):
  183. """Find the python source file for a package, relative to a
  184. particular directory (defaults to current working directory if not
  185. given).
  186. """
  187. if relativeTo is None:
  188. relativeTo = os.getcwd()
  189. path = os.path.join(relativeTo, os.sep.join(package.split('.')))
  190. suffixes = ('/__init__.py', '.py')
  191. for suffix in suffixes:
  192. filename = path + suffix
  193. if os.path.exists(filename):
  194. return filename
  195. return None
  196. def getpackage(filename):
  197. """
  198. Find the full dotted package name for a given python source file
  199. name. Returns None if the file is not a python source file.
  200. >>> getpackage('foo.py')
  201. 'foo'
  202. >>> getpackage('biff/baf.py')
  203. 'baf'
  204. >>> getpackage('nose/util.py')
  205. 'nose.util'
  206. Works for directories too.
  207. >>> getpackage('nose')
  208. 'nose'
  209. >>> getpackage('nose/plugins')
  210. 'nose.plugins'
  211. And __init__ files stuck onto directories
  212. >>> getpackage('nose/plugins/__init__.py')
  213. 'nose.plugins'
  214. Absolute paths also work.
  215. >>> path = os.path.abspath(os.path.join('nose', 'plugins'))
  216. >>> getpackage(path)
  217. 'nose.plugins'
  218. """
  219. src_file = src(filename)
  220. if (os.path.isdir(src_file) or not src_file.endswith('.py')) and not ispackage(src_file):
  221. return None
  222. base, ext = os.path.splitext(os.path.basename(src_file))
  223. if base == '__init__':
  224. mod_parts = []
  225. else:
  226. mod_parts = [base]
  227. path, part = os.path.split(os.path.split(src_file)[0])
  228. while part:
  229. if ispackage(os.path.join(path, part)):
  230. mod_parts.append(part)
  231. else:
  232. break
  233. path, part = os.path.split(path)
  234. mod_parts.reverse()
  235. return '.'.join(mod_parts)
  236. def ln(label):
  237. """Draw a 70-char-wide divider, with label in the middle.
  238. >>> ln('hello there')
  239. '---------------------------- hello there -----------------------------'
  240. """
  241. label_len = len(label) + 2
  242. chunk = (70 - label_len) // 2
  243. out = '%s %s %s' % ('-' * chunk, label, '-' * chunk)
  244. pad = 70 - len(out)
  245. if pad > 0:
  246. out = out + ('-' * pad)
  247. return out
  248. def resolve_name(name, module=None):
  249. """Resolve a dotted name to a module and its parts. This is stolen
  250. wholesale from unittest.TestLoader.loadTestByName.
  251. >>> resolve_name('nose.util') #doctest: +ELLIPSIS
  252. <module 'nose.util' from...>
  253. >>> resolve_name('nose.util.resolve_name') #doctest: +ELLIPSIS
  254. <function resolve_name at...>
  255. """
  256. parts = name.split('.')
  257. parts_copy = parts[:]
  258. if module is None:
  259. while parts_copy:
  260. try:
  261. log.debug("__import__ %s", name)
  262. module = __import__('.'.join(parts_copy))
  263. break
  264. except ImportError:
  265. del parts_copy[-1]
  266. if not parts_copy:
  267. raise
  268. parts = parts[1:]
  269. obj = module
  270. log.debug("resolve: %s, %s, %s, %s", parts, name, obj, module)
  271. for part in parts:
  272. obj = getattr(obj, part)
  273. return obj
  274. def split_test_name(test):
  275. """Split a test name into a 3-tuple containing file, module, and callable
  276. names, any of which (but not all) may be blank.
  277. Test names are in the form:
  278. file_or_module:callable
  279. Either side of the : may be dotted. To change the splitting behavior, you
  280. can alter nose.util.split_test_re.
  281. """
  282. norm = os.path.normpath
  283. file_or_mod = test
  284. fn = None
  285. if not ':' in test:
  286. # only a file or mod part
  287. if file_like(test):
  288. return (norm(test), None, None)
  289. else:
  290. return (None, test, None)
  291. # could be path|mod:callable, or a : in the file path someplace
  292. head, tail = os.path.split(test)
  293. if not head:
  294. # this is a case like 'foo:bar' -- generally a module
  295. # name followed by a callable, but also may be a windows
  296. # drive letter followed by a path
  297. try:
  298. file_or_mod, fn = test.split(':')
  299. if file_like(fn):
  300. # must be a funny path
  301. file_or_mod, fn = test, None
  302. except ValueError:
  303. # more than one : in the test
  304. # this is a case like c:\some\path.py:a_test
  305. parts = test.split(':')
  306. if len(parts[0]) == 1:
  307. file_or_mod, fn = ':'.join(parts[:-1]), parts[-1]
  308. else:
  309. # nonsense like foo:bar:baz
  310. raise ValueError("Test name '%s' could not be parsed. Please "
  311. "format test names as path:callable or "
  312. "module:callable." % (test,))
  313. elif not tail:
  314. # this is a case like 'foo:bar/'
  315. # : must be part of the file path, so ignore it
  316. file_or_mod = test
  317. else:
  318. if ':' in tail:
  319. file_part, fn = tail.split(':')
  320. else:
  321. file_part = tail
  322. file_or_mod = os.sep.join([head, file_part])
  323. if file_or_mod:
  324. if file_like(file_or_mod):
  325. return (norm(file_or_mod), None, fn)
  326. else:
  327. return (None, file_or_mod, fn)
  328. else:
  329. return (None, None, fn)
  330. split_test_name.__test__ = False # do not collect
  331. def test_address(test):
  332. """Find the test address for a test, which may be a module, filename,
  333. class, method or function.
  334. """
  335. if hasattr(test, "address"):
  336. return test.address()
  337. # type-based polymorphism sucks in general, but I believe is
  338. # appropriate here
  339. t = type(test)
  340. file = module = call = None
  341. if t == types.ModuleType:
  342. file = getattr(test, '__file__', None)
  343. module = getattr(test, '__name__', None)
  344. return (src(file), module, call)
  345. if t == types.FunctionType or issubclass(t, type) or t == types.ClassType:
  346. module = getattr(test, '__module__', None)
  347. if module is not None:
  348. m = sys.modules[module]
  349. file = getattr(m, '__file__', None)
  350. if file is not None:
  351. file = os.path.abspath(file)
  352. call = getattr(test, '__name__', None)
  353. return (src(file), module, call)
  354. if t == types.MethodType:
  355. cls_adr = test_address(test.im_class)
  356. return (src(cls_adr[0]), cls_adr[1],
  357. "%s.%s" % (cls_adr[2], test.__name__))
  358. # handle unittest.TestCase instances
  359. if isinstance(test, unittest.TestCase):
  360. if (hasattr(test, '_FunctionTestCase__testFunc') # pre 2.7
  361. or hasattr(test, '_testFunc')): # 2.7
  362. # unittest FunctionTestCase
  363. try:
  364. return test_address(test._FunctionTestCase__testFunc)
  365. except AttributeError:
  366. return test_address(test._testFunc)
  367. # regular unittest.TestCase
  368. cls_adr = test_address(test.__class__)
  369. # 2.5 compat: __testMethodName changed to _testMethodName
  370. try:
  371. method_name = test._TestCase__testMethodName
  372. except AttributeError:
  373. method_name = test._testMethodName
  374. return (src(cls_adr[0]), cls_adr[1],
  375. "%s.%s" % (cls_adr[2], method_name))
  376. if (hasattr(test, '__class__') and
  377. test.__class__.__module__ not in ('__builtin__', 'builtins')):
  378. return test_address(test.__class__)
  379. raise TypeError("I don't know what %s is (%s)" % (test, t))
  380. test_address.__test__ = False # do not collect
  381. def try_run(obj, names):
  382. """Given a list of possible method names, try to run them with the
  383. provided object. Keep going until something works. Used to run
  384. setup/teardown methods for module, package, and function tests.
  385. """
  386. for name in names:
  387. func = getattr(obj, name, None)
  388. if func is not None:
  389. if type(obj) == types.ModuleType:
  390. # py.test compatibility
  391. if isinstance(func, types.FunctionType):
  392. args, varargs, varkw, defaults = \
  393. inspect.getargspec(func)
  394. else:
  395. # Not a function. If it's callable, call it anyway
  396. if hasattr(func, '__call__') and not inspect.ismethod(func):
  397. func = func.__call__
  398. try:
  399. args, varargs, varkw, defaults = \
  400. inspect.getargspec(func)
  401. args.pop(0) # pop the self off
  402. except TypeError:
  403. raise TypeError("Attribute %s of %r is not a python "
  404. "function. Only functions or callables"
  405. " may be used as fixtures." %
  406. (name, obj))
  407. if len(args):
  408. log.debug("call fixture %s.%s(%s)", obj, name, obj)
  409. return func(obj)
  410. log.debug("call fixture %s.%s", obj, name)
  411. return func()
  412. def src(filename):
  413. """Find the python source file for a .pyc, .pyo or $py.class file on
  414. jython. Returns the filename provided if it is not a python source
  415. file.
  416. """
  417. if filename is None:
  418. return filename
  419. if sys.platform.startswith('java') and filename.endswith('$py.class'):
  420. return '.'.join((filename[:-9], 'py'))
  421. base, ext = os.path.splitext(filename)
  422. if ext in ('.pyc', '.pyo', '.py'):
  423. return '.'.join((base, 'py'))
  424. return filename
  425. def regex_last_key(regex):
  426. """Sort key function factory that puts items that match a
  427. regular expression last.
  428. >>> from nose.config import Config
  429. >>> from nose.pyversion import sort_list
  430. >>> c = Config()
  431. >>> regex = c.testMatch
  432. >>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.py']
  433. >>> sort_list(entries, regex_last_key(regex))
  434. >>> entries
  435. ['.', '..', 'foo.py', 'lib', 'src', 'a_test', 'test']
  436. """
  437. def k(obj):
  438. if regex.search(obj):
  439. return (1, obj)
  440. return (0, obj)
  441. return k
  442. def tolist(val):
  443. """Convert a value that may be a list or a (possibly comma-separated)
  444. string into a list. The exception: None is returned as None, not [None].
  445. >>> tolist(["one", "two"])
  446. ['one', 'two']
  447. >>> tolist("hello")
  448. ['hello']
  449. >>> tolist("separate,values, with, commas, spaces , are ,ok")
  450. ['separate', 'values', 'with', 'commas', 'spaces', 'are', 'ok']
  451. """
  452. if val is None:
  453. return None
  454. try:
  455. # might already be a list
  456. val.extend([])
  457. return val
  458. except AttributeError:
  459. pass
  460. # might be a string
  461. try:
  462. return re.split(r'\s*,\s*', val)
  463. except TypeError:
  464. # who knows...
  465. return list(val)
  466. class odict(dict):
  467. """Simple ordered dict implementation, based on:
  468. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
  469. """
  470. def __init__(self, *arg, **kw):
  471. self._keys = []
  472. super(odict, self).__init__(*arg, **kw)
  473. def __delitem__(self, key):
  474. super(odict, self).__delitem__(key)
  475. self._keys.remove(key)
  476. def __setitem__(self, key, item):
  477. super(odict, self).__setitem__(key, item)
  478. if key not in self._keys:
  479. self._keys.append(key)
  480. def __str__(self):
  481. return "{%s}" % ', '.join(["%r: %r" % (k, v) for k, v in self.items()])
  482. def clear(self):
  483. super(odict, self).clear()
  484. self._keys = []
  485. def copy(self):
  486. d = super(odict, self).copy()
  487. d._keys = self._keys[:]
  488. return d
  489. def items(self):
  490. return zip(self._keys, self.values())
  491. def keys(self):
  492. return self._keys[:]
  493. def setdefault(self, key, failobj=None):
  494. item = super(odict, self).setdefault(key, failobj)
  495. if key not in self._keys:
  496. self._keys.append(key)
  497. return item
  498. def update(self, dict):
  499. super(odict, self).update(dict)
  500. for key in dict.keys():
  501. if key not in self._keys:
  502. self._keys.append(key)
  503. def values(self):
  504. return map(self.get, self._keys)
  505. def transplant_func(func, module):
  506. """
  507. Make a function imported from module A appear as if it is located
  508. in module B.
  509. >>> from pprint import pprint
  510. >>> pprint.__module__
  511. 'pprint'
  512. >>> pp = transplant_func(pprint, __name__)
  513. >>> pp.__module__
  514. 'nose.util'
  515. The original function is not modified.
  516. >>> pprint.__module__
  517. 'pprint'
  518. Calling the transplanted function calls the original.
  519. >>> pp([1, 2])
  520. [1, 2]
  521. >>> pprint([1,2])
  522. [1, 2]
  523. """
  524. from nose.tools import make_decorator
  525. if isgenerator(func):
  526. def newfunc(*arg, **kw):
  527. for v in func(*arg, **kw):
  528. yield v
  529. else:
  530. def newfunc(*arg, **kw):
  531. return func(*arg, **kw)
  532. newfunc = make_decorator(func)(newfunc)
  533. newfunc.__module__ = module
  534. return newfunc
  535. def transplant_class(cls, module):
  536. """
  537. Make a class appear to reside in `module`, rather than the module in which
  538. it is actually defined.
  539. >>> from nose.failure import Failure
  540. >>> Failure.__module__
  541. 'nose.failure'
  542. >>> Nf = transplant_class(Failure, __name__)
  543. >>> Nf.__module__
  544. 'nose.util'
  545. >>> Nf.__name__
  546. 'Failure'
  547. """
  548. class C(cls):
  549. pass
  550. C.__module__ = module
  551. C.__name__ = cls.__name__
  552. return C
  553. def safe_str(val, encoding='utf-8'):
  554. try:
  555. return str(val)
  556. except UnicodeEncodeError:
  557. if isinstance(val, Exception):
  558. return ' '.join([safe_str(arg, encoding)
  559. for arg in val])
  560. return unicode(val).encode(encoding)
  561. if __name__ == '__main__':
  562. import doctest
  563. doctest.testmod()